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.
fix(teamhub): apply live email header edits on the latest canvas
muterCcc89c48e37c5
diff --git a/apps/teamhub/internal/document/comment_semantic.go b/apps/teamhub/internal/document/comment_semantic.goindex b8b30c25..d87da979 100644--- a/apps/teamhub/internal/document/comment_semantic.go+++ b/apps/teamhub/internal/document/comment_semantic.go@@ -74,6 +74,15 @@ func (s *Service) ApplyCommentTextReplacement(}, nil}+// RevisionMarkdown renders a stored revision of a Document as Markdown, such+// as the revision an Agent last read, so a caller can see what changed since.+// A revision that is unknown or no longer has its state is+// ErrRevisionUnavailable.+func (s *Service) RevisionMarkdown(ctx context.Context, documentID, revisionID string) ([]byte, error) {+ markdown, _, err := s.renderRevisionMarkdown(ctx, documentID, revisionID)+ return markdown, err+}+func (s *Service) renderRevisionMarkdown(ctx context.Context,documentID, revisionID string,diff --git a/apps/teamhub/internal/voice/voice_live_canvas.go b/apps/teamhub/internal/voice/voice_live_canvas.goindex 8e3223b4..605632ea 100644--- a/apps/teamhub/internal/voice/voice_live_canvas.go+++ b/apps/teamhub/internal/voice/voice_live_canvas.go@@ -163,26 +163,83 @@ func (s *Service) editVoiceLiveEmailCanvas(ctx context.Context, session voicelivif err != nil {return "", err}- // A body rewrite is text: it replaces the text blocks and keeps the- // attached files after them. Images or files among the text would be- // lost, so that body changes through a task; the header can always change.- if args.Body != nil && canvas.mediaInText {- return voicelive.ErrorOutput("canvas_has_media"), nil- }- if args.RevisionID != canvas.revisionID {- return canvas.changed(), nil- }if args.Body != nil {// The model may copy an attachment line from the body it was shown.body := voiceLiveAttachmentLine.ReplaceAllString(*args.Body, "")args.Body = &body}+ // To, cc and subject each replace a whole line with what the user just+ // asked for, so they change on the latest canvas whatever changed since the+ // model read it, also by its own calls in parallel. The body is rewritten+ // from the text the model read, so it changes only while that text is+ // still the body; a body the user edited since comes back to be redone.+ for attempt := 0; ; attempt++ {+ if args.Body != nil {+ same, err := s.voiceLiveCanvasBodySince(ctx, args.RevisionID, canvas)+ if err != nil {+ return "", err+ }+ if !same {+ return canvas.changed(), nil+ }+ // A body rewrite is text: it replaces the text blocks and keeps the+ // attached files after them. Images or files among the text would be+ // lost, so that body changes through a task; the header can always change.+ if canvas.mediaInText {+ return voicelive.ErrorOutput("canvas_has_media"), nil+ }+ }+ output, conflicted, err := s.applyVoiceLiveEmailEdit(ctx, session, request, principal, canvas, args, attempt)+ if err != nil || !conflicted {+ return output, err+ }+ // Another change landed while this one was made: read the canvas+ // again and redo it there, a few times at most.+ latest, readErr := s.voiceLiveCanvas(ctx, principal, args.DocumentID)+ if output, handled := voiceLiveCanvasError(readErr); handled {+ return output, nil+ }+ if readErr != nil {+ return "", readErr+ }+ if attempt+1 >= voiceLiveEmailEditAttempts {+ return latest.changed(), nil+ }+ canvas = latest+ }+}++// voiceLiveEmailEditAttempts bounds how often an email edit is redone on a+// canvas that changed while it was made.+const voiceLiveEmailEditAttempts = 3++// voiceLiveCanvasBodySince reports whether the canvas body is still the text+// it had at revisionID, the revision the live model last read.+func (s *Service) voiceLiveCanvasBodySince(ctx context.Context, revisionID string, canvas voiceLiveCanvasState) (bool, error) {+ if revisionID == canvas.revisionID {+ return true, nil+ }+ markdown, err := s.documents.RevisionMarkdown(ctx, canvas.documentID, revisionID)+ if errors.Is(err, document.ErrRevisionUnavailable) || errors.Is(err, document.ErrInvalidInput) {+ return false, nil+ }+ if err != nil {+ return false, err+ }+ _, text := voiceLiveCanvasText(string(markdown))+ return text == canvas.text, nil+}++// applyVoiceLiveEmailEdit makes one email edit on the canvas as read. A+// native edit is one operation: the header, the title and the body's text+// change in turn, each against the revision the one before made. conflicted+// means another change landed first, after which part of it may be made.+func (s *Service) applyVoiceLiveEmailEdit(ctx context.Context, session voicelive.Session, request teamhubinternal.VoiceLiveToolCall,+ principal agentcredential.Principal, canvas voiceLiveCanvasState, args voicelive.EditEmailCanvasArguments, attempt int) (string, bool, error) {_, header, problem := voicelive.EditedEmailCanvas(canvas.fields, canvas.text, args)if problem != "" {- return voicelive.ErrorOutput(problem), nil+ return voicelive.ErrorOutput(problem), false, nil}- // A native edit is one operation: the header, the title and the body's- // text change in turn, each against the revision the one before made.edits := []map[string]string{}if args.To != nil || args.Cc != nil || args.Subject != nil {edits = append(edits, map[string]string{"command": "block_replace", "block_id": canvas.firstBlockID, "content": header})@@ -214,16 +271,21 @@ func (s *Service) editVoiceLiveEmailCanvas(ctx context.Context, session voiceliv}}if len(edits) == 0 {- return voicelive.ErrorOutput("nothing_to_change"), nil+ return voicelive.ErrorOutput("nothing_to_change"), false, nil}revisionID := canvas.revisionIDfor index, edit := range edits {edit["kind"], edit["parser_version"] = "edit_document", "markdown-v1"change, err := json.Marshal([]map[string]string{edit})if err != nil {- return "", err+ return "", false, err}+ // Each step of each try is its own operation: a retried call makes+ // it once, and a redone try never replays an earlier try's step.invocationID := voiceLiveInvocationID(session, request)+ if attempt > 0 {+ invocationID += "_r" + strconv.Itoa(attempt)+ }if index > 0 {invocationID += "_" + strconv.Itoa(index)}@@ -235,27 +297,19 @@ func (s *Service) editVoiceLiveEmailCanvas(ctx context.Context, session voicelivswitch {case errors.Is(err, document.ErrVersionConflict), errors.Is(err, document.ErrConflict),err == nil && result.Status == document.SemanticMutationConflicted:- // The user edited it while the change was made: hand back the latest.- latest, readErr := s.voiceLiveCanvas(ctx, principal, args.DocumentID)- if output, handled := voiceLiveCanvasError(readErr); handled {- return output, nil- }- if readErr != nil {- return "", readErr- }- return latest.changed(), nil+ return "", true, nilcase errors.Is(err, document.ErrInvalidInput):// Block edits cannot keep comments anchored in the canvas.- return voicelive.ErrorOutput("canvas_locked"), nil+ return voicelive.ErrorOutput("canvas_locked"), false, nilcase err != nil:- return "", err+ return "", false, err}revisionID = result.RevisionID}return voicelive.Output(map[string]string{"status": "changed", "document_id": args.DocumentID, "revision_id": revisionID,"next": "Tell the user in one short sentence what you changed in the email.",- }), nil+ }), false, nil}// attachVoiceLiveEmailFile copies a file the Agent reads (a Document in a@@ -553,6 +607,13 @@ func (s *Service) voiceLiveDocument(ctx context.Context, principal agentcredenti}// voiceLiveCanvas reads the latest Gmail canvas as the Agent.+// voiceLiveCanvasText is a canvas's Markdown without its header, and the+// text of that body without attachment lines, as the live model reads it.+func voiceLiveCanvasText(markdown string) (body, text string) {+ body = agentconnectedapps.CanvasHeaderFence.ReplaceAllString(markdown, "")+ return body, strings.TrimSpace(voiceLiveAttachmentLine.ReplaceAllString(body, "")) + "\n"+}+func (s *Service) voiceLiveCanvas(ctx context.Context, principal agentcredential.Principal, documentID string) (voiceLiveCanvasState, error) {state, err := s.voiceLiveDocument(ctx, principal, documentID)if err != nil {@@ -568,7 +629,7 @@ func (s *Service) voiceLiveCanvas(ctx context.Context, principal agentcredentialreturn voiceLiveCanvasState{}, errNotEmailCanvas}runs, attachmentFirst, attachments, mediaInText := voiceLiveCanvasBody(idBlocks.Blocks)- body := agentconnectedapps.CanvasHeaderFence.ReplaceAllString(string(state.markdown), "")+ body, text := voiceLiveCanvasText(string(state.markdown))header, ok := agentconnectedapps.ReadCanvasHeader(headerBlocks.Blocks)if !ok || header.Target != "gmail" {return voiceLiveCanvasState{}, errNotEmailCanvas@@ -576,7 +637,7 @@ func (s *Service) voiceLiveCanvas(ctx context.Context, principal agentcredentialreturn voiceLiveCanvasState{documentID: documentID, revisionID: state.revisionID, firstBlockID: state.firstBlockID, lastBlockID: state.lastBlockID,hasMedia: state.hasMedia, fields: header.Fields, body: body,- text: strings.TrimSpace(voiceLiveAttachmentLine.ReplaceAllString(body, "")) + "\n",+ text: text,textRuns: runs, attachmentFirst: attachmentFirst, attachments: attachments, mediaInText: mediaInText,}, nil}diff --git a/apps/teamhub/internal/voicelive/canvas.go b/apps/teamhub/internal/voicelive/canvas.goindex 0b3ac920..9a37b3ec 100644--- a/apps/teamhub/internal/voicelive/canvas.go+++ b/apps/teamhub/internal/voicelive/canvas.go@@ -50,9 +50,10 @@ var EmailCanvasTool = Tool{var EditEmailCanvasTool = Tool{Name: ToolEditEmailCanvas,Description: "Change a Gmail canvas in this room as the user asks: its recipients, subject or body. It changes in the side panel at once. " ++ "Put everything one request changes in one call, to, cc, subject and body together; never split it into several calls. " +"Give only what changes: to, cc or subject replace that line, and the canvas title follows the subject, so never rename an email canvas yourself; body replaces the whole body text, so write all of it, keeping what the user did not ask to change. Attached files are not part of the body: they stay attached, listed as attachments, wherever they sat. " +"revision_id is the one the last open_email_canvas or edit_email_canvas result gave for this document_id. " +- "canvas_changed means the canvas is not as you last saw it (the user may have edited it): its result has the latest text and revision_id; redo the change on that text, keeping the user's own edits, and call again with that revision_id. " ++ "canvas_changed means the body is not as you last saw it (the user may have edited it): its result has the latest text and revision_id; redo the body on that text, keeping the user's own edits, and call again with that revision_id. " +"When it is changed, tell the user in one short sentence what you changed. " + emailCanvasDelivery +"canvas_has_media means images sit among the text, which a body rewrite would lose: recipients and subject still change here; change the body with start_task instead, naming the document_id. canvas_locked: change it with start_task instead, naming the document_id. invalid_recipients means an address is not an email address: ask the user for it. " +"missing_content means the email's subject or body is empty, also when the canvas already had it empty and this call left it out: ask the user what it should say. body_too_long means the body is too long: shorten it. nothing_to_change means you gave none of to, cc, subject or body.",diff --git a/apps/teamhub/tests/integration/voice_live_apps_test.go b/apps/teamhub/tests/integration/voice_live_apps_test.goindex f22d32ba..0198201f 100644--- a/apps/teamhub/tests/integration/voice_live_apps_test.go+++ b/apps/teamhub/tests/integration/voice_live_apps_test.go@@ -210,8 +210,7 @@ func TestVoiceLiveSendsAnEmailCanvasOnlyAfterTheUserSaidYes(t *testing.T) {t.Fatalf("saves of an unchanged canvas=%d", saves)}// A canvas changed after the question asks again.- stale := call("lt_edit", "edit-0", "edit_email_canvas", map[string]any{"document_id": documentID, "revision_id": "revision_unseen", "subject": "Wed afternoon pickup"})- edited := call("lt_edit", "edit-1", "edit_email_canvas", map[string]any{"document_id": documentID, "revision_id": stale["revision_id"], "subject": "Wed afternoon pickup"})+ edited := call("lt_edit", "edit-1", "edit_email_canvas", map[string]any{"document_id": documentID, "revision_id": "revision_unseen", "subject": "Wed afternoon pickup"})if edited["status"] != "changed" {t.Fatalf("edit=%v", edited)}diff --git a/apps/teamhub/tests/integration/voice_live_canvas_test.go b/apps/teamhub/tests/integration/voice_live_canvas_test.goindex 7ae19e5c..70c8b6d9 100644--- a/apps/teamhub/tests/integration/voice_live_canvas_test.go+++ b/apps/teamhub/tests/integration/voice_live_canvas_test.go@@ -255,8 +255,9 @@ func TestVoiceLiveWritesAndChangesAnEmailCanvasAsTheAgent(t *testing.T) {if !strings.Contains(live.Instructions, `"Next Wed LA airport pickup" document_id=`+documentID+", last: open_email_canvas → opened") {t.Fatalf("live context names no call Document: %q", live.Instructions[max(0, len(live.Instructions)-400):])}- // A revision the live model did not see gets the latest text back instead.- stale := call("edit-0", "edit_email_canvas", map[string]string{"document_id": documentID, "revision_id": "revision_unseen", "subject": "Changed"})+ // A body rewritten from a revision the live model did not see gets the+ // latest text back instead.+ stale := call("edit-0", "edit_email_canvas", map[string]string{"document_id": documentID, "revision_id": "revision_unseen", "body": "Changed"})if stale["error"] != "canvas_changed" || stale["revision_id"] != revisionID || stale["subject"] != "Next Wed LA airport pickup" ||!strings.Contains(stale["body"].(string), "Can you pick me up at LAX at 9 am next Wednesday?") || computes.Load() != 0 {t.Fatalf("stale edit=%v computes=%d", stale, computes.Load())@@ -285,15 +286,25 @@ func TestVoiceLiveWritesAndChangesAnEmailCanvasAsTheAgent(t *testing.T) {if again := call("edit-1", "edit_email_canvas", edit); again["revision_id"] != next || computes.Load() != 2 {t.Fatalf("retried edit=%v computes=%d", again, computes.Load())}- if superseded := call("edit-2", "edit_email_canvas", edit); superseded["error"] != "canvas_changed" || superseded["revision_id"] != next || superseded["subject"] != "Next Wed barbecue pickup" {- t.Fatalf("superseded edit=%v", superseded)+ // A header line replaces that line on the latest canvas, from whichever+ // revision the model read: parallel calls of one request all land.+ older := call("edit-2", "edit_email_canvas", map[string]string{"document_id": documentID, "revision_id": revisionID, "to": "[email protected], [email protected]"})+ if content := <-replaced; older["status"] != "changed" ||+ content != "```\ncanvas: gmail\nto: [email protected], [email protected]\ncc: [email protected]\nsubject: Next Wed barbecue pickup\nstatus: editing\nlink:\nexternal_id:\n```\n" {+ t.Fatalf("header edit from an older revision=%v replacement=%q", older, content)}- // A body change replaces the body's text and leaves the header.+ // A body change replaces the body's text and leaves the header. It is+ // read at an older revision, but only the header changed since.body := map[string]string{"document_id": documentID, "revision_id": next, "body": "Hi Amy,\n\nBarbecue is on me!"}rewritten := call("edit-3", "edit_email_canvas", body)if content := <-replaced; rewritten["status"] != "changed" || content != "Hi Amy,\n\nBarbecue is on me!\n" {t.Fatalf("body edit=%v replacement=%q", rewritten, content)}+ // A body read before it was rewritten is redone on the latest text.+ if outdated := call("edit-3b", "edit_email_canvas", map[string]string{"document_id": documentID, "revision_id": next, "body": "Hi Amy,\n\nSee you."}); outdated["error"] != "canvas_changed" ||+ outdated["revision_id"] != rewritten["revision_id"] || !strings.Contains(outdated["body"].(string), "Barbecue is on me!") {+ t.Fatalf("body edit over a newer body=%v", outdated)+ }stateOf := func() string {t.Helper()var state []byte@@ -307,7 +318,7 @@ func TestVoiceLiveWritesAndChangesAnEmailCanvasAsTheAgent(t *testing.T) {if _, err := bodies.Exec(t.Context(), `UPDATE document_bodies SET seq=seq+1,state=$2 WHERE document_id=$1`, documentID, []byte(state)); err != nil {t.Fatal(err)}- return call("read-"+state[len(state)-8:], "edit_email_canvas", map[string]string{"document_id": documentID, "revision_id": "revision_unseen", "to": "x"})["revision_id"].(string)+ return call("read-"+state[len(state)-8:], "edit_email_canvas", map[string]string{"document_id": documentID, "revision_id": "revision_unseen", "body": "x"})["revision_id"].(string)}// An attached file after the text stays through recipient and body// changes, and the model sees it apart from the text.@@ -323,7 +334,7 @@ func TestVoiceLiveWritesAndChangesAnEmailCanvasAsTheAgent(t *testing.T) {!strings.Contains(state, "to: [email protected]") || !strings.HasSuffix(state, "Hi Carol,\n\nSee you at the Saturday barbecue.\n\n"+attachment+"\n") {t.Fatalf("recipients=%v body=%v state=%q", recipients, rewritten, state)}- stale = call("edit-6", "edit_email_canvas", map[string]string{"document_id": documentID, "revision_id": "revision_unseen", "subject": "x"})+ stale = call("edit-6", "edit_email_canvas", map[string]string{"document_id": documentID, "revision_id": "revision_unseen", "body": "x"})if attachments, _ := stale["attachments"].([]any); len(attachments) != 1 || strings.Contains(stale["body"].(string), "document-asset") {t.Fatalf("canvas as the model sees it=%v", stale)}