Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.
feat(voice): post Live cards through the bundled TeamHub CLI
LeoXingb54d81fee114
diff --git a/apps/computer/local-daemon/cmd/linger-computer-daemon/main.go b/apps/computer/local-daemon/cmd/linger-computer-daemon/main.goindex 98dc884e..b28305ef 100644--- a/apps/computer/local-daemon/cmd/linger-computer-daemon/main.go+++ b/apps/computer/local-daemon/cmd/linger-computer-daemon/main.go@@ -296,6 +296,7 @@ func run(args []string) (resultErr error) {BrowserConnections: browserConnections, Owners: owners,ComputerPermissions: localtools.NewComputerPermissions(permissionOptions),CLICredentials: cliCredentials,+ TeamHubCLIBin: teamhubBin,ModelInvoker: provider.ModelInvoker{TempBase: operationTempBase,ClaudeConfigRoot: filepath.Join(computer.StateDirectory, "model-invoke", "claude", ".claude"),diff --git a/apps/computer/local-daemon/internal/daemon/daemon.go b/apps/computer/local-daemon/internal/daemon/daemon.goindex 4e2d03e8..34ccb293 100644--- a/apps/computer/local-daemon/internal/daemon/daemon.go+++ b/apps/computer/local-daemon/internal/daemon/daemon.go@@ -44,6 +44,9 @@ type Options struct {ComputerPermissions ComputerPermissionsOwners []ComputerOwnerCLICredentials *clicredential.Store+ // TeamHubCLIBin is the bundled TeamHub CLI directory; live voice cards+ // post through it as the Agent.+ TeamHubCLIBin stringComputerID stringOperationResolver OperationResolverRetryDelay func(attempt int) time.Duration@@ -99,6 +102,7 @@ type Daemon struct {computerPermissions ComputerPermissionsowners []ComputerOwnercliCredentials *clicredential.Store+ teamhubCLIBin stringonModelUnavailable func(runtimeType, modelID string)openMCPProxies func(context.Context, json.RawMessage, mcpproxy.OperationIdentity) (*mcpproxy.Set, error)connectionEpoch uint64@@ -242,6 +246,7 @@ func New(options Options) (*Daemon, error) {computerPermissions: options.ComputerPermissions,owners: options.Owners,cliCredentials: options.CLICredentials,+ teamhubCLIBin: options.TeamHubCLIBin,openMCPProxies: mcpproxy.Open,onModelUnavailable: options.OnModelUnavailable,}, nildiff --git a/apps/computer/local-daemon/internal/daemon/playground_tools.go b/apps/computer/local-daemon/internal/daemon/playground_tools.goindex dec9d9f4..57495851 100644--- a/apps/computer/local-daemon/internal/daemon/playground_tools.go+++ b/apps/computer/local-daemon/internal/daemon/playground_tools.go@@ -1,37 +1,23 @@package daemonimport (+ "bytes""context"- "crypto/sha256"- "encoding/hex""encoding/json""errors"- "fmt"- "io""io/fs"- "mime/multipart"- "net/http""os"- "path"- "strconv"+ "os/exec"+ "path/filepath"+ "runtime""strings""github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/linger/clicredential"lingercontext "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/linger/context")-const (- // The Agent message commit route's limits: per file and per message.- maxCardFileBytes = 50 << 20- maxCardTotalBytes = 512 << 20- maxCardFiles = 5-)--// playgroundCardClient posts cards to TeamHub; the Computer tool's deadline-// bounds each request, and a redirect is never followed with the credential.-var playgroundCardClient = &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error {- return http.ErrUseLastResponse-}}+// maxCardFiles is how many files one card carries.+const maxCardFiles = 5// playgroundFailure is a result TeamHub tells the live model as an error code.type playgroundFailure struct{ code, detail string }@@ -46,10 +32,8 @@ type playgroundRequest struct {}type playgroundCardFile struct {- Folder lingercontext.PlaygroundFolder `json:"folder"`- Path string `json:"path"`- RepresentationFormat string `json:"representation_format"`- MediaType string `json:"media_type"`+ Folder lingercontext.PlaygroundFolder `json:"folder"`+ Path string `json:"path"`}type playgroundCard struct {@@ -115,155 +99,120 @@ func decodes(arguments json.RawMessage, target any) bool {return json.Unmarshal(arguments, target) == nil}-type openedCardFile struct {- file *os.File- upload map[string]any- size int64- uploadID string-}--// sendPlaygroundCard reads the card's files where the Agent wrote them and-// commits the card through the Agent API, the request `teamhub message card-// --attach` sends. The operation ID makes a repeated call the same message.+// sendPlaygroundCard posts a card with files where the Agent wrote them by+// running `teamhub message card --attach` as the Agent, so a card from the+// live voice is the one a Meta posts, Markdown images included. The+// operation ID makes a repeated call the same message.func (d *Daemon) sendPlaygroundCard(ctx context.Context, tenantID, agentID string, card playgroundCard) (map[string]any, error) {- title := strings.TrimSpace(card.Title)- if card.OperationID == "" || !strings.HasPrefix(card.InboxID, "room:") || title == "" || title != card.Title ||- len([]rune(title)) > 120 || strings.ContainsAny(title, "\r\n") || strings.TrimSpace(card.Content) == "" || len(card.Files) > maxCardFiles {- return nil, &playgroundFailure{"invalid_card", "A card needs a one-line title, content and at most 5 files."}- }- files := make([]openedCardFile, 0, len(card.Files))- defer func() {- for _, opened := range files {- _ = opened.file.Close()- }- }()- var total int64- for index, requested := range card.Files {- file, info, err := d.contextViews.OpenPlaygroundFile(ctx, tenantID, agentID, requested.Folder, requested.Path)- if err != nil {- return nil, err- }- opened, err := prepareCardFile(file, info.Size(), index, requested)- files = append(files, opened)+ roomID, isRoom := strings.CutPrefix(card.InboxID, "room:")+ if card.OperationID == "" || !isRoom || roomID == "" || strings.TrimSpace(card.Title) == "" ||+ strings.TrimSpace(card.Content) == "" || len(card.Files) > maxCardFiles {+ return nil, &playgroundFailure{"invalid_card", "A card needs a title, content and at most 5 files."}+ }+ arguments := []string{"message", "card", "--title", card.Title, "--content", card.Content}+ for _, requested := range card.Files {+ filename, err := d.contextViews.PlaygroundFilePath(ctx, tenantID, agentID, requested.Folder, requested.Path)if err != nil {return nil, err}- if total += info.Size(); total > maxCardTotalBytes {- return nil, &playgroundFailure{"files_too_large", "The files are over 512 MiB together."}- }+ arguments = append(arguments, "--attach", filename)}- profile, token, err := d.agentCLICredential(tenantID, agentID)+ arguments = append(arguments, "--operation-id", card.OperationID, "--json")+ installation, err := d.agentCLICredential(tenantID, agentID)if err != nil {return nil, err}- return commitCard(ctx, profile, token, card, files)+ return d.runCardCLI(ctx, installation, roomID, arguments)}-// prepareCardFile hashes one opened file for its upload entry.-func prepareCardFile(file *os.File, size int64, index int, requested playgroundCardFile) (openedCardFile, error) {- opened := openedCardFile{file: file, size: size, uploadID: "upload_" + strconv.Itoa(index)}- if size > maxCardFileBytes {- return opened, &playgroundFailure{"file_too_large", path.Base(requested.Path) + " is over 50 MiB."}- }- hash := sha256.New()- if _, err := io.Copy(hash, file); err != nil {- return opened, err- }- if _, err := file.Seek(0, io.SeekStart); err != nil {- return opened, err+// runCardCLI runs the bundled CLI with a profile of its own that targets the+// card's Room. The credential stays in its file; the CLI reads it.+func (d *Daemon) runCardCLI(ctx context.Context, installation clicredential.Installation, roomID string, arguments []string) (map[string]any, error) {+ if d.teamhubCLIBin == "" {+ return nil, &playgroundFailure{"cli_unavailable", "This Computer has no TeamHub CLI; update the Computer."}}- opened.upload = map[string]any{- "upload_id": opened.uploadID, "filename": path.Base(requested.Path),- "representation_format": requested.RepresentationFormat, "media_type": requested.MediaType,- "size_bytes": size, "sha256": hex.EncodeToString(hash.Sum(nil)),+ program := filepath.Join(d.teamhubCLIBin, "teamhub")+ if runtime.GOOS == "windows" {+ program += ".exe"}- return opened, nil-}--// commitCard posts the card and its prepared files as the Agent.-func commitCard(ctx context.Context, profile clicredential.Profile, token string, card playgroundCard, files []openedCardFile) (map[string]any, error) {- segments := []map[string]any{{"type": "text", "content": card.Content}}- uploads := make([]map[string]any, 0, len(files))- for _, opened := range files {- segments = append(segments, map[string]any{"type": "document", "upload_id": opened.uploadID})- uploads = append(uploads, opened.upload)- }- invocation := sha256.Sum256([]byte(card.OperationID))- metadata, err := json.Marshal(map[string]any{- "invocation_id": "agent-invocation-sha256:" + hex.EncodeToString(invocation[:]),- "inbox_id": card.InboxID, "card_title": card.Title, "segments": segments, "uploads": uploads,- })+ home, err := os.MkdirTemp("", "linger-live-card-")if err != nil {return nil, err}- body, writer := io.Pipe()- form := multipart.NewWriter(writer)- go func() {- _ = writer.CloseWithError(writeCardForm(form, metadata, files))- }()- defer body.Close()- request, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimSuffix(profile.URL, "/")+"/api/agent/v1/messages/commit", body)+ defer os.RemoveAll(home)+ config, err := json.Marshal(map[string]any{"version": 1, "default_profile": "live", "profiles": map[string]any{"live": map[string]any{+ "url": installation.Profile.URL, "token_file": installation.CredentialPath,+ "tenant_id": installation.Profile.TenantID, "agent_id": installation.Profile.AgentID,+ "scope": map[string]string{"kind": "room", "id": roomID},+ }}})if err != nil {return nil, err}- request.Header.Set("Authorization", "Bearer "+token)- request.Header.Set("Content-Type", form.FormDataContentType())- request.Header.Set("X-TeamHub-Expected-Tenant-Id", profile.TenantID)- request.Header.Set("X-TeamHub-Expected-Agent-Id", profile.AgentID)- request.Header.Set("X-TeamHub-Operation-Id", card.OperationID)- response, err := playgroundCardClient.Do(request)- if err != nil {- // The request may have reached TeamHub; only the same operation may retry.+ configPath := filepath.Join(home, "config.json")+ if err := os.WriteFile(configPath, config, 0o600); err != nil {+ return nil, err+ }+ command := exec.CommandContext(ctx, program, arguments...)+ command.Dir = home+ command.Env = append(cardCLIEnvironment(os.Environ()), "TEAMHUB_CONFIG="+configPath, "TEAMHUB_PROFILE=live")+ var stdout, stderr bytes.Buffer+ command.Stdout, command.Stderr = &stdout, &stderr+ runErr := command.Run()+ if ctx.Err() != nil {return nil, &playgroundFailure{"outcome_unknown", "The card may have been posted; check the chat before trying again."}}- defer response.Body.Close()- return cardCommitResult(response)+ if runErr != nil {+ var exit *exec.ExitError+ if !errors.As(runErr, &exit) {+ return nil, runErr+ }+ return nil, cardCLIFailure(stderr.Bytes())+ }+ return cardCommitResult(stdout.Bytes())}-func writeCardForm(form *multipart.Writer, metadata []byte, files []openedCardFile) error {- if err := form.WriteField("metadata", string(metadata)); err != nil {- return err- }- for _, opened := range files {- part, err := form.CreateFormFile("file", opened.uploadID)- if err != nil {- return err- }- // A file that grew since it was hashed fails TeamHub's size check.- if _, err := io.Copy(part, io.LimitReader(opened.file, opened.size+1)); err != nil {- return err+// cardCLIEnvironment is the daemon's environment without TeamHub settings,+// so only the card's own profile applies; proxies still reach the CLI.+func cardCLIEnvironment(environment []string) []string {+ kept := make([]string, 0, len(environment))+ for _, entry := range environment {+ if !strings.HasPrefix(strings.ToUpper(entry), "TEAMHUB_") {+ kept = append(kept, entry)}}- return form.Close()+ return kept+}++// cardCLIFailure tells the live model why the CLI did not post the card. A+// failure whose outcome the CLI could not know is never reported as refused.+func cardCLIFailure(stderr []byte) error {+ var envelope struct {+ Error struct {+ Code string `json:"code"`+ Message string `json:"message"`+ } `json:"error"`+ }+ _ = json.Unmarshal(bytes.TrimSpace(stderr), &envelope)+ switch envelope.Error.Code {+ case "", "connection_failed", "timeout", "outcome_unknown", "external_outcome_unknown":+ return &playgroundFailure{"outcome_unknown", "The card may have been posted; check the chat before trying again."}+ }+ return &playgroundFailure{"upload_failed", strings.TrimSpace(envelope.Error.Code + ": " + envelope.Error.Message)}}// cardCommitResult is the posted card's message and the Documents its files// became, in file order.-func cardCommitResult(response *http.Response) (map[string]any, error) {- data, err := io.ReadAll(io.LimitReader(response.Body, 8<<20))- if err != nil {- return nil, &playgroundFailure{"outcome_unknown", "The card may have been posted; check the chat before trying again."}- }- if response.StatusCode != http.StatusOK {- var envelope struct {- Error struct {- Code string `json:"code"`- } `json:"error"`- }- _ = json.Unmarshal(data, &envelope)- return nil, &playgroundFailure{"upload_failed", strings.TrimSpace(fmt.Sprintf("TeamHub answered HTTP %d %s", response.StatusCode, envelope.Error.Code))}- }+func cardCommitResult(stdout []byte) (map[string]any, error) {var committed struct {MessageID string `json:"message_id"`Resources []struct {- Kind string `json:"kind"`- SegmentIndex int `json:"segment_index"`- DocumentID string `json:"document_id"`- Name string `json:"name"`+ Kind string `json:"kind"`+ DocumentID string `json:"document_id"`+ Name string `json:"name"`} `json:"resources"`}- if err := json.Unmarshal(data, &committed); err != nil || committed.MessageID == "" {- return nil, &playgroundFailure{"outcome_unknown", "TeamHub's answer could not be read; check the chat before trying again."}+ if json.Unmarshal(bytes.TrimSpace(stdout), &committed) != nil || committed.MessageID == "" {+ return nil, &playgroundFailure{"outcome_unknown", "The CLI's answer could not be read; check the chat before trying again."}}documents := make([]map[string]any, 0, len(committed.Resources))for _, resource := range committed.Resources {@@ -274,22 +223,15 @@ func cardCommitResult(response *http.Response) (map[string]any, error) {return map[string]any{"message_id": committed.MessageID, "documents": documents}, nil}-// agentCLICredential is the TeamHub CLI profile and token the Agent Service-// pushed to this Computer for the Agent.-func (d *Daemon) agentCLICredential(tenantID, agentID string) (clicredential.Profile, string, error) {+// agentCLICredential is the TeamHub CLI profile and credential file the+// Agent Service pushed to this Computer for the Agent.+func (d *Daemon) agentCLICredential(tenantID, agentID string) (clicredential.Installation, error) {if d.cliCredentials == nil {- return clicredential.Profile{}, "", &playgroundFailure{"agent_unavailable", "This Computer holds no TeamHub credential for the Agent."}+ return clicredential.Installation{}, &playgroundFailure{"agent_unavailable", "This Computer holds no TeamHub credential for the Agent."}}installation, err := d.cliCredentials.Lookup(tenantID, agentID)if errors.Is(err, clicredential.ErrNotInstalled) {- return clicredential.Profile{}, "", &playgroundFailure{"agent_unavailable", "This Computer holds no TeamHub credential for the Agent."}- }- if err != nil {- return clicredential.Profile{}, "", err- }- token, err := os.ReadFile(installation.CredentialPath)- if err != nil {- return clicredential.Profile{}, "", err+ return clicredential.Installation{}, &playgroundFailure{"agent_unavailable", "This Computer holds no TeamHub credential for the Agent."}}- return installation.Profile, strings.TrimSpace(string(token)), nil+ return installation, err}diff --git a/apps/computer/local-daemon/internal/daemon/playground_tools_test.go b/apps/computer/local-daemon/internal/daemon/playground_tools_test.goindex 796cb108..a7921feb 100644--- a/apps/computer/local-daemon/internal/daemon/playground_tools_test.go+++ b/apps/computer/local-daemon/internal/daemon/playground_tools_test.go@@ -1,123 +1,102 @@package daemonimport (- "bytes"- "crypto/sha256"- "encoding/hex""encoding/json""errors"- "io"- "net/http"- "net/http/httptest""os""path/filepath"+ "runtime""strings""testing""github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/linger/clicredential")-func openTestCardFile(t *testing.T, name string, content []byte, index int) openedCardFile {+// fakeCardCLI installs a teamhub program that records how it was run and+// answers with stdout, stderr and an exit code.+func fakeCardCLI(t *testing.T, stdout, stderr string, exit int) (directory, record string) {t.Helper()- filename := filepath.Join(t.TempDir(), name)- if err := os.WriteFile(filename, content, 0o600); err != nil {- t.Fatal(err)+ if runtime.GOOS == "windows" {+ t.Skip("the fake CLI is a shell script")}- file, err := os.Open(filename)- if err != nil {- t.Fatal(err)- }- t.Cleanup(func() { _ = file.Close() })- opened, err := prepareCardFile(file, int64(len(content)), index, playgroundCardFile{Path: "out/" + name, RepresentationFormat: "png", MediaType: "image/png"})- if err != nil {+ directory = t.TempDir()+ record = filepath.Join(t.TempDir(), "record")+ script := "#!/bin/sh\n" ++ "{ printf '%s\\n' \"$@\"; echo ---; echo \"$TEAMHUB_PROFILE\"; cat \"$TEAMHUB_CONFIG\"; echo; echo ---; env | grep -c '^TEAMHUB_SECRET=' ; } > '" + record + "'\n" ++ "printf '%s' '" + stdout + "'\nprintf '%s' '" + stderr + "' >&2\nexit " + string(rune('0'+exit)) + "\n"+ if err := os.WriteFile(filepath.Join(directory, "teamhub"), []byte(script), 0o755); err != nil {t.Fatal(err)}- return opened+ return directory, record}-func TestPlaygroundCardCommitsTheFilesAsTheAgent(t *testing.T) {- image := bytes.Repeat([]byte{0x89, 'P', 'N', 'G'}, 300_000)- var metadata map[string]any- parts := map[string][]byte{}- server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {- if request.URL.Path != "/api/agent/v1/messages/commit" || request.Header.Get("Authorization") != "Bearer token-1" ||- request.Header.Get("X-TeamHub-Expected-Agent-Id") != "agent-1" || request.Header.Get("X-TeamHub-Operation-Id") != "voice-call-1" {- http.Error(writer, `{"error":{"code":"FORBIDDEN"}}`, http.StatusForbidden)- return- }- reader, err := request.MultipartReader()- if err != nil {- t.Error(err)- return- }- for {- part, err := reader.NextPart()- if errors.Is(err, io.EOF) {- break- }- if err != nil {- t.Error(err)- return- }- data, _ := io.ReadAll(part)- if part.FormName() == "metadata" {- _ = json.Unmarshal(data, &metadata)- continue- }- parts[part.FileName()] = data- }- _, _ = writer.Write([]byte(`{"accepted":true,"target":{"type":"room","id":"room-1"},"inbox_id":"room:room-1","message_id":"message-1","duplicate_request":false,"resources":[{"kind":"document","segment_index":1,"status":"published","document_id":"document-1","name":"cartoon.png"}]}`))- }))- defer server.Close()- card := playgroundCard{OperationID: "voice-call-1", InboxID: "room:room-1", Title: "Cartoon", Content: "The drawing is done."}- result, err := commitCard(t.Context(), clicredential.Profile{URL: server.URL, TenantID: "tenant-1", AgentID: "agent-1"}, "token-1", card,- []openedCardFile{openTestCardFile(t, "cartoon.png", image, 0)})+var cardInstallation = clicredential.Installation{CredentialPath: "/state/agent-1/token", Profile: clicredential.Profile{URL: "https://teamhub.example", TenantID: "tenant-1", AgentID: "agent-1"}}++func TestPlaygroundCardRunsTheCLIAsTheAgentInTheRoom(t *testing.T) {+ t.Setenv("TEAMHUB_SECRET", "from-the-daemon")+ directory, record := fakeCardCLI(t, `{"accepted":true,"message_id":"message-1","resources":[{"kind":"document","segment_index":1,"status":"published","document_id":"document-1","name":"report.md"}]}`, "", 0)+ daemon := &Daemon{teamhubCLIBin: directory}+ result, err := daemon.runCardCLI(t.Context(), cardInstallation, "room-1",+ []string{"message", "card", "--title", "Report", "--content", "Done.", "--attach", "/work/playground/task-1/report.md", "--operation-id", "voice-live:abc", "--json"})if err != nil {t.Fatal(err)}documents := result["documents"].([]map[string]any)- if result["message_id"] != "message-1" || len(documents) != 1 || documents[0]["document_id"] != "document-1" || documents[0]["filename"] != "cartoon.png" {+ if result["message_id"] != "message-1" || len(documents) != 1 || documents[0]["document_id"] != "document-1" || documents[0]["filename"] != "report.md" {t.Fatalf("result=%v", result)}- if !bytes.Equal(parts["upload_0"], image) {- t.Fatalf("uploaded %d bytes, want the whole %d byte file", len(parts["upload_0"]), len(image))+ recorded, err := os.ReadFile(record)+ if err != nil {+ t.Fatal(err)+ }+ parts := strings.Split(string(recorded), "---\n")+ if !strings.Contains(parts[0], "--attach\n/work/playground/task-1/report.md\n--operation-id\nvoice-live:abc\n--json\n") {+ t.Fatalf("argv=%q", parts[0])+ }+ profile, config, _ := strings.Cut(parts[1], "\n")+ var parsed struct {+ Profiles map[string]map[string]any `json:"profiles"`+ }+ if err := json.Unmarshal([]byte(config), &parsed); err != nil {+ t.Fatal(err)}- sum := sha256.Sum256(image)- invocation := sha256.Sum256([]byte("voice-call-1"))- uploads := metadata["uploads"].([]any)- upload := uploads[0].(map[string]any)- if metadata["invocation_id"] != "agent-invocation-sha256:"+hex.EncodeToString(invocation[:]) || metadata["inbox_id"] != "room:room-1" ||- metadata["card_title"] != "Cartoon" || upload["filename"] != "cartoon.png" || upload["sha256"] != hex.EncodeToString(sum[:]) ||- upload["size_bytes"] != float64(len(image)) || upload["media_type"] != "image/png" || upload["representation_format"] != "png" {- t.Fatalf("metadata=%v", metadata)+ live := parsed.Profiles["live"]+ if profile != "live" || live["token_file"] != "/state/agent-1/token" || live["agent_id"] != "agent-1" || live["url"] != "https://teamhub.example" ||+ live["scope"].(map[string]any)["id"] != "room-1" || live["scope"].(map[string]any)["kind"] != "room" {+ t.Fatalf("profile=%s config=%s", profile, config)}- segments := metadata["segments"].([]any)- if len(segments) != 2 || segments[0].(map[string]any)["content"] != "The drawing is done." || segments[1].(map[string]any)["upload_id"] != "upload_0" {- t.Fatalf("segments=%v", segments)+ if strings.TrimSpace(parts[2]) != "0" {+ t.Fatal("the daemon's own TeamHub settings reached the CLI")}}-func TestPlaygroundCardReportsARefusedCommit(t *testing.T) {- server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {- _, _ = io.Copy(io.Discard, request.Body)- writer.WriteHeader(http.StatusForbidden)- _, _ = writer.Write([]byte(`{"error":{"code":"OPERATION_NOT_PERMITTED","message":"no","request_id":"r"}}`))- }))- defer server.Close()- card := playgroundCard{OperationID: "voice-call-2", InboxID: "room:room-1", Title: "Cartoon", Content: "Done."}- _, err := commitCard(t.Context(), clicredential.Profile{URL: server.URL, TenantID: "tenant-1", AgentID: "agent-1"}, "token-1", card,- []openedCardFile{openTestCardFile(t, "cartoon.png", []byte("png"), 0)})+func TestPlaygroundCardTellsWhyTheCLIFailed(t *testing.T) {+ for stderr, want := range map[string]string{+ `{"error":{"code":"invalid_input","message":"A resource exceeds 50 MiB."}}`: "upload_failed",+ `{"error":{"code":"connection_failed","message":"no route"}}`: "outcome_unknown",+ `not json`: "outcome_unknown",+ } {+ directory, _ := fakeCardCLI(t, "", stderr, 2)+ _, err := (&Daemon{teamhubCLIBin: directory}).runCardCLI(t.Context(), cardInstallation, "room-1", []string{"message", "card"})+ var failure *playgroundFailure+ if !errors.As(err, &failure) || failure.code != want {+ t.Fatalf("%s: err=%v, want %s", stderr, err, want)+ }+ if want == "upload_failed" && !strings.Contains(failure.detail, "exceeds 50 MiB") {+ t.Fatalf("detail=%q", failure.detail)+ }+ }var failure *playgroundFailure- if !errors.As(err, &failure) || failure.code != "upload_failed" || !strings.Contains(failure.detail, "403 OPERATION_NOT_PERMITTED") {- t.Fatalf("err=%v", err)+ if _, err := (&Daemon{}).runCardCLI(t.Context(), cardInstallation, "room-1", nil); !errors.As(err, &failure) || failure.code != "cli_unavailable" {+ t.Fatalf("no CLI = %v", err)}}func TestPlaygroundCardRefusesAnInvalidCardOrMissingCredential(t *testing.T) {daemon := &Daemon{}for _, card := range []playgroundCard{- {OperationID: "op", InboxID: "room:room-1", Title: "Two\nlines", Content: "x"},{OperationID: "op", InboxID: "task:task-1", Title: "Title", Content: "x"},+ {OperationID: "op", InboxID: "room:room-1", Title: " ", Content: "x"},{OperationID: "op", InboxID: "room:room-1", Title: "Title", Content: " "},{OperationID: "op", InboxID: "room:room-1", Title: "Title", Content: "x", Files: make([]playgroundCardFile, 6)},} {@@ -127,7 +106,7 @@ func TestPlaygroundCardRefusesAnInvalidCardOrMissingCredential(t *testing.T) {}}var failure *playgroundFailure- if _, _, err := daemon.agentCLICredential("tenant-1", "agent-1"); !errors.As(err, &failure) || failure.code != "agent_unavailable" {+ if _, err := daemon.agentCLICredential("tenant-1", "agent-1"); !errors.As(err, &failure) || failure.code != "agent_unavailable" {t.Fatalf("credential = %v", err)}}diff --git a/apps/computer/local-daemon/internal/linger/context/live_playground.go b/apps/computer/local-daemon/internal/linger/context/live_playground.goindex d7268911..9bf97441 100644--- a/apps/computer/local-daemon/internal/linger/context/live_playground.go+++ b/apps/computer/local-daemon/internal/linger/context/live_playground.go@@ -149,6 +149,21 @@ func (s *ViewStore) OpenPlaygroundFile(ctx context.Context, tenantID, agentID streturn file, info, nil}+// PlaygroundFilePath is the path of one regular file of a folder, checked+// the way OpenPlaygroundFile checks it, for a program that reads it itself.+func (s *ViewStore) PlaygroundFilePath(ctx context.Context, tenantID, agentID string, folder PlaygroundFolder, relative string) (string, error) {+ file, _, err := s.OpenPlaygroundFile(ctx, tenantID, agentID, folder, relative)+ if err != nil {+ return "", err+ }+ _ = file.Close()+ directory, err := s.PlaygroundDirectory(ctx, tenantID, agentID, folder)+ if err != nil {+ return "", err+ }+ return filepath.Join(directory, filepath.FromSlash(strings.Trim(relative, "/"))), nil+}+func openPlaygroundPath(directory, relative string) (*os.File, error) {relative = filepath.FromSlash(strings.Trim(relative, "/"))if relative == "" || relative == "." {diff --git a/apps/teamhub/internal/voice/voice_live_files.go b/apps/teamhub/internal/voice/voice_live_files.goindex fbacbb8c..6288739a 100644--- a/apps/teamhub/internal/voice/voice_live_files.go+++ b/apps/teamhub/internal/voice/voice_live_files.go@@ -7,7 +7,6 @@ import ("errors""fmt""io"- "path""slices""strconv""strings"@@ -248,8 +247,7 @@ func (s *Service) sendVoiceLiveCard(ctx context.Context, session voicelive.Sessiif folder.taskID != "" && !slices.Contains(tasks, folder.taskID) {tasks = append(tasks, folder.taskID)}- format, mediaType := voicelive.FileType(path.Base(inside))- files = append(files, map[string]any{"folder": folder.folder, "path": inside, "representation_format": format, "media_type": mediaType})+ files = append(files, map[string]any{"folder": folder.folder, "path": inside})}if roomID == "" {roomID = session.RoomID@@ -263,7 +261,7 @@ func (s *Service) sendVoiceLiveCard(ctx context.Context, session voicelive.Sessireturn "", voicelive.ErrNotFound}result, err := s.callVoiceLivePlayground(ctx, session, "send_card", map[string]any{- "operation_id": "voice-live:" + session.ID + ":" + request.CallId, "inbox_id": "room:" + roomID,+ "operation_id": voiceLiveInvocationID(session, request), "inbox_id": "room:" + roomID,"title": title, "content": content, "files": files,}, voiceLiveCardDeadline)if err != nil {diff --git a/apps/teamhub/internal/voicelive/playground.go b/apps/teamhub/internal/voicelive/playground.goindex c5108dfd..20cb9d40 100644--- a/apps/teamhub/internal/voicelive/playground.go+++ b/apps/teamhub/internal/voicelive/playground.go@@ -2,7 +2,6 @@ package voiceliveimport ("fmt"- "mime""path""strings""time"@@ -88,24 +87,6 @@ func ParsePlaygroundPath(raw string) (PlaygroundPath, bool) {return PlaygroundPath{Folder: folder, Inside: inside}, true}-// FileType is the Document representation format and media type a file is-// stored with, from its extension.-func FileType(filename string) (format, mediaType string) {- extension := strings.ToLower(path.Ext(filename))- format = strings.TrimPrefix(extension, ".")- switch format {- case "":- format = "binary"- case "md":- format = "markdown"- }- mediaType = mime.TypeByExtension(extension)- if mediaType == "" {- mediaType = "application/octet-stream"- }- return format, mediaType-}-// ListEntry is one row of a folder listing.type ListEntry struct {Name stringdiff --git a/apps/teamhub/internal/voicelive/playground_test.go b/apps/teamhub/internal/voicelive/playground_test.goindex 3602197f..8e96cb79 100644--- a/apps/teamhub/internal/voicelive/playground_test.go+++ b/apps/teamhub/internal/voicelive/playground_test.go@@ -43,16 +43,10 @@ func TestFormatListingReadsLikeLs(t *testing.T) {}}-func TestHumanSizeAndFileType(t *testing.T) {+func TestHumanSize(t *testing.T) {for size, want := range map[int64]string{0: "0", 512: "512", 3800: "3.7K", 201_728: "197K", 12 << 20: "12M"} {if got := HumanSize(size); got != want {t.Errorf("HumanSize(%d)=%s, want %s", size, got, want)}}- for name, want := range map[string][2]string{"a.PNG": {"png", "image/png"}, "r.md": {"markdown", ""}, "blob": {"binary", "application/octet-stream"}} {- format, media := FileType(name)- if format != want[0] || (want[1] != "" && media != want[1]) {- t.Errorf("FileType(%s)=%s %s", name, format, media)- }- }}