package appui import ( "context" "crypto/sha1" "encoding/base64" "encoding/hex" "fmt" "os" "path/filepath" "regexp" "strings" "sync" "time" "github.com/egoist/mygo" "github.com/egoist/mygo/ui" "github.com/egoist/mygo/ui/mobile" "github.com/openchamber/openchamber-native/internal/ocapi" ) var imagePathPattern = regexp.MustCompile(`(/[^\s"'` + "`" + `()\[\]{}<>]+\.(?:png|jpg|jpeg|gif|webp|bmp|avif))`) var imageExtensions = map[string]bool{ ".png": true, ".jpg": true, ".jpeg": true, ".gif": true, ".webp": true, ".bmp": true, ".avif": true, } // imageRef is one previewable image a tool call names. type imageRef struct { Source string Label string } func isImagePath(path string) bool { return imageExtensions[strings.ToLower(filepath.Ext(path))] } // toolImages lists the images a tool call names: its file input, file // parts in its output, and paths in its text output. func (ch *chat) toolImages(p ocapi.ContentPart) []imageRef { seen := map[string]bool{} out := make([]imageRef, 0, 2) hasLabel := func(label string) bool { for _, ref := range out { if ref.Label == label { return true } } return false } add := func(source, label string) { source = strings.TrimSpace(source) if strings.HasPrefix(source, "file://") { source = strings.TrimPrefix(source, "file://") } if source == "" || seen[source] { return } if !strings.HasPrefix(source, "data:") { if strings.Contains(source, "://") { return } if !strings.HasPrefix(source, "/") { if ch.dir == "" { return } source = filepath.Join(ch.dir, source) } if !isImagePath(source) { return } if label == "" { label = filepath.Base(source) } } if label == "" { label = "图片" } seen[source] = true out = append(out, imageRef{Source: source, Label: label}) } addPath := func(path string) { path = strings.TrimSpace(path) if strings.HasPrefix(path, "file://") { path = strings.TrimPrefix(path, "file://") } else if strings.Contains(path, "://") { return } if !strings.HasPrefix(path, "/") { if ch.dir == "" { return } path = filepath.Join(ch.dir, path) } if !isImagePath(path) || hasLabel(filepath.Base(path)) { return } add(path, "") } attachments := 0 if p.State != nil { for _, group := range [][]ocapi.ContentPart{p.State.Attachments, p.State.Content} { for _, c := range group { switch c.Type { case "file": source := c.URL if source == "" { source = c.URI } if source != "" && strings.HasPrefix(c.MIME, "image/") { attachments++ add(source, c.Filename) } case "text": for _, m := range imagePathPattern.FindAllString(c.Text, -1) { addPath(m) } } } } if attachments == 0 { for _, key := range []string{"filePath", "path", "file", "file_path", "sourcePath"} { if v, ok := p.State.Input[key].(string); ok { addPath(v) } } } } return out } // ------------------------------------------------------------- preview func previewKey(source string) string { sum := sha1.Sum([]byte(source)) return hex.EncodeToString(sum[:]) } // previewDir is where fetched previews are kept. func previewDir() string { dir, err := mygo.App.Path(mygo.PathUserData) if err != nil { return "" } return filepath.Join(dir, "previews") } func (ch *chat) previewImage(ref imageRef) { ch.previewSeq++ seq := ch.previewSeq ch.previewTitle = ref.Label ch.previewPath = "" ch.previewLoading = true ch.previewOpen = true key := previewKey(ref.Source) if local, ok := ch.previewCache[key]; ok { ch.previewPath = local ch.previewLoading = false return } go func() { data, err := ch.loadPreview(ref.Source) if err != nil { ch.a.chatPost(func() { if seq != ch.previewSeq { return } ch.previewLoading = false ch.previewOpen = false ch.errText = "无法预览:" + friendlyError(err) }) return } dir := previewDir() _ = os.MkdirAll(dir, 0o700) name := strings.Map(func(r rune) rune { if r == '/' || r == '\\' || r == ':' || r < ' ' { return '_' } return r }, ref.Label) local := filepath.Join(dir, fmt.Sprintf("%d-%s", time.Now().UnixNano(), name)) if err := os.WriteFile(local, data, 0o600); err != nil { ch.a.chatPost(func() { if seq != ch.previewSeq { return } ch.previewLoading = false ch.previewOpen = false }) return } ch.a.chatPost(func() { if seq != ch.previewSeq { return } ch.previewCache[key] = local ch.previewPath = local ch.previewLoading = false }) }() } // loadPreview reads a data URL itself or asks the server for the file. func (ch *chat) loadPreview(source string) ([]byte, error) { if strings.HasPrefix(source, "data:") { comma := strings.IndexByte(source, ',') if comma < 0 { return nil, fmt.Errorf("malformed data URL") } meta := source[len("data:"):comma] if !strings.Contains(meta, ";base64") { return nil, fmt.Errorf("unsupported data URL") } return base64.StdEncoding.DecodeString(source[comma+1:]) } client := ch.a.client if client == nil { return nil, fmt.Errorf("未连接") } ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) defer cancel() data, _, err := client.RawFile(ctx, source, ch.dir) return data, err } // previewSheet shows the fetched image. func (ch *chat) previewSheet(c *ui.Context) { if !ch.previewOpen { return } mobile.Sheet(c, &ch.previewOpen, mobile.SheetOptions{Detents: []float32{0.92}}, func() { ui.Column(c).FillWidth().Padding(8, 16, 24, 16).Gap(8).Children(func() { ui.Text(c, ch.previewTitle).FontSize(16).FontWeight(600).MaxLines(2) if ch.previewLoading { ui.Column(c).Fill().Center().Height(300).Children(func() { ui.Spinner(c) }) return } bmp := loadImageFile(ch.previewPath) if bmp != nil { ui.Image(c, bmp).FillWidth().Height(420).Radius(10).Clip() } }) }) } // loadImageFile decodes a local image file into a bitmap, caching it. var imageCache sync.Map // path -> *ui.Bitmap func loadImageFile(path string) *ui.Bitmap { if path == "" { return nil } if v, ok := imageCache.Load(path); ok { return v.(*ui.Bitmap) } data, err := os.ReadFile(path) if err != nil { return nil } bmp, err := ui.DecodeBitmap(data) if err != nil { return nil } imageCache.Store(path, bmp) return bmp }