返回 DeepSeek-Reasonix
attachments_app.go
根目录 / desktop / attachments_app.go
1 package main
2
3 import (
4 "context"
5 "encoding/base64"
6 "fmt"
7 "os"
8 "path/filepath"
9 "strings"
10
11 "reasonix/internal/attachment"
12 "reasonix/internal/control"
13 )
14
15 type attachmentTarget struct {
16 tab *WorkspaceTab
17 tabID string
18 draftID string
19 draftGeneration uint64
20 root string
21 generation uint64
22 ctrl control.SessionAPI
23 ctx context.Context
24 cancel context.CancelFunc
25 ownerIdentity string
26 ownerBound bool
27 runtimeEpoch string
28 }
29
30 func (a *App) attachmentTargetForComposerTarget(composer ComposerTarget) (attachmentTarget, error) {
31 if composer.Kind != "draft" {
32 target, err := a.attachmentTargetForTab(composer.TabID)
33 if err != nil || composer.Session == nil {
34 return target, err
35 }
36 if err := validateLocalSessionRef(*composer.Session); err != nil {
37 return attachmentTarget{}, err
38 }
39 a.mu.RLock()
40 matches := target.tab != nil && target.tab.SessionID == composer.Session.SessionID
41 a.mu.RUnlock()
42 if !matches || !a.attachmentTargetCurrent(target) {
43 return attachmentTarget{}, fmt.Errorf("attachment session changed; please retry")
44 }
45 return target, nil
46 }
47 record, err := a.draftStore().Get(a.bootContext(), strings.TrimSpace(composer.DraftID))
48 if err != nil {
49 return attachmentTarget{}, err
50 }
51 root := record.WorkspaceRoot
52 if record.Scope != "project" {
53 root = globalWorkspaceRoot()
54 }
55 absRoot, err := filepath.Abs(root)
56 if err != nil {
57 return attachmentTarget{}, err
58 }
59 return attachmentTarget{
60 draftID: record.ID, draftGeneration: composer.Generation, root: absRoot,
61 ownerIdentity: fmt.Sprintf("draft:%s:%d", record.ID, composer.Generation),
62 }, nil
63 }
64
65 func attachmentWorkspaceRoot(tab *WorkspaceTab) (string, error) {
66 root := strings.TrimSpace(tab.WorkspaceRoot)
67 if root == "" {
68 if tab.Scope == "project" {
69 return "", fmt.Errorf("attachment workspace is not ready")
70 }
71 root = globalWorkspaceRoot()
72 }
73 absRoot, err := filepath.Abs(root)
74 if err != nil {
75 return "", err
76 }
77 return absRoot, nil
78 }
79
80 func (a *App) attachmentTargetForTab(tabID string) (attachmentTarget, error) {
81 tab, _ := a.tabAndCtrlByID(tabID)
82 if tab == nil {
83 return attachmentTarget{}, fmt.Errorf("attachment workspace is no longer available")
84 }
85 a.reconcileTabWithPinnedSessionMeta(tab)
86 a.mu.RLock()
87 defer a.mu.RUnlock()
88 if a.tabs[tab.ID] != tab || tab.removed {
89 return attachmentTarget{}, fmt.Errorf("attachment workspace is no longer available")
90 }
91 root, err := attachmentWorkspaceRoot(tab)
92 if err != nil {
93 return attachmentTarget{}, err
94 }
95 target := attachmentTarget{
96 tab: tab, tabID: tab.ID, root: root, generation: tab.SessionGeneration, ctrl: tab.Ctrl,
97 runtimeEpoch: a.runtimeEpochForTabLocked(tab),
98 }
99 if c, ok := tab.Ctrl.(*control.Controller); ok {
100 target.ownerIdentity = c.AttachmentOwnerIdentity()
101 target.ownerBound = strings.Trim(target.ownerIdentity, "\x00") != ""
102 }
103 if !target.ownerBound {
104 target.ownerIdentity = fmt.Sprintf("tab:%s:%d:%s", tab.ID, tab.SessionGeneration, target.runtimeEpoch)
105 }
106 return target, nil
107 }
108
109 func (a *App) attachmentTargetCurrent(target attachmentTarget) bool {
110 return a.attachmentTargetInvalidReason(target) == ""
111 }
112
113 func (a *App) attachmentTargetInvalidReason(target attachmentTarget) string {
114 if target.ctx != nil && target.ctx.Err() != nil {
115 return "attachment operation cancelled"
116 }
117 if target.tab == nil {
118 if target.draftID == "" {
119 return "missing owner"
120 }
121 record, err := a.draftStore().Get(a.bootContext(), target.draftID)
122 if err != nil || record.Status != "active" {
123 return "draft is no longer active"
124 }
125 root := record.WorkspaceRoot
126 if record.Scope != "project" {
127 root = globalWorkspaceRoot()
128 }
129 absRoot, err := filepath.Abs(root)
130 if err != nil || !sameProjectRoot(absRoot, target.root) {
131 return "workspace changed"
132 }
133 return ""
134 }
135 a.mu.RLock()
136 defer a.mu.RUnlock()
137 tab := a.tabs[target.tabID]
138 if tab != target.tab || tab.removed {
139 return "tab closed"
140 }
141 if tab.SessionGeneration != target.generation {
142 return "session generation changed"
143 }
144 if tab.Ctrl != target.ctrl {
145 return "runtime changed"
146 }
147 if a.runtimeEpochForTabLocked(tab) != target.runtimeEpoch {
148 return "runtime epoch changed"
149 }
150 if c, ok := tab.Ctrl.(*control.Controller); ok && target.ownerBound && c.AttachmentOwnerIdentity() != target.ownerIdentity {
151 return "attachment owner changed"
152 }
153 root, err := attachmentWorkspaceRoot(tab)
154 if err != nil || !sameProjectRoot(root, target.root) {
155 return "workspace changed"
156 }
157 return ""
158 }
159
160 func (a *App) finishAttachmentWrite(target attachmentTarget, rel string, err error) (string, error) {
161 if err != nil {
162 return "", err
163 }
164 if a.attachmentIOHook != nil {
165 a.attachmentIOHook()
166 }
167 if a.attachmentTargetCurrent(target) {
168 return rel, nil
169 }
170 if isAttachmentRefPath(rel) {
171 _ = control.RemoveStoredAttachment(target.root, rel)
172 }
173 return "", fmt.Errorf("attachment workspace changed while saving; please retry")
174 }
175
176 func isAttachmentRefPath(path string) bool {
177 path = filepath.ToSlash(filepath.Clean(filepath.FromSlash(path)))
178 return strings.HasPrefix(path, ".reasonix/attachments/")
179 }
180
181 // SavePastedImage stores a browser clipboard image data URL under the active
182 // tab's workspace .reasonix/attachments and returns the relative @-reference path.
183 func (a *App) SavePastedImage(dataURL string) (string, error) {
184 target, err := a.attachmentTargetForTab("")
185 if err != nil {
186 return "", err
187 }
188 rel, saveErr := control.SaveImageDataURLInRoot(target.root, dataURL)
189 return a.finishAttachmentWrite(target, rel, saveErr)
190 }
191
192 func (a *App) SavePastedImageForTab(tabID, dataURL string) (string, error) {
193 target, err := a.attachmentTargetForTab(tabID)
194 if err != nil {
195 return "", err
196 }
197 rel, saveErr := control.SaveImageDataURLInRoot(target.root, dataURL)
198 return a.finishAttachmentWrite(target, rel, saveErr)
199 }
200
201 // SaveClipboardImage reads the native OS clipboard image under the active tab's
202 // workspace .reasonix/attachments and returns the relative @-reference path.
203 func (a *App) SaveClipboardImage() (string, error) {
204 target, err := a.attachmentTargetForTab("")
205 if err != nil {
206 return "", err
207 }
208 rel, saveErr := control.SaveClipboardImageInRoot(target.root)
209 return a.finishAttachmentWrite(target, rel, saveErr)
210 }
211
212 func (a *App) SaveClipboardImageForTab(tabID string) (string, error) {
213 target, err := a.attachmentTargetForTab(tabID)
214 if err != nil {
215 return "", err
216 }
217 rel, saveErr := control.SaveClipboardImageInRoot(target.root)
218 return a.finishAttachmentWrite(target, rel, saveErr)
219 }
220
221 // SavePastedFile stores a dropped non-image file (the browser exposes its bytes
222 // as a data URL but not a real path) under the active tab's workspace
223 // .reasonix/attachments and returns the relative @-reference path.
224 func (a *App) SavePastedFile(name, dataURL string) (string, error) {
225 target, err := a.attachmentTargetForTab("")
226 if err != nil {
227 return "", err
228 }
229 rel, saveErr := control.SaveAttachmentDataURLInRoot(target.root, name, dataURL)
230 return a.finishAttachmentWrite(target, rel, saveErr)
231 }
232
233 func (a *App) SavePastedFileForTab(tabID, name, dataURL string) (string, error) {
234 target, err := a.attachmentTargetForTab(tabID)
235 if err != nil {
236 return "", err
237 }
238 rel, saveErr := control.SaveAttachmentDataURLInRoot(target.root, name, dataURL)
239 return a.finishAttachmentWrite(target, rel, saveErr)
240 }
241
242 // AttachmentDataURL returns a safe data URL for a stored image attachment.
243 func (a *App) AttachmentDataURL(path string) (string, error) {
244 target, err := a.attachmentTargetForTab("")
245 if err != nil {
246 return "", err
247 }
248 return a.attachmentDataURLForTarget(target, path)
249 }
250
251 func (a *App) AttachmentDataURLForTab(tabID, path string) (string, error) {
252 target, err := a.attachmentTargetForTab(tabID)
253 if err != nil {
254 return "", err
255 }
256 return a.attachmentDataURLForTarget(target, path)
257 }
258
259 func (a *App) attachmentDataURLForTarget(target attachmentTarget, path string) (string, error) {
260 dataURL, readErr := control.ImageDataURLInRoot(target.root, path)
261 if readErr != nil {
262 return "", readErr
263 }
264 if a.attachmentIOHook != nil {
265 a.attachmentIOHook()
266 }
267 if !a.attachmentTargetCurrent(target) {
268 return "", fmt.Errorf("attachment workspace changed while reading; please retry")
269 }
270 return dataURL, nil
271 }
272
273 // DroppedItem is one OS-dropped file resolved into a composer context entry.
274 type DroppedItem struct {
275 Kind string `json:"kind"`
276 Path string `json:"path"`
277 IsDir bool `json:"isDir,omitempty"`
278 DisplayPath string `json:"displayPath,omitempty"`
279 PreviewURL string `json:"previewUrl,omitempty"`
280 }
281
282 const attachmentsCapabilityV1 = "attachments-v1"
283
284 type DraftImageView struct {
285 DraftID string `json:"draftId"`
286 Path string `json:"path,omitempty"`
287 DisplayName string `json:"displayName"`
288 MIME string `json:"mime"`
289 Width int `json:"width"`
290 Height int `json:"height"`
291 Bytes int64 `json:"bytes"`
292 }
293
294 func (a *App) StageImageForTab(tabID, operationID, displayName, mime, dataURL string) (DraftImageView, error) {
295 target, err := a.attachmentTargetForTab(tabID)
296 if err != nil {
297 return DraftImageView{}, err
298 }
299 return a.stageImageForTarget(target, displayName, mime, dataURL)
300 }
301
302 func (a *App) stageImageForTarget(target attachmentTarget, displayName, mime, dataURL string) (DraftImageView, error) {
303 identified, ok := target.ctrl.(*control.Controller)
304 if !ok {
305 return DraftImageView{}, fmt.Errorf("unsupported: %s", attachmentsCapabilityV1)
306 }
307 draft, err := identified.StageImage(a.attachmentOperationContext(target), displayName, mime, dataURL)
308 if a.attachmentIOHook != nil {
309 a.attachmentIOHook()
310 }
311 if !a.attachmentTargetCurrent(target) {
312 identified.ReleaseDraftImage(draft.ID)
313 return DraftImageView{}, fmt.Errorf("attachment workspace changed while saving; please retry")
314 }
315 if err != nil {
316 return DraftImageView{}, err
317 }
318 return draftImageView(draft), nil
319 }
320
321 func (a *App) ReadDraftImageForTab(tabID, draftID string) (string, error) {
322 target, err := a.attachmentTargetForTab(tabID)
323 if err != nil {
324 return "", err
325 }
326 return a.readDraftImageForTarget(target, draftID)
327 }
328
329 func (a *App) readDraftImageForTarget(target attachmentTarget, draftID string) (string, error) {
330 identified, ok := target.ctrl.(*control.Controller)
331 if !ok {
332 return "", fmt.Errorf("unsupported: %s", attachmentsCapabilityV1)
333 }
334 draft, raw, err := identified.ReadDraftImage(a.attachmentOperationContext(target), draftID)
335 if a.attachmentIOHook != nil {
336 a.attachmentIOHook()
337 }
338 if !a.attachmentTargetCurrent(target) {
339 return "", fmt.Errorf("attachment workspace changed while reading; please retry")
340 }
341 if err != nil {
342 return "", err
343 }
344 return attachment.DataURL(draft.MIME, raw), nil
345 }
346
347 func (a *App) ReadSessionAttachmentForTab(tabID, digest string, offset int64) (SessionHistoryContentChunk, error) {
348 target, err := a.attachmentTargetForTab(tabID)
349 if err != nil {
350 return SessionHistoryContentChunk{}, err
351 }
352 ctx := a.attachmentContext()
353 var cancel context.CancelFunc
354 if controller, ok := target.ctrl.(*control.Controller); ok {
355 ctx, cancel = controller.NewAttachmentOperationContext(ctx)
356 } else {
357 ctx, cancel = context.WithCancel(ctx)
358 }
359 defer cancel()
360 target.ctx = ctx
361 if err := ctx.Err(); err != nil {
362 return SessionHistoryContentChunk{}, err
363 }
364 query, sessionRef, err := a.canonicalSessionQuery(tabID)
365 if err != nil {
366 return SessionHistoryContentChunk{}, err
367 }
368 if !a.attachmentTargetCurrent(target) {
369 return SessionHistoryContentChunk{}, fmt.Errorf("attachment workspace changed while reading; please retry")
370 }
371 data, total, err := query.ReadSessionAttachment(ctx, sessionRef, digest, offset, sessionHistoryContentChunkBytes)
372 if a.attachmentIOHook != nil {
373 a.attachmentIOHook()
374 }
375 if !a.attachmentTargetCurrent(target) {
376 return SessionHistoryContentChunk{}, fmt.Errorf("attachment workspace changed while reading; please retry")
377 }
378 if err != nil {
379 return SessionHistoryContentChunk{}, err
380 }
381 next := offset + int64(len(data))
382 return SessionHistoryContentChunk{
383 Data: base64.StdEncoding.EncodeToString(data),
384 NextOffset: next,
385 Done: next >= total,
386 }, nil
387 }
388
389 func (a *App) ReleaseDraftImageForTab(tabID, draftID string) error {
390 target, err := a.attachmentTargetForTab(tabID)
391 if err != nil {
392 return err
393 }
394 identified, ok := target.ctrl.(*control.Controller)
395 if !ok {
396 return fmt.Errorf("unsupported: %s", attachmentsCapabilityV1)
397 }
398 identified.ReleaseDraftImage(draftID)
399 return nil
400 }
401
402 func draftImageView(draft attachment.DraftCredential) DraftImageView {
403 return DraftImageView{
404 DraftID: draft.ID,
405 DisplayName: draft.DisplayName,
406 MIME: draft.MIME,
407 Width: draft.Width,
408 Height: draft.Height,
409 Bytes: draft.Bytes,
410 }
411 }
412
413 func (a *App) AttachDropped(path string) (DroppedItem, error) {
414 return a.attachDroppedForTab("", path)
415 }
416
417 func (a *App) AttachDroppedForTab(tabID, path string) (DroppedItem, error) {
418 return a.attachDroppedForTab(tabID, path)
419 }
420
421 func (a *App) attachDroppedForTab(tabID, path string) (DroppedItem, error) {
422 target, err := a.attachmentTargetForTab(tabID)
423 if err != nil {
424 return DroppedItem{}, err
425 }
426 return a.attachDroppedForTarget(target, path)
427 }
428
429 func (a *App) attachDroppedForTarget(target attachmentTarget, path string) (DroppedItem, error) {
430 info, err := os.Lstat(path)
431 if err != nil {
432 return DroppedItem{}, err
433 }
434 if info.Mode()&os.ModeSymlink != 0 || (!info.IsDir() && !info.Mode().IsRegular()) {
435 return DroppedItem{}, fmt.Errorf("dropped path must be a regular file or directory")
436 }
437 if isImageExt(path) {
438 if rel, saveErr := control.SaveImageFileInRoot(target.root, path); saveErr == nil {
439 rel, saveErr = a.finishAttachmentWrite(target, rel, nil)
440 if saveErr != nil {
441 return DroppedItem{}, saveErr
442 }
443 preview, previewErr := a.attachmentDataURLForTarget(target, rel)
444 if previewErr != nil {
445 _ = control.RemoveStoredAttachment(target.root, rel)
446 return DroppedItem{}, previewErr
447 }
448 return DroppedItem{Kind: "attachment", Path: rel, PreviewURL: preview}, nil
449 } else {
450 return DroppedItem{}, saveErr
451 }
452 }
453 if rel, ok := workspaceRelativeIn(path, target.root); ok {
454 if !a.attachmentTargetCurrent(target) {
455 return DroppedItem{}, fmt.Errorf("attachment workspace changed while reading; please retry")
456 }
457 return DroppedItem{Kind: "workspace", Path: rel, IsDir: info.IsDir()}, nil
458 }
459 if target.draftID != "" {
460 abs, err := filepath.Abs(path)
461 if err != nil {
462 return DroppedItem{}, err
463 }
464 if !info.IsDir() {
465 abs, err = filepath.EvalSymlinks(abs)
466 if err != nil {
467 return DroppedItem{}, err
468 }
469 abs = filepath.ToSlash(abs)
470 }
471 return DroppedItem{Kind: "workspace", Path: abs, IsDir: info.IsDir(), DisplayPath: filepath.ToSlash(abs)}, nil
472 }
473 if info.IsDir() {
474 if target.tab == nil || target.ctrl == nil {
475 return DroppedItem{}, fmt.Errorf("workspace is not ready")
476 }
477 if err := a.ensureTabControllerWorkspace(target.tab); err != nil {
478 return DroppedItem{}, err
479 }
480 refreshed, err := a.attachmentTargetForTab(target.tabID)
481 if err != nil || refreshed.tab != target.tab || refreshed.generation != target.generation ||
482 !sameProjectRoot(refreshed.root, target.root) {
483 return DroppedItem{}, fmt.Errorf("attachment workspace is no longer available")
484 }
485 target = refreshed
486 ctrl := target.ctrl
487 if ctrl == nil || !a.attachmentTargetCurrent(target) {
488 return DroppedItem{}, fmt.Errorf("attachment workspace is no longer available")
489 }
490 token, displayPath, err := ctrl.RegisterExternalFolderRef(path)
491 if err != nil {
492 return DroppedItem{}, err
493 }
494 return DroppedItem{Kind: "workspace", Path: token, IsDir: true, DisplayPath: displayPath}, nil
495 }
496 if target.ctrl == nil || !a.attachmentTargetCurrent(target) {
497 return DroppedItem{}, fmt.Errorf("workspace is not ready")
498 }
499 token, displayPath, err := target.ctrl.RegisterExternalFileRef(path)
500 if err != nil {
501 return DroppedItem{}, err
502 }
503 if !a.attachmentTargetCurrent(target) {
504 return DroppedItem{}, fmt.Errorf("attachment workspace changed while reading; please retry")
505 }
506 return DroppedItem{Kind: "workspace", Path: token, DisplayPath: displayPath}, nil
507 }
508
509 func isImageExt(path string) bool {
510 switch strings.ToLower(filepath.Ext(path)) {
511 case ".png", ".jpg", ".jpeg", ".gif", ".webp":
512 return true
513 }
514 return false
515 }
516
517 func workspaceRelativeIn(path, workspaceRoot string) (string, bool) {
518 root := workspaceRoot
519 if !filepath.IsAbs(root) {
520 abs, err := filepath.Abs(root)
521 if err != nil {
522 return "", false
523 }
524 root = abs
525 }
526 rel, err := filepath.Rel(root, path)
527 if err != nil {
528 return "", false
529 }
530 if rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) || filepath.IsAbs(rel) {
531 return "", false
532 }
533 return filepath.ToSlash(rel), true
534 }
535
535 lines GO