Skip to content

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(mail): send a Gmail canvas from its chat card

muterC40d20f048c65
diff --git a/apps/teamhub/AGENTS.md b/apps/teamhub/AGENTS.md
index 2214ace6..b6293969 100644
--- a/apps/teamhub/AGENTS.md
+++ b/apps/teamhub/AGENTS.md
@@ -35,6 +35,40 @@ Go service owning Human HTTP/SSE, Agent callbacks, and active product state.
## Important Conventions
+- Gmail canvas drafts persist their source digest alongside the provider draft ID.
+ Preparing and executing a send confirmation both check the current authorized
+ canvas against that source; changed recipients, body, or attachments require a
+ refreshed draft and a new confirmation. Delivery status and link bookkeeping
+ do not change the source digest. Draft saves run one at a time per connection under a
+ `gmail_canvas_draft_leases` lease that holds no database connection during
+ the upload; a save whose lease expired leaves its draft unbound. A save
+ waits at most 30 seconds for the lease, then fails as retryable; a lease a
+ crashed process left blocks that connection's saves until it expires
+ (10 minutes).
+ Large MIME drafts use Gmail resumable uploads in bounded chunks through the
+ authenticated proxy, avoiding its request-body limit. Each chunk must be fully
+ acknowledged; transport failures do not replay a possibly completed write.
+- A Human sends a Gmail canvas from its chat card (`internal/mailcanvas`):
+ editing only saves the Document; `POST /v0/documents/{id}/mail` carries the
+ source digest of the email the card last showed and queues one River
+ delivery that uploads the draft and sends it, refusing a canvas that changed
+ since. Each canvas has one `mail_canvas_deliveries` row: a `failed` or
+ `unknown` delivery may be sent again or declined (an unknown one only after
+ the Human checked Gmail), while `declined` (Don't send) and `sent` are final.
+ A rejected or interrupted upload is `failed` (it sent nothing); only an
+ interrupted or unconfirmed send becomes `unknown`, which is never replayed
+ on its own. Sending an `unknown` delivery again whose earlier Gmail draft
+ is gone (404; Gmail deletes a draft once it is sent) fails with a
+ may-have-been-sent message and starts a new draft next time; other upload
+ errors keep the draft. A delivery that is in flight, `sent` or `unknown`
+ blocks Voice Live and Agent sends of that canvas, and an Agent's confirmed
+ send of a canvas-bound draft records a `sent` (or `unknown`) row, so the
+ card cannot send it again. `GET` reports `sent` whenever the header says so, and
+ `can_edit`; only editors may send or decline. While the latest content is
+ still rendering these routes answer 503 with `Retry-After`.
+- Live voice write tools that finish a send return a `next` asking the model
+ to say it was sent; a result without one can leave the voice silent.
+
- A Room permits 100 Routines: recurring ones count while they exist, and
one-shot ones count until they fire. There is no separate one-shot limit.
diff --git a/apps/teamhub/internal/agentconnectedapps/canvas.go b/apps/teamhub/internal/agentconnectedapps/canvas.go
index 935ce87b..e01d3e7b 100644
--- a/apps/teamhub/internal/agentconnectedapps/canvas.go
+++ b/apps/teamhub/internal/agentconnectedapps/canvas.go
@@ -47,7 +47,9 @@ func (e *CanvasDraftError) Error() string { return e.Message }
// CanvasDraft is a canvas built as a Gmail draft.
type CanvasDraft struct {
- Raw string
+ Raw string
+ DocumentID string
+ SourceDigest string
// InlineImages counts the images shown in the body.
InlineImages int
// Attachments names the files the email carries, in canvas order.
@@ -58,7 +60,7 @@ type CanvasDraft struct {
// the body and its file blocks go as attachments. Recipients and subject left
// nil come from the canvas header.
func (s *Canvas) GmailCanvasDraftRaw(ctx context.Context, tenantID, agentID, documentID string, to, cc *[]string, subject *string) (CanvasDraft, error) {
- blocks, err := s.canvasBlocks(ctx, tenantID, agentID, documentID)
+ blocks, sourceDigest, err := s.canvasBlocks(ctx, tenantID, agentID, documentID)
if err != nil {
return CanvasDraft{}, err
}
@@ -152,12 +154,29 @@ func (s *Canvas) GmailCanvasDraftRaw(ctx context.Context, tenantID, agentID, doc
for i, attachment := range attachments {
names[i] = attachment.Filename
}
- return CanvasDraft{Raw: raw, InlineImages: len(images), Attachments: names}, nil
+ current, err := s.SourceDigest(ctx, tenantID, agentID, documentID)
+ if err != nil {
+ return CanvasDraft{}, err
+ }
+ if current != sourceDigest {
+ return CanvasDraft{}, &CanvasDraftError{Message: "The canvas changed while its draft was being built. Save the draft again from the current canvas."}
+ }
+ return CanvasDraft{Raw: raw, InlineImages: len(images), Attachments: names, DocumentID: documentID, SourceDigest: sourceDigest}, nil
}
// assetBytes reads one canvas Asset, at most limit bytes.
func (s *Canvas) assetBytes(ctx context.Context, tenantID, agentID, documentID, assetID string, limit int) ([]byte, document.Asset, error) {
- content, err := s.documents.OpenAgentAssetContent(ctx, tenantID, agentID, documentID, assetID)
+ var content document.AssetContent
+ var err error
+ if s.accountID != "" {
+ content, err = s.documents.OpenAssetContent(ctx, s.accountID, assetID)
+ if err == nil && content.Asset.DocumentID != documentID {
+ _ = content.Reader.Close()
+ return nil, document.Asset{}, document.ErrNotFound
+ }
+ } else {
+ content, err = s.documents.OpenAgentAssetContent(ctx, tenantID, agentID, documentID, assetID)
+ }
if err != nil {
return nil, document.Asset{}, err
}
@@ -195,7 +214,13 @@ func canvasFileAssets(blocks []CanvasBlock) []string {
// CanvasExport reads the canvas in one export format, up to 1 MiB.
func (s *Canvas) CanvasExport(ctx context.Context, tenantID, agentID, documentID, format string) ([]byte, error) {
- download, err := s.documents.DownloadAgentFileAs(ctx, tenantID, agentID, documentID, format)
+ var download document.AgentFileDownload
+ var err error
+ if s.accountID != "" {
+ download, err = s.documents.DownloadHumanFileAs(ctx, s.accountID, documentID, format)
+ } else {
+ download, err = s.documents.DownloadAgentFileAs(ctx, tenantID, agentID, documentID, format)
+ }
if err != nil {
return nil, err
}
@@ -217,18 +242,19 @@ func (s *Canvas) CanvasExport(ctx context.Context, tenantID, agentID, documentID
}
// canvasBlocks reads the canvas as blocks, for its header and image widths.
-func (s *Canvas) canvasBlocks(ctx context.Context, tenantID, agentID, documentID string) ([]CanvasBlock, error) {
+func (s *Canvas) canvasBlocks(ctx context.Context, tenantID, agentID, documentID string) ([]CanvasBlock, string, error) {
content, err := s.CanvasExport(ctx, tenantID, agentID, documentID, "blocks")
if err != nil {
- return nil, err
+ return nil, "", err
}
var export struct {
Blocks []CanvasBlock `json:"blocks"`
}
if err := json.Unmarshal(content, &export); err != nil {
- return nil, document.ErrInvalidInput
+ return nil, "", document.ErrInvalidInput
}
- return export.Blocks, nil
+ digest, err := canvasSourceDigest(content)
+ return export.Blocks, digest, err
}
// CanvasHeader is the header code block of a canvas: its target app and fields.
@@ -369,6 +395,12 @@ func ptr[T any](value T) *T { return &value }
type Canvas struct {
documents *document.Service
artifacts artifactstore.ObjectStore
+ accountID string
+}
+
+// ForAccount reads a canvas using the Human's current document permissions.
+func (s *Canvas) ForAccount(accountID string) *Canvas {
+ return &Canvas{documents: s.documents, artifacts: s.artifacts, accountID: accountID}
}
// NewCanvas builds the canvas reader.
diff --git a/apps/teamhub/internal/agentconnectedapps/canvas_source.go b/apps/teamhub/internal/agentconnectedapps/canvas_source.go
new file mode 100644
index 00000000..40e81497
--- /dev/null
+++ b/apps/teamhub/internal/agentconnectedapps/canvas_source.go
@@ -0,0 +1,191 @@
+package agentconnectedapps
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/composio"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/document"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/externalsource"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/ids"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/store"
+)
+
+// CanvasSourceReader reads the current, authorized source of a saved draft.
+type CanvasSourceReader interface {
+ SourceDigest(context.Context, string, string, string) (string, error)
+}
+
+// SetCanvasReader enables source checks before a canvas draft is confirmed or sent.
+func (s *Service) SetCanvasReader(reader CanvasSourceReader) { s.canvasSource = reader }
+
+// SourceDigest fingerprints mail content while ignoring delivery bookkeeping.
+func (s *Canvas) SourceDigest(ctx context.Context, tenantID, agentID, documentID string) (string, error) {
+ content, err := s.CanvasExport(ctx, tenantID, agentID, documentID, "blocks")
+ if err != nil {
+ return "", err
+ }
+ return canvasSourceDigest(content)
+}
+
+func canvasSourceDigest(content []byte) (string, error) {
+ var typed struct {
+ Blocks []CanvasBlock `json:"blocks"`
+ }
+ var source struct {
+ Blocks []map[string]any `json:"blocks"`
+ }
+ if json.Unmarshal(content, &typed) != nil || json.Unmarshal(content, &source) != nil || len(source.Blocks) == 0 {
+ return "", document.ErrInvalidInput
+ }
+ header, canvas := ReadCanvasHeader(typed.Blocks)
+ if canvas {
+ fields := map[string]string{}
+ for _, key := range []string{"to", "cc", "subject"} {
+ fields[key] = header.Fields[key]
+ }
+ source.Blocks[0] = map[string]any{"target": header.Target, "fields": fields}
+ }
+ return digestOf(source.Blocks), nil
+}
+
+// draftLeaseDuration bounds one draft save; its upload gets a minute less.
+const draftLeaseDuration = 10 * time.Minute
+
+// draftLeaseWait bounds how long a save waits for another save of the same
+// connection, including a lease a crashed process left until it expires.
+const draftLeaseWait = 30 * time.Second
+
+// acquireDraftLease waits until no other save of this connection holds it.
+func (s *Service) acquireDraftLease(ctx context.Context, connectionID, holder string) error {
+ ctx, cancel := context.WithTimeout(ctx, draftLeaseWait)
+ defer cancel()
+ for {
+ taken, err := store.New(s.pool).AcquireGmailCanvasDraftLease(ctx, store.AcquireGmailCanvasDraftLeaseParams{
+ ConnectionID: connectionID, Holder: holder, Seconds: draftLeaseDuration.Seconds(),
+ })
+ if err == nil && taken == 1 {
+ return nil
+ }
+ if err != nil && ctx.Err() == nil {
+ return unavailableError(err)
+ }
+ select {
+ case <-ctx.Done():
+ return &Error{Code: "provider_unavailable", Message: "Another draft save on this Gmail connection is still running; try again shortly.", Retryable: true, cause: ctx.Err()}
+ case <-time.After(250 * time.Millisecond):
+ }
+ }
+}
+
+// SaveGmailCanvasDraft binds the saved draft to the exact canvas source it used.
+func (s *Service) SaveGmailCanvasDraft(ctx context.Context, token, connectionID, draftID string, built CanvasDraft) (composio.GmailDraft, error) {
+ if built.DocumentID == "" || built.SourceDigest == "" {
+ return composio.GmailDraft{}, ErrInvalid
+ }
+ if s == nil || s.pool == nil {
+ return composio.GmailDraft{}, unavailableError(nil)
+ }
+ // Saves of one connection run one at a time, so the binding always names
+ // what the mailbox holds. The lease holds no database connection while
+ // the upload runs; the upload ends before the lease can expire.
+ holder := ids.New("draft_lease")
+ if err := s.acquireDraftLease(ctx, connectionID, holder); err != nil {
+ return composio.GmailDraft{}, err
+ }
+ defer func() {
+ release, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
+ defer cancel()
+ _ = store.New(s.pool).ReleaseGmailCanvasDraftLease(release, store.ReleaseGmailCanvasDraftLeaseParams{ConnectionID: connectionID, Holder: holder})
+ }()
+ upload, cancel := context.WithTimeout(ctx, draftLeaseDuration-time.Minute)
+ draft, err := s.SaveGmailDraft(upload, token, connectionID, draftID, built.Raw)
+ cancel()
+ if err != nil {
+ return draft, err
+ }
+ tx, err := s.pool.Begin(ctx)
+ if err != nil {
+ return composio.GmailDraft{}, uncertainExecutionError(err)
+ }
+ defer tx.Rollback(ctx)
+ q := store.New(tx)
+ // A lease lost to expiry leaves the draft unbound, so no send trusts it.
+ if _, err := q.HoldGmailCanvasDraftLease(ctx, store.HoldGmailCanvasDraftLeaseParams{ConnectionID: connectionID, Holder: holder}); err != nil {
+ return composio.GmailDraft{}, uncertainExecutionError(err)
+ }
+ err = q.UpsertGmailCanvasDraft(ctx, store.UpsertGmailCanvasDraftParams{
+ ConnectionID: connectionID, DraftID: draft.DraftID, DocumentID: built.DocumentID, SourceDigest: built.SourceDigest,
+ })
+ if err != nil {
+ return composio.GmailDraft{}, uncertainExecutionError(err)
+ }
+ if err := tx.Commit(ctx); err != nil {
+ return composio.GmailDraft{}, uncertainExecutionError(err)
+ }
+ return draft, nil
+}
+
+// canvasSend is the canvas a confirmed Gmail draft send was bound to; both
+// fields are empty for a draft that came from no canvas.
+type canvasSend struct{ digest, documentID string }
+
+// recordCanvasSend marks a canvas sent, or possibly sent, by an Agent's
+// confirmed send, so its chat card never sends it again.
+func (s *Service) recordCanvasSend(ctx context.Context, connection externalsource.AgentToolConnection, send canvasSend, status, message string) {
+ if send.documentID == "" {
+ return
+ }
+ ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
+ defer cancel()
+ if err := store.New(s.pool).RecordAgentMailCanvasSend(ctx, store.RecordAgentMailCanvasSendParams{
+ DocumentID: send.documentID, ID: ids.New("mail_delivery"), AccountID: connection.AccountID,
+ ConnectionID: pgtype.Text{String: connection.ID, Valid: true}, SourceDigest: send.digest,
+ Status: status, ErrorMessage: message,
+ }); err != nil && s.logger != nil {
+ s.logger.Error("connected_apps.canvas_send_record_failed", "document_id", send.documentID, "error", err)
+ }
+}
+
+func (s *Service) checkedCanvasSource(ctx context.Context, connection externalsource.AgentToolConnection, action confirmationAction) (canvasSend, error) {
+ if action.ToolSlug != "GMAIL_SEND_DRAFT" || s.pool == nil {
+ return canvasSend{}, nil
+ }
+ q := store.New(s.pool)
+ saved, err := q.GetGmailCanvasDraft(ctx, store.GetGmailCanvasDraftParams{ConnectionID: connection.ID, DraftID: str(action.Arguments, "draft_id")})
+ if errors.Is(err, pgx.ErrNoRows) {
+ if action.CanvasSourceDigest != "" {
+ return canvasSend{}, unavailableError(err)
+ }
+ return canvasSend{}, nil
+ }
+ if err != nil {
+ return canvasSend{}, unavailableError(err)
+ }
+ if s.canvasSource == nil {
+ return canvasSend{}, unavailableError(nil)
+ }
+ held, err := q.MailCanvasDeliveryHolds(ctx, saved.DocumentID)
+ if err != nil {
+ return canvasSend{}, unavailableError(err)
+ }
+ if held {
+ return canvasSend{}, &Error{Code: "invalid_input", Message: "The Human is sending or already sent this email from its card in the chat; do not send it again."}
+ }
+ registration, err := q.GetAgentRegistrationByActor(ctx, store.GetAgentRegistrationByActorParams{TenantID: saved.TenantID, ActorID: connection.AgentActorID})
+ if err != nil {
+ return canvasSend{}, unavailableError(err)
+ }
+ current, err := s.canvasSource.SourceDigest(ctx, saved.TenantID, registration.AgentManagementID.String, saved.DocumentID)
+ if err != nil {
+ return canvasSend{}, &Error{Code: "invalid_input", Message: "The email canvas could not be checked. Update the Gmail draft from the canvas and request a new confirmation before sending.", cause: err}
+ }
+ if current != saved.SourceDigest || (action.CanvasSourceDigest != "" && current != action.CanvasSourceDigest) {
+ return canvasSend{}, &Error{Code: "invalid_input", Message: "The email canvas changed after the Gmail draft was saved. Update that draft with gmail canvas-draft --update and request a new send confirmation; the old draft was not sent.", Issues: []Issue{{Path: "draft_id", Code: "canvas_draft_stale", Message: "Update the draft from the current canvas, including its attachments, before sending."}}}
+ }
+ return canvasSend{digest: current, documentID: saved.DocumentID}, nil
+}
diff --git a/apps/teamhub/internal/agentconnectedapps/canvas_test.go b/apps/teamhub/internal/agentconnectedapps/canvas_test.go
index b3904505..65d62d02 100644
--- a/apps/teamhub/internal/agentconnectedapps/canvas_test.go
+++ b/apps/teamhub/internal/agentconnectedapps/canvas_test.go
@@ -127,3 +127,43 @@ func TestCanvasFileBlocksAreAttachedOnceInOrder(t *testing.T) {
t.Fatalf("files=%q", files)
}
}
+
+func TestCanvasSourceDigestTracksMailContentButNotDeliveryStatus(t *testing.T) {
+ source := func(header, body string) []byte {
+ blocks := canvasCode(t, header)
+ var data map[string]any
+ raw, _ := json.Marshal(map[string]any{"blocks": blocks})
+ if err := json.Unmarshal(raw, &data); err != nil {
+ t.Fatal(err)
+ }
+ var rest []any
+ if err := json.Unmarshal([]byte(body), &rest); err != nil {
+ t.Fatal(err)
+ }
+ data["blocks"] = append(data["blocks"].([]any)[:1], rest...)
+ raw, _ = json.Marshal(data)
+ return raw
+ }
+ baseHeader := "canvas: gmail\nto: [email protected]\ncc:\nsubject: Test\nstatus: editing"
+ body := `[{"id":"body","type":"paragraph","content":[{"type":"text","text":"Hello","styles":{}}],"children":[]}]`
+ original, err := canvasSourceDigest(source(baseHeader, body))
+ if err != nil {
+ t.Fatal(err)
+ }
+ unchanged, err := canvasSourceDigest(source(baseHeader+"\nstatus: draft\nexternal_id: draft-1\nlink: https://mail.google.com/mail/#drafts", body))
+ if err != nil || unchanged != original {
+ t.Fatalf("delivery bookkeeping changed digest: %v", err)
+ }
+ for name, input := range map[string][]byte{
+ "recipient": source(strings.ReplaceAll(baseHeader, "[email protected]", "[email protected]"), body),
+ "subject": source(strings.ReplaceAll(baseHeader, "subject: Test", "subject: Edited"), body),
+ "body": source(baseHeader, strings.ReplaceAll(body, "Hello", "Updated")),
+ "attachment": source(baseHeader, strings.TrimSuffix(body, "]")+`,{"type":"file","props":{"url":"document-asset:asset_file"},"children":[]}]`),
+ "format": source(baseHeader, strings.ReplaceAll(body, `"styles":{}`, `"styles":{"bold":true}`)),
+ } {
+ changed, err := canvasSourceDigest(input)
+ if err != nil || changed == original {
+ t.Fatalf("%s did not change digest: %v", name, err)
+ }
+ }
+}
diff --git a/apps/teamhub/internal/agentconnectedapps/confirmation.go b/apps/teamhub/internal/agentconnectedapps/confirmation.go
index c17613a4..1597b3d1 100644
--- a/apps/teamhub/internal/agentconnectedapps/confirmation.go
+++ b/apps/teamhub/internal/agentconnectedapps/confirmation.go
@@ -34,15 +34,21 @@ type Result struct {
// confirmationAction is the stored call. DraftDigest pins the content of a
// draft that a send-draft call sends, which TeamHub read to build the card.
type confirmationAction struct {
- ToolSlug string `json:"tool_slug,omitempty"`
- ToolVersion string `json:"tool_version,omitempty"`
- Arguments map[string]any `json:"arguments,omitempty"`
- DraftDigest string `json:"draft_digest,omitempty"`
+ ToolSlug string `json:"tool_slug,omitempty"`
+ ToolVersion string `json:"tool_version,omitempty"`
+ Arguments map[string]any `json:"arguments,omitempty"`
+ DraftDigest string `json:"draft_digest,omitempty"`
+ CanvasSourceDigest string `json:"canvas_source_digest,omitempty"`
}
// prepareConfirmation builds the stored call and its card from what will run
// for an authorized call on an active connection.
func (s *Service) prepareConfirmation(ctx context.Context, connection externalsource.AgentToolConnection, action confirmationAction) (Result, error) {
+ canvas, err := s.checkedCanvasSource(ctx, connection, action)
+ if err != nil {
+ return Result{}, err
+ }
+ action.CanvasSourceDigest = canvas.digest
card := describeConfirmation(connection, action)
// A tool without its own card layout shows only its arguments, so they
// must fit on the card: the sponsor approves nothing they cannot see.
@@ -113,10 +119,18 @@ func (s *Service) ExecuteConfirmed(ctx context.Context, decisionID, tenantID, ag
return "failed", "The draft changed after the card was posted, so it was not sent.", nil
}
}
+ canvas, err := s.checkedCanvasSource(ctx, connection, action)
+ if err != nil {
+ return "failed", "The email canvas changed or could not be checked. Update the Gmail draft from the current canvas and request a new confirmation; nothing was sent.", nil
+ }
execution, err := s.provider.ExecuteTool(ctx, connection.UpstreamConnectionID, connection.UserID,
action.ToolSlug, action.ToolVersion, action.Arguments)
if err != nil {
- return failedOrUnknown(err)
+ status, outcome, value := failedOrUnknown(err)
+ if status == "unknown" {
+ s.recordCanvasSend(ctx, connection, canvas, "unknown", "The Agent's send was not confirmed. Check Sent in Gmail before sending again.")
+ }
+ return status, outcome, value
}
if !execution.Successful {
outcome := "The connected application rejected the call."
@@ -125,6 +139,7 @@ func (s *Service) ExecuteConfirmed(ctx context.Context, decisionID, tenantID, ag
}
return "failed", outcome, nil
}
+ s.recordCanvasSend(ctx, connection, canvas, "sent", "")
return "succeeded", "", sanitizeValue(execution.Data)
}
diff --git a/apps/teamhub/internal/agentconnectedapps/gmail_draft.go b/apps/teamhub/internal/agentconnectedapps/gmail_draft.go
index c07196bd..4c2c1645 100644
--- a/apps/teamhub/internal/agentconnectedapps/gmail_draft.go
+++ b/apps/teamhub/internal/agentconnectedapps/gmail_draft.go
@@ -222,7 +222,10 @@ func (s *Service) SaveGmailDraft(ctx context.Context, token, connectionID, draft
if connection.ToolkitSlug != "gmail" {
return composio.GmailDraft{}, ErrInvalid
}
- defer func() { s.logCall(ctx, "gmail/canvas-draft", connection, "", "", callOutcome(err)) }()
+ var providerError string
+ defer func() {
+ s.logCall(ctx, "gmail/canvas-draft", connection, "", "", callOutcome(err), "provider_error", providerError)
+ }()
status, err := s.provider.GetConnectionStatusForToolkit(ctx, connection.UpstreamConnectionID, connection.ToolkitSlug)
if err != nil {
return composio.GmailDraft{}, mapToolError(&providerOperationError{phase: "connection_status", err: err}, "execute")
@@ -239,6 +242,7 @@ func (s *Service) SaveGmailDraft(ctx context.Context, token, connectionID, draft
}
draft, err = provider.SaveGmailDraft(ctx, connection.UpstreamConnectionID, draftID, raw)
if err != nil {
+ providerError = err.Error()
return composio.GmailDraft{}, uncertainExecutionError(err)
}
return draft, nil
diff --git a/apps/teamhub/internal/agentconnectedapps/service.go b/apps/teamhub/internal/agentconnectedapps/service.go
index 24906c3e..691936e4 100644
--- a/apps/teamhub/internal/agentconnectedapps/service.go
+++ b/apps/teamhub/internal/agentconnectedapps/service.go
@@ -52,11 +52,12 @@ type ToolProvider interface {
}
type Service struct {
- pool *pgxpool.Pool
- contexts *agentauth.Service
- connections connectionAuthority
- provider ToolProvider
- logger *slog.Logger
+ canvasSource CanvasSourceReader
+ pool *pgxpool.Pool
+ contexts *agentauth.Service
+ connections connectionAuthority
+ provider ToolProvider
+ logger *slog.Logger
// pinnedTools keeps fetched tool versions for pinnedToolTTL; every call
// otherwise waits on the same Composio lookup before it runs.
pinnedTools sync.Map
diff --git a/apps/teamhub/internal/app/app.go b/apps/teamhub/internal/app/app.go
index dc561112..af7c7915 100644
--- a/apps/teamhub/internal/app/app.go
+++ b/apps/teamhub/internal/app/app.go
@@ -48,6 +48,7 @@ import (
"github.com/simplexai-labs/linger/apps/teamhub/internal/documenttext"
"github.com/simplexai-labs/linger/apps/teamhub/internal/externalsource"
"github.com/simplexai-labs/linger/apps/teamhub/internal/jobs"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/mailcanvas"
"github.com/simplexai-labs/linger/apps/teamhub/internal/mcpcontext"
"github.com/simplexai-labs/linger/apps/teamhub/internal/memoryclient"
"github.com/simplexai-labs/linger/apps/teamhub/internal/permissionreview"
@@ -155,6 +156,7 @@ type App struct {
agents *agentregistry.Service
agentMessages *agentmessages.Service
canvas *agentconnectedapps.Canvas
+ mailCanvas *mailcanvas.Service
voice *voice.Service
agentCredentials *agentcredential.Service
tracking *reminder.TrackingService
@@ -648,6 +650,8 @@ func (a *App) registerAccounts(deps Deps) {
a.agentCredentials = agentcredential.New(a.pool)
a.tracking = reminder.NewTrackingService(a.pool)
a.canvas = agentconnectedapps.NewCanvas(a.documents, a.artifacts)
+ a.agentConnectedApps.SetCanvasReader(a.canvas)
+ a.mailCanvas = mailcanvas.New(a.pool, a.documents, a.canvas, a.externalSources, a.composioClient)
a.passwordHashes = account.NewHashLimiter(passwordHashPermits, passwordHashWait)
a.verifyPassword = account.VerifyPassword
if deps.VerifyPassword != nil {
@@ -776,6 +780,7 @@ func (a *App) startJobs(ctx context.Context, runs func(Worker) bool) error {
river.AddWorker(riverWorkers, &stoppedTaskApprovalsWorker{app: a})
river.AddWorker(riverWorkers, a.collaboration.MessageAttachmentExpiryWorker())
river.AddWorker(riverWorkers, &decisionRunWorker{app: a})
+ a.mailCanvas.AddWorker(riverWorkers)
river.AddWorker(riverWorkers, &decisionExpireWorker{app: a})
taskexecution.AddJobWorkers(riverWorkers, a.pool)
riverOptions := jobs.Options{
diff --git a/apps/teamhub/internal/app/contract_server_agent_connector_gmail_canvas.go b/apps/teamhub/internal/app/contract_server_agent_connector_gmail_canvas.go
index 83939e1d..cfd4c9ec 100644
--- a/apps/teamhub/internal/app/contract_server_agent_connector_gmail_canvas.go
+++ b/apps/teamhub/internal/app/contract_server_agent_connector_gmail_canvas.go
@@ -46,7 +46,7 @@ func (a *App) saveConnectorGmailCanvasDraft(c *gin.Context) {
if input.DraftId != nil {
draftID = *input.DraftId
}
- draft, err := a.agentConnectedApps.SaveGmailDraft(connectorCallContext(c), token, input.ConnectionId, draftID, built.Raw)
+ draft, err := a.agentConnectedApps.SaveGmailCanvasDraft(connectorCallContext(c), token, input.ConnectionId, draftID, built)
if a.writeAgentConnectedAppsError(c, "save Gmail canvas draft", err) {
return
}
diff --git a/apps/teamhub/internal/app/handlers_mail_canvas.go b/apps/teamhub/internal/app/handlers_mail_canvas.go
new file mode 100644
index 00000000..b9ca8602
--- /dev/null
+++ b/apps/teamhub/internal/app/handlers_mail_canvas.go
@@ -0,0 +1,79 @@
+package app
+
+import (
+ "errors"
+ "net/http"
+
+ "github.com/gin-gonic/gin"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/document"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/mailcanvas"
+ httpapi "github.com/simplexai-labs/linger/contracts-go/teamhubpublic"
+)
+
+// writeMailCanvasNotReady answers 503 while the email's latest content is
+// being rendered: the shared Document mapping answers 202, which a client
+// would read as a mail state.
+func (a *App) writeMailCanvasNotReady(c *gin.Context, err error) bool {
+ if !errors.Is(err, document.ErrLatestProjectionNotReady) {
+ return false
+ }
+ c.Header("Retry-After", "1")
+ a.writeError(c, http.StatusServiceUnavailable, "DOCUMENT_LATEST_NOT_READY", "The email is being saved; retry")
+ return true
+}
+
+func (a *App) getMailCanvas(c *gin.Context) {
+ state, err := a.mailCanvas.Get(c.Request.Context(), currentPrincipal(c).Session.AccountID, c.Param("documentId"))
+ if a.writeMailCanvasNotReady(c, err) || a.writeUnifiedDocumentError(c, "read email canvas", err) {
+ return
+ }
+ c.Header("Cache-Control", "no-store")
+ c.JSON(http.StatusOK, state)
+}
+
+func (a *App) sendMailCanvas(c *gin.Context) {
+ var input httpapi.SendMailCanvasRequest
+ if decodeJSON(c, &input) != nil {
+ a.writeError(c, http.StatusBadRequest, "INVALID_REQUEST", "Email delivery input is invalid")
+ return
+ }
+ state, err := a.mailCanvas.Send(c.Request.Context(), mailcanvas.SendInput{
+ AccountID: currentPrincipal(c).Session.AccountID, DocumentID: c.Param("documentId"),
+ ConnectionID: input.ConnectionId, RequestID: input.RequestId, SourceDigest: input.SourceDigest,
+ })
+ if a.writeMailCanvasError(c, err) {
+ return
+ }
+ if a.writeMailCanvasNotReady(c, err) || a.writeUnifiedDocumentError(c, "send email canvas", err) {
+ return
+ }
+ c.JSON(http.StatusAccepted, state)
+}
+
+func (a *App) declineMailCanvas(c *gin.Context) {
+ state, err := a.mailCanvas.Decline(c.Request.Context(), currentPrincipal(c).Session.AccountID, c.Param("documentId"))
+ if a.writeMailCanvasError(c, err) {
+ return
+ }
+ if a.writeMailCanvasNotReady(c, err) || a.writeUnifiedDocumentError(c, "decline email canvas", err) {
+ return
+ }
+ c.JSON(http.StatusOK, state)
+}
+
+// writeMailCanvasError answers the delivery outcomes a Human can act on.
+func (a *App) writeMailCanvasError(c *gin.Context, err error) bool {
+ switch {
+ case errors.Is(err, mailcanvas.ErrAlreadySent):
+ a.writeError(c, http.StatusConflict, "CONFLICT", "This email was already sent.")
+ case errors.Is(err, mailcanvas.ErrConflict):
+ a.writeError(c, http.StatusConflict, "CONFLICT", "The email changed or is already being sent. Review it and try again.")
+ case errors.Is(err, mailcanvas.ErrForbidden):
+ a.writeError(c, http.StatusForbidden, "FORBIDDEN", "You cannot send or change this email.")
+ case errors.Is(err, mailcanvas.ErrConnectionUnavailable):
+ a.writeError(c, http.StatusForbidden, "FORBIDDEN", "The Gmail account is unavailable. Reconnect it before sending.")
+ default:
+ return false
+ }
+ return true
+}
diff --git a/apps/teamhub/internal/app/routes_public.go b/apps/teamhub/internal/app/routes_public.go
index 1f4b07a5..dfe731eb 100644
--- a/apps/teamhub/internal/app/routes_public.go
+++ b/apps/teamhub/internal/app/routes_public.go
@@ -35,6 +35,9 @@ func (a *App) publicRoutes() []contractRoute {
route(http.MethodPost, "/v0/document-versions/:documentVersionId/preview-sessions", nil, session, a.createDocumentPreviewSession),
route(http.MethodDelete, "/v0/documents/:documentId", nil, session, a.trashDocument),
route(http.MethodGet, "/v0/documents/:documentId", nil, session, a.getDocument),
+ route(http.MethodGet, "/v0/documents/:documentId/mail", nil, session, a.getMailCanvas),
+ route(http.MethodPost, "/v0/documents/:documentId/mail", nil, session, a.sendMailCanvas),
+ route(http.MethodPost, "/v0/documents/:documentId/mail/decline", nil, session, a.declineMailCanvas),
route(http.MethodPatch, "/v0/documents/:documentId", nil, session, a.updateDocumentMetadata),
route(http.MethodGet, "/v0/documents/:documentId/agent-mention-candidates", httpapi.ListDocumentAgentMentionCandidatesParams{}, session, a.listDocumentAgentMentionCandidates),
route(http.MethodPost, "/v0/documents/:documentId/assets", httpapi.PlanRoomDocumentAssetParams{}, session, a.planRoomDocumentAsset),
diff --git a/apps/teamhub/internal/composio/client.go b/apps/teamhub/internal/composio/client.go
index a4b2e8e8..54abd03d 100644
--- a/apps/teamhub/internal/composio/client.go
+++ b/apps/teamhub/internal/composio/client.go
@@ -187,6 +187,12 @@ type proxyRequest struct {
Method string `json:"method"`
Parameters []proxyParameter `json:"parameters,omitempty"`
Body json.RawMessage `json:"body,omitempty"`
+ BinaryBody *proxyBinaryBody `json:"binary_body,omitempty"`
+}
+
+type proxyBinaryBody struct {
+ Base64 string `json:"base64"`
+ ContentType string `json:"content_type"`
}
type proxyResponse struct {
diff --git a/apps/teamhub/internal/composio/gmail.go b/apps/teamhub/internal/composio/gmail.go
index 2d81b959..515e403a 100644
--- a/apps/teamhub/internal/composio/gmail.go
+++ b/apps/teamhub/internal/composio/gmail.go
@@ -435,6 +435,25 @@ type GmailDraft struct {
DraftID, MessageID, ThreadID string
}
+// SendGmailDraft sends one already uploaded draft without replaying the write.
+func (c *Client) SendGmailDraft(ctx context.Context, accountID, draftID string) (string, error) {
+ ctx, _ = WithProviderAttemptBudget(ctx, 1)
+ body, err := json.Marshal(map[string]string{"id": draftID})
+ if err != nil {
+ return "", err
+ }
+ var message struct {
+ ID string `json:"id"`
+ }
+ if err := c.proxy(ctx, proxyRequest{ConnectedAccountID: accountID, Endpoint: "/gmail/v1/users/me/drafts/send", Method: http.MethodPost, Body: body}, &message, "send Gmail draft"); err != nil {
+ return "", err
+ }
+ if message.ID == "" {
+ return "", errors.New("Gmail did not return the sent message ID")
+ }
+ return message.ID, nil
+}
+
// SaveGmailDraft stores a complete RFC 5322 message (base64url, as Gmail's
// raw field) as a new draft, or replaces draftID in place. It never sends.
func (c *Client) SaveGmailDraft(ctx context.Context, connectedAccountID, draftID, raw string) (GmailDraft, error) {
@@ -455,9 +474,18 @@ func (c *Client) SaveGmailDraft(ctx context.Context, connectedAccountID, draftID
ThreadID string `json:"threadId"`
} `json:"message"`
}
- if err := c.proxy(ctx, proxyRequest{
- ConnectedAccountID: connectedAccountID, Endpoint: endpoint, Method: method, Body: body,
- }, &draft, "save Gmail draft"); err != nil {
+ if len(raw) > gmailDraftChunkBytes {
+ var response json.RawMessage
+ response, err = c.uploadGmailDraft(ctx, connectedAccountID, endpoint, method, raw)
+ if err == nil {
+ err = json.Unmarshal(response, &draft)
+ }
+ } else {
+ err = c.proxy(ctx, proxyRequest{
+ ConnectedAccountID: connectedAccountID, Endpoint: endpoint, Method: method, Body: body,
+ }, &draft, "save Gmail draft")
+ }
+ if err != nil {
return GmailDraft{}, err
}
if draft.ID == "" || draftID != "" && draft.ID != draftID {
diff --git a/apps/teamhub/internal/composio/gmail_draft_test.go b/apps/teamhub/internal/composio/gmail_draft_test.go
index 2c3d4464..e72650cd 100644
--- a/apps/teamhub/internal/composio/gmail_draft_test.go
+++ b/apps/teamhub/internal/composio/gmail_draft_test.go
@@ -10,6 +10,30 @@ import (
type proxiedDraftCall struct{ Method, Endpoint, Raw, ID string }
+type gmailDraftTransport func(*http.Request) (*http.Response, error)
+
+func (transport gmailDraftTransport) RoundTrip(request *http.Request) (*http.Response, error) {
+ return transport(request)
+}
+
+func TestGmailDraftUploadHonorsCancellationWithoutRetry(t *testing.T) {
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ calls := 0
+ client, err := newTestClient(Config{APIKey: "restricted-key", HTTPClient: &http.Client{Transport: gmailDraftTransport(func(request *http.Request) (*http.Response, error) {
+ calls++
+ cancel()
+ <-request.Context().Done()
+ return nil, request.Context().Err()
+ })}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := client.SaveGmailDraft(ctx, "ca_1", "r-1", "cmF3"); err == nil || calls != 1 {
+ t.Fatalf("cancelled upload: err=%v calls=%d", err, calls)
+ }
+}
+
func TestClientSavesGmailDraftThroughProxyWithoutSending(t *testing.T) {
var calls []proxiedDraftCall
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
diff --git a/apps/teamhub/internal/composio/gmail_draft_upload.go b/apps/teamhub/internal/composio/gmail_draft_upload.go
new file mode 100644
index 00000000..0ecd7642
--- /dev/null
+++ b/apps/teamhub/internal/composio/gmail_draft_upload.go
@@ -0,0 +1,79 @@
+package composio
+
+import (
+ "context"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "net/url"
+ "strconv"
+)
+
+// Each chunk is a multiple of Gmail's 256 KiB granularity and stays below
+// the proxy's request-body limit even after base64 encoding.
+const gmailDraftChunkBytes = 1 << 20
+
+func (c *Client) uploadGmailDraft(ctx context.Context, accountID, endpoint, method, raw string) (json.RawMessage, error) {
+ message, err := base64.RawURLEncoding.DecodeString(raw)
+ if err != nil {
+ return nil, errors.New("Gmail draft contains invalid encoded MIME")
+ }
+ response, err := c.gmailUploadProxy(ctx, proxyRequest{
+ ConnectedAccountID: accountID, Endpoint: "/upload" + endpoint, Method: method,
+ Parameters: []proxyParameter{
+ {Name: "uploadType", Value: "resumable", Type: "query"},
+ {Name: "X-Upload-Content-Type", Value: "message/rfc822", Type: "header"},
+ {Name: "X-Upload-Content-Length", Value: strconv.Itoa(len(message)), Type: "header"},
+ },
+ })
+ if err != nil {
+ return nil, err
+ }
+ if response.Status != http.StatusOK {
+ return nil, &remoteError{operation: "start Gmail draft upload", status: response.Status}
+ }
+ session := headerValue(response.Headers, "location")
+ parsed, err := url.Parse(session)
+ if err != nil || parsed.Scheme != "https" || (parsed.Host != "www.googleapis.com" && parsed.Host != "gmail.googleapis.com") ||
+ parsed.User != nil || parsed.Fragment != "" || parsed.Path != "/upload"+endpoint || parsed.Query().Get("upload_id") == "" {
+ return nil, errors.New("Gmail returned an invalid draft upload location")
+ }
+ for start := 0; start < len(message); start += gmailDraftChunkBytes {
+ end := min(start+gmailDraftChunkBytes, len(message))
+ response, err = c.gmailUploadProxy(ctx, proxyRequest{
+ ConnectedAccountID: accountID, Endpoint: session, Method: http.MethodPut,
+ BinaryBody: &proxyBinaryBody{Base64: base64.StdEncoding.EncodeToString(message[start:end]), ContentType: "message/rfc822"},
+ Parameters: []proxyParameter{{Name: "Content-Range", Value: fmt.Sprintf("bytes %d-%d/%d", start, end-1, len(message)), Type: "header"}},
+ })
+ if err != nil {
+ return nil, err
+ }
+ if end == len(message) {
+ if response.Status != http.StatusOK && response.Status != http.StatusCreated {
+ return nil, &remoteError{operation: "finish Gmail draft upload", status: response.Status}
+ }
+ return response.Data, nil
+ }
+ if response.Status != http.StatusPermanentRedirect {
+ return nil, &remoteError{operation: "upload Gmail draft chunk", status: response.Status}
+ }
+ if headerValue(response.Headers, "range") != fmt.Sprintf("bytes=0-%d", end-1) {
+ return nil, errors.New("Gmail did not acknowledge the complete draft chunk")
+ }
+ }
+ return nil, errors.New("Gmail draft upload was empty")
+}
+
+func (c *Client) gmailUploadProxy(ctx context.Context, request proxyRequest) (proxyResponse, error) {
+ binding, err := c.authorizeConnection(ctx, request.ConnectedAccountID)
+ if err != nil {
+ return proxyResponse{}, err
+ }
+ request.UserID = binding.UserID
+ var response proxyResponse
+ // A failed final chunk may already have saved the draft. Never replay it.
+ err = c.requestJSONOnce(ctx, http.MethodPost, "/api/v3.1/tools/execute/proxy", request, &response, "upload Gmail draft")
+ return response, err
+}
diff --git a/apps/teamhub/internal/composio/gmail_draft_upload_test.go b/apps/teamhub/internal/composio/gmail_draft_upload_test.go
new file mode 100644
index 00000000..1126b631
--- /dev/null
+++ b/apps/teamhub/internal/composio/gmail_draft_upload_test.go
@@ -0,0 +1,132 @@
+package composio
+
+import (
+ "bytes"
+ "context"
+ "encoding/base64"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+)
+
+func TestLargeGmailDraftUploadsEveryByteWithoutSending(t *testing.T) {
+ for _, draftID := range []string{"", "r-1"} {
+ t.Run("draft="+draftID, func(t *testing.T) {
+ message := bytes.Repeat([]byte("attachment\r\n"), gmailDraftChunkBytes/6)
+ var uploaded []byte
+ calls := 0
+ path := "/upload/gmail/v1/users/me/drafts"
+ method := http.MethodPost
+ if draftID != "" {
+ path += "/" + draftID
+ method = http.MethodPut
+ }
+ session := "https://www.googleapis.com" + path + "?uploadType=resumable&upload_id=test"
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ calls++
+ var request proxyRequest
+ if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
+ t.Fatal(err)
+ }
+ if request.ConnectedAccountID != "ca_1" || request.UserID == "" || strings.Contains(request.Endpoint, "/send") {
+ t.Fatalf("unexpected draft request: %+v", request)
+ }
+ if calls == 1 {
+ if request.Endpoint != path || request.Method != method || request.BinaryBody != nil {
+ t.Fatalf("invalid session initiation: %+v", request)
+ }
+ assertProxyParameter(t, []proxyRequest{request}, path, "uploadType", "resumable")
+ assertGmailUploadHeader(t, request, "X-Upload-Content-Length", fmt.Sprint(len(message)))
+ _ = json.NewEncoder(w).Encode(proxyResponse{Status: http.StatusOK, Headers: map[string]string{"Location": session}})
+ return
+ }
+ if request.Endpoint != session || request.Method != http.MethodPut || request.BinaryBody == nil || request.BinaryBody.ContentType != "message/rfc822" {
+ t.Fatal("invalid chunk request")
+ }
+ chunk, err := base64.StdEncoding.DecodeString(request.BinaryBody.Base64)
+ if err != nil || len(chunk) > gmailDraftChunkBytes {
+ t.Fatalf("invalid chunk: size=%d err=%v", len(chunk), err)
+ }
+ start := len(uploaded)
+ uploaded = append(uploaded, chunk...)
+ assertGmailUploadHeader(t, request, "Content-Range", fmt.Sprintf("bytes %d-%d/%d", start, len(uploaded)-1, len(message)))
+ if len(uploaded) < len(message) {
+ _ = json.NewEncoder(w).Encode(proxyResponse{Status: http.StatusPermanentRedirect, Headers: map[string]string{"Range": fmt.Sprintf("bytes=0-%d", len(uploaded)-1)}})
+ return
+ }
+ _, _ = w.Write([]byte(`{"status":200,"data":{"id":"r-1","message":{"id":"m-1","threadId":"t-1"}}}`))
+ }))
+ defer server.Close()
+ client, err := newTestClient(Config{BaseURL: server.URL, APIKey: "restricted-key", HTTPClient: server.Client()})
+ if err != nil {
+ t.Fatal(err)
+ }
+ client.SetConnectionAuthority(func(context.Context, string) (ConnectionBinding, error) {
+ return ConnectionBinding{UserID: "owner-1"}, nil
+ })
+ draft, err := client.SaveGmailDraft(context.Background(), "ca_1", draftID, base64.RawURLEncoding.EncodeToString(message))
+ if err != nil || draft.DraftID != "r-1" || !bytes.Equal(uploaded, message) || calls != 3 {
+ t.Fatalf("upload: draft=%+v err=%v bytes=%d calls=%d", draft, err, len(uploaded), calls)
+ }
+ })
+ }
+}
+
+func assertGmailUploadHeader(t *testing.T, request proxyRequest, name, value string) {
+ t.Helper()
+ for _, parameter := range request.Parameters {
+ if parameter.Type == "header" && parameter.Name == name && parameter.Value == value {
+ return
+ }
+ }
+ t.Fatalf("missing upload header %s=%s", name, value)
+}
+
+func TestLargeGmailDraftStopsAfterInvalidUploadResponse(t *testing.T) {
+ for _, failure := range []string{"location", "range", "transport", "wrong_draft"} {
+ t.Run(failure, func(t *testing.T) {
+ calls := 0
+ message := bytes.Repeat([]byte("x"), gmailDraftChunkBytes+1)
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ calls++
+ if calls == 1 {
+ host := "www.googleapis.com"
+ if failure == "location" {
+ host = "untrusted.example"
+ }
+ _ = json.NewEncoder(w).Encode(proxyResponse{Status: 200, Headers: map[string]string{"Location": "https://" + host + "/upload/gmail/v1/users/me/drafts/r-1?upload_id=test"}})
+ return
+ }
+ if failure == "transport" {
+ connection, _, _ := w.(http.Hijacker).Hijack()
+ _ = connection.Close()
+ return
+ }
+ if failure == "range" {
+ _, _ = w.Write([]byte(`{"status":308,"headers":{"range":"bytes=0-1"}}`))
+ return
+ }
+ if calls == 2 {
+ _ = json.NewEncoder(w).Encode(proxyResponse{Status: 308, Headers: map[string]string{"Range": fmt.Sprintf("bytes=0-%d", gmailDraftChunkBytes-1)}})
+ return
+ }
+ _, _ = w.Write([]byte(`{"status":200,"data":{"id":"wrong-id"}}`))
+ }))
+ defer server.Close()
+ client, err := newTestClient(Config{BaseURL: server.URL, APIKey: "restricted-key", HTTPClient: server.Client()})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := client.SaveGmailDraft(context.Background(), "ca_1", "r-1", base64.RawURLEncoding.EncodeToString(message)); err == nil {
+ t.Fatal("invalid upload result was accepted")
+ }
+ wantCalls := map[string]int{"location": 1, "range": 2, "transport": 2, "wrong_draft": 3}[failure]
+ if calls != wantCalls {
+ t.Fatalf("upload retried or continued: calls=%d want=%d", calls, wantCalls)
+ }
+ })
+ }
+}
diff --git a/apps/teamhub/internal/document/cli_download.go b/apps/teamhub/internal/document/cli_download.go
index 6c8f1c8e..c9d1ecd6 100644
--- a/apps/teamhub/internal/document/cli_download.go
+++ b/apps/teamhub/internal/document/cli_download.go
@@ -80,6 +80,28 @@ func (s *Service) DownloadAgentFileAs(ctx context.Context, tenantID, agentID, do
return s.DownloadAgentFileConditional(ctx, tenantID, agentID, documentID, format, "")
}
+// DownloadHumanFileAs exports the latest native content under current Human access.
+func (s *Service) DownloadHumanFileAs(ctx context.Context, accountID, documentID, format string) (AgentFileDownload, error) {
+ if format != "markdown" && format != "blocks" {
+ return AgentFileDownload{}, ErrInvalidInput
+ }
+ return s.readLatestAgentDownload(ctx, func() (AgentFileDownload, error) {
+ tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead})
+ if err != nil {
+ return AgentFileDownload{}, err
+ }
+ defer tx.Rollback(ctx)
+ value, err := get(ctx, tx, accountID, documentID)
+ if err != nil {
+ return AgentFileDownload{}, err
+ }
+ if !value.Capabilities.Export || value.AccessV2 == nil {
+ return AgentFileDownload{}, ErrNotFound
+ }
+ return s.downloadAuthorizedFile(ctx, tx, value.TenantID, documentID, value.AccessV2.ContentRole, format, "", "human")
+ })
+}
+
func (s *Service) DownloadAgentFileConditional(ctx context.Context, tenantID, agentID, documentID, format, ifNoneMatch string) (AgentFileDownload, error) {
if format != "markdown" && format != "html" && format != "blocks" {
return AgentFileDownload{}, ErrInvalidInput
diff --git a/apps/teamhub/internal/mailcanvas/service.go b/apps/teamhub/internal/mailcanvas/service.go
new file mode 100644
index 00000000..6226f694
--- /dev/null
+++ b/apps/teamhub/internal/mailcanvas/service.go
@@ -0,0 +1,354 @@
+// Package mailcanvas delivers a Human-reviewed canvas only after Send is clicked.
+package mailcanvas
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "net/mail"
+ "strings"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/jackc/pgx/v5/pgxpool"
+ "github.com/riverqueue/river"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/agentconnectedapps"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/composio"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/document"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/externalsource"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/ids"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/jobs"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/store"
+)
+
+// ErrConflict means the reviewed canvas changed or a delivery already started.
+var ErrConflict = errors.New("mail canvas changed or delivery already started")
+
+// ErrForbidden means the caller cannot change this canvas.
+var ErrForbidden = errors.New("mail canvas delivery is not allowed")
+
+// ErrAlreadySent means the canvas went out by another path.
+var ErrAlreadySent = errors.New("mail canvas was already sent")
+
+// ErrConnectionUnavailable means the chosen Gmail connection cannot send.
+var ErrConnectionUnavailable = errors.New("gmail connection is unavailable")
+
+// Provider uploads and sends drafts under a currently authorized Gmail connection.
+type Provider interface {
+ SaveGmailDraft(context.Context, string, string, string) (composio.GmailDraft, error)
+ SendGmailDraft(context.Context, string, string) (string, error)
+}
+
+// Service owns the delivery receipt shown in the editor and its queued execution.
+type Service struct {
+ pool *pgxpool.Pool
+ documents *document.Service
+ canvas *agentconnectedapps.Canvas
+ connections *externalsource.Service
+ provider Provider
+}
+
+// New constructs the Human mail delivery service.
+func New(pool *pgxpool.Pool, documents *document.Service, canvas *agentconnectedapps.Canvas, connections *externalsource.Service, provider Provider) *Service {
+ return &Service{pool: pool, documents: documents, canvas: canvas, connections: connections, provider: provider}
+}
+
+// State is the current local draft or persisted delivery receipt.
+type State struct {
+ Status string `json:"status"`
+ Subject string `json:"subject"`
+ To string `json:"to"`
+ Error string `json:"error,omitempty"`
+ MessageID string `json:"message_id,omitempty"`
+ SourceDigest string `json:"source_digest"`
+ CanEdit bool `json:"can_edit"`
+}
+
+// SendInput pins the durable version the Human reviewed before clicking Send.
+type SendInput struct {
+ AccountID, DocumentID, ConnectionID, RequestID, SourceDigest string
+}
+
+func (s *Service) read(ctx context.Context, accountID, documentID string) (document.Document, agentconnectedapps.CanvasHeader, error) {
+ doc, err := s.documents.Get(ctx, accountID, documentID)
+ if err != nil {
+ return doc, agentconnectedapps.CanvasHeader{}, err
+ }
+ content, err := s.canvas.ForAccount(accountID).CanvasExport(ctx, "", "", documentID, "blocks")
+ if err != nil {
+ return doc, agentconnectedapps.CanvasHeader{}, err
+ }
+ var source struct {
+ Blocks []agentconnectedapps.CanvasBlock `json:"blocks"`
+ }
+ if err := json.Unmarshal(content, &source); err != nil {
+ return doc, agentconnectedapps.CanvasHeader{}, err
+ }
+ header, ok := agentconnectedapps.ReadCanvasHeader(source.Blocks)
+ if !ok || header.Target != "gmail" {
+ return doc, header, document.ErrInvalidInput
+ }
+ return doc, header, nil
+}
+
+// Get reads editor status without contacting Gmail or changing an external draft.
+func (s *Service) Get(ctx context.Context, accountID, documentID string) (State, error) {
+ doc, header, err := s.read(ctx, accountID, documentID)
+ if err != nil {
+ return State{}, err
+ }
+ digest, err := s.canvas.ForAccount(accountID).SourceDigest(ctx, "", "", documentID)
+ if err != nil {
+ return State{}, err
+ }
+ state := State{Status: "draft", Subject: header.Fields["subject"], To: header.Fields["to"], SourceDigest: digest, CanEdit: doc.CanEditNativeContent}
+ row, err := store.New(s.pool).GetMailCanvasDelivery(ctx, documentID)
+ if err != nil && !errors.Is(err, pgx.ErrNoRows) {
+ return State{}, err
+ }
+ found := err == nil
+ // A send by any path writes sent into the header, which outranks an
+ // older card receipt such as declined or failed.
+ if header.Fields["status"] == "sent" {
+ state.Status = "sent"
+ if found && row.Status == "sent" {
+ state.MessageID = row.MessageID
+ }
+ return state, nil
+ }
+ if found {
+ state.Status, state.Error, state.MessageID = row.Status, row.ErrorMessage, row.MessageID
+ }
+ return state, nil
+}
+
+// Send queues exactly one upload and delivery after checking the reviewed version.
+func (s *Service) Send(ctx context.Context, input SendInput) (State, error) {
+ if len(input.RequestID) < 16 || len(input.RequestID) > 120 || input.SourceDigest == "" {
+ return State{}, document.ErrInvalidInput
+ }
+ doc, header, err := s.read(ctx, input.AccountID, input.DocumentID)
+ if err != nil {
+ return State{}, err
+ }
+ if !doc.CanEditNativeContent {
+ return State{}, ErrForbidden
+ }
+ if header.Fields["status"] == "sent" {
+ return State{}, ErrAlreadySent
+ }
+ if strings.TrimSpace(header.Fields["subject"]) == "" {
+ return State{}, document.ErrInvalidInput
+ }
+ if _, err := mail.ParseAddressList(header.Fields["to"]); err != nil {
+ return State{}, document.ErrInvalidInput
+ }
+ if _, err := s.connection(ctx, input.AccountID, input.ConnectionID); err != nil {
+ return State{}, err
+ }
+ reader := s.canvas.ForAccount(input.AccountID)
+ digest, err := reader.SourceDigest(ctx, "", "", input.DocumentID)
+ if err != nil {
+ return State{}, err
+ }
+ tx, err := s.pool.Begin(ctx)
+ if err != nil {
+ return State{}, err
+ }
+ defer tx.Rollback(ctx)
+ q := store.New(tx)
+ if err := q.AcquireAdvisoryTransactionLock(ctx, "mail-canvas:"+input.DocumentID); err != nil {
+ return State{}, err
+ }
+ if row, err := q.GetMailCanvasDelivery(ctx, input.DocumentID); err == nil {
+ if row.ID == input.RequestID {
+ return State{Status: row.Status, Subject: header.Fields["subject"], To: header.Fields["to"], Error: row.ErrorMessage, SourceDigest: digest, CanEdit: true}, nil
+ }
+ if !reopenable(row.Status) {
+ return State{}, conflictFor(row.Status)
+ }
+ } else if !errors.Is(err, pgx.ErrNoRows) {
+ return State{}, err
+ }
+ if digest != input.SourceDigest {
+ return State{}, ErrConflict
+ }
+ row, err := q.StartMailCanvasDelivery(ctx, store.StartMailCanvasDeliveryParams{DocumentID: input.DocumentID, ID: input.RequestID, AccountID: input.AccountID, ConnectionID: pgtype.Text{String: input.ConnectionID, Valid: true}, SourceDigest: digest})
+ if err != nil {
+ return State{}, err
+ }
+ if err := jobs.InsertTx(ctx, tx, deliveryArgs{ID: row.ID}, nil); err != nil {
+ return State{}, err
+ }
+ if err := tx.Commit(ctx); err != nil {
+ return State{}, err
+ }
+ return State{Status: row.Status, Subject: header.Fields["subject"], To: header.Fields["to"], SourceDigest: digest, CanEdit: true}, nil
+}
+
+// reopenable says whether the Human may send or decline again: after a
+// failure, or after an unknown result they checked in Gmail themselves.
+func reopenable(status string) bool { return status == "failed" || status == "unknown" }
+
+func conflictFor(status string) error {
+ if status == "sent" {
+ return ErrAlreadySent
+ }
+ return ErrConflict
+}
+
+// Decline records that the Human chose not to send; Send is refused afterwards.
+func (s *Service) Decline(ctx context.Context, accountID, documentID string) (State, error) {
+ doc, header, err := s.read(ctx, accountID, documentID)
+ if err != nil {
+ return State{}, err
+ }
+ if !doc.CanEditNativeContent {
+ return State{}, ErrForbidden
+ }
+ if header.Fields["status"] == "sent" {
+ return State{}, ErrAlreadySent
+ }
+ digest, err := s.canvas.ForAccount(accountID).SourceDigest(ctx, "", "", documentID)
+ if err != nil {
+ return State{}, err
+ }
+ tx, err := s.pool.Begin(ctx)
+ if err != nil {
+ return State{}, err
+ }
+ defer tx.Rollback(ctx)
+ q := store.New(tx)
+ if err := q.AcquireAdvisoryTransactionLock(ctx, "mail-canvas:"+documentID); err != nil {
+ return State{}, err
+ }
+ state := State{Status: "declined", Subject: header.Fields["subject"], To: header.Fields["to"], SourceDigest: digest, CanEdit: true}
+ if row, err := q.GetMailCanvasDelivery(ctx, documentID); err == nil {
+ if row.Status == "declined" {
+ return state, nil
+ }
+ if !reopenable(row.Status) {
+ return State{}, conflictFor(row.Status)
+ }
+ } else if !errors.Is(err, pgx.ErrNoRows) {
+ return State{}, err
+ }
+ if _, err := q.DeclineMailCanvasDelivery(ctx, store.DeclineMailCanvasDeliveryParams{DocumentID: documentID, ID: ids.New("mail_delivery"), AccountID: accountID, SourceDigest: digest}); err != nil {
+ return State{}, err
+ }
+ return state, tx.Commit(ctx)
+}
+
+func (s *Service) connection(ctx context.Context, accountID, connectionID string) (externalsource.Connection, error) {
+ connection, err := s.connections.GetConnection(ctx, accountID, connectionID)
+ if errors.Is(err, externalsource.ErrNotFound) {
+ return connection, ErrConnectionUnavailable
+ }
+ if err != nil {
+ return connection, err
+ }
+ if connection.Provider != "gmail" || connection.Status != "active" {
+ return connection, ErrConnectionUnavailable
+ }
+ return connection, nil
+}
+
+type deliveryArgs struct {
+ ID string `json:"id"`
+}
+
+func (deliveryArgs) Kind() string { return "mail.canvas_delivery" }
+func (deliveryArgs) InsertOpts() river.InsertOpts {
+ return river.InsertOpts{Queue: jobs.QueueDefault, MaxAttempts: 3}
+}
+
+type deliveryWorker struct {
+ river.WorkerDefaults[deliveryArgs]
+ service *Service
+}
+
+func (*deliveryWorker) Timeout(*river.Job[deliveryArgs]) time.Duration { return 10 * time.Minute }
+
+// AddWorker registers delivery and recovery of interrupted operations.
+func (s *Service) AddWorker(workers *river.Workers) {
+ river.AddWorker(workers, &deliveryWorker{service: s})
+}
+
+func (w *deliveryWorker) Work(ctx context.Context, job *river.Job[deliveryArgs]) error {
+ s := w.service
+ q := store.New(s.pool)
+ row, err := q.GetMailCanvasDeliveryByID(ctx, job.Args.ID)
+ if errors.Is(err, pgx.ErrNoRows) {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ // Uploading only writes a draft, so an interrupted upload sent nothing;
+ // an interrupted send may have gone out and is never replayed.
+ if row.Status == "uploading" {
+ return s.finish(ctx, row, "failed", "The upload was interrupted. Nothing was sent; send again.")
+ }
+ if row.Status == "sending" {
+ return s.finish(ctx, row, "unknown", "Sending was interrupted. Check Sent in Gmail before trying again.")
+ }
+ if row.Status != "queued" {
+ return nil
+ }
+ row, err = q.UpdateMailCanvasDelivery(ctx, store.UpdateMailCanvasDeliveryParams{ID: row.ID, ExpectedStatus: "queued", Status: "uploading", DraftID: row.DraftID})
+ if errors.Is(err, pgx.ErrNoRows) {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ connection, err := s.connection(ctx, row.AccountID, row.ConnectionID.String)
+ if err != nil {
+ return s.finish(ctx, row, "failed", "The Gmail account is unavailable. Reconnect it before sending.")
+ }
+ reader := s.canvas.ForAccount(row.AccountID)
+ draft, err := reader.GmailCanvasDraftRaw(ctx, "", "", row.DocumentID, nil, nil, nil)
+ if err != nil {
+ return s.finish(ctx, row, "failed", "The email could not be prepared. Check its recipients and attachments.")
+ }
+ if draft.SourceDigest != row.SourceDigest {
+ return s.finish(ctx, row, "failed", "The email changed after Send was clicked. Review it and send again.")
+ }
+ saved, err := s.provider.SaveGmailDraft(ctx, connection.UpstreamConnectionID, row.DraftID, draft.Raw)
+ if status, ok := composio.ErrorStatus(err); ok && status == http.StatusNotFound && row.DraftID != "" {
+ // Gmail deletes a draft once it is sent, so a lost earlier draft may
+ // mean an unconfirmed send went out. The next Send starts a new draft.
+ row.DraftID = ""
+ return s.finish(ctx, row, "failed", "The earlier Gmail draft is gone, so this email may already have been sent. Check Sent in Gmail; send again only if it is not there.")
+ }
+ if err != nil {
+ return s.finish(ctx, row, "failed", "Gmail did not accept the upload. Nothing was sent; send again.")
+ }
+ row.DraftID = saved.DraftID
+ current, err := reader.SourceDigest(ctx, "", "", row.DocumentID)
+ if err != nil || current != row.SourceDigest {
+ return s.finish(ctx, row, "failed", "The email changed during upload. Nothing was sent. Review it and send again.")
+ }
+ if _, err = s.connection(ctx, row.AccountID, row.ConnectionID.String); err != nil {
+ return s.finish(ctx, row, "failed", "The Gmail account is no longer available. Nothing was sent.")
+ }
+ row, err = q.UpdateMailCanvasDelivery(ctx, store.UpdateMailCanvasDeliveryParams{ID: row.ID, ExpectedStatus: "uploading", Status: "sending", DraftID: row.DraftID})
+ if err != nil {
+ return err
+ }
+ messageID, err := s.provider.SendGmailDraft(ctx, connection.UpstreamConnectionID, row.DraftID)
+ if err != nil {
+ return s.finish(ctx, row, "unknown", "Gmail did not confirm delivery. Check Sent before trying again.")
+ }
+ row.MessageID = messageID
+ return s.finish(ctx, row, "sent", "")
+}
+
+func (s *Service) finish(ctx context.Context, row store.MailCanvasDelivery, status, message string) error {
+ ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
+ defer cancel()
+ _, err := store.New(s.pool).UpdateMailCanvasDelivery(ctx, store.UpdateMailCanvasDeliveryParams{ID: row.ID, ExpectedStatus: row.Status, Status: status, DraftID: row.DraftID, MessageID: row.MessageID, ErrorMessage: message})
+ return err
+}
diff --git a/apps/teamhub/internal/store/gmail_canvas_drafts.sql.go b/apps/teamhub/internal/store/gmail_canvas_drafts.sql.go
new file mode 100644
index 00000000..66004613
--- /dev/null
+++ b/apps/teamhub/internal/store/gmail_canvas_drafts.sql.go
@@ -0,0 +1,113 @@
+// Code generated by sqlc. DO NOT EDIT.
+// versions:
+// sqlc v1.29.0
+// source: gmail_canvas_drafts.sql
+
+package store
+
+import (
+ "context"
+)
+
+const acquireGmailCanvasDraftLease = `-- name: AcquireGmailCanvasDraftLease :execrows
+INSERT INTO gmail_canvas_draft_leases(connection_id, holder, expires_at)
+VALUES ($1, $2, clock_timestamp() + make_interval(secs => $3::float8))
+ON CONFLICT (connection_id) DO UPDATE
+SET holder = EXCLUDED.holder, expires_at = EXCLUDED.expires_at
+WHERE gmail_canvas_draft_leases.expires_at < clock_timestamp()
+`
+
+type AcquireGmailCanvasDraftLeaseParams struct {
+ ConnectionID string `json:"connection_id"`
+ Holder string `json:"holder"`
+ Seconds float64 `json:"seconds"`
+}
+
+func (q *Queries) AcquireGmailCanvasDraftLease(ctx context.Context, arg AcquireGmailCanvasDraftLeaseParams) (int64, error) {
+ result, err := q.db.Exec(ctx, acquireGmailCanvasDraftLease, arg.ConnectionID, arg.Holder, arg.Seconds)
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
+}
+
+const getGmailCanvasDraft = `-- name: GetGmailCanvasDraft :one
+SELECT draft.document_id, draft.source_digest, document.tenant_id
+FROM gmail_canvas_drafts draft
+JOIN documents document ON document.id = draft.document_id
+WHERE draft.connection_id = $1 AND draft.draft_id = $2
+`
+
+type GetGmailCanvasDraftParams struct {
+ ConnectionID string `json:"connection_id"`
+ DraftID string `json:"draft_id"`
+}
+
+type GetGmailCanvasDraftRow struct {
+ DocumentID string `json:"document_id"`
+ SourceDigest string `json:"source_digest"`
+ TenantID string `json:"tenant_id"`
+}
+
+func (q *Queries) GetGmailCanvasDraft(ctx context.Context, arg GetGmailCanvasDraftParams) (GetGmailCanvasDraftRow, error) {
+ row := q.db.QueryRow(ctx, getGmailCanvasDraft, arg.ConnectionID, arg.DraftID)
+ var i GetGmailCanvasDraftRow
+ err := row.Scan(&i.DocumentID, &i.SourceDigest, &i.TenantID)
+ return i, err
+}
+
+const holdGmailCanvasDraftLease = `-- name: HoldGmailCanvasDraftLease :one
+SELECT holder FROM gmail_canvas_draft_leases
+WHERE connection_id = $1 AND holder = $2 AND expires_at > clock_timestamp()
+FOR UPDATE
+`
+
+type HoldGmailCanvasDraftLeaseParams struct {
+ ConnectionID string `json:"connection_id"`
+ Holder string `json:"holder"`
+}
+
+func (q *Queries) HoldGmailCanvasDraftLease(ctx context.Context, arg HoldGmailCanvasDraftLeaseParams) (string, error) {
+ row := q.db.QueryRow(ctx, holdGmailCanvasDraftLease, arg.ConnectionID, arg.Holder)
+ var holder string
+ err := row.Scan(&holder)
+ return holder, err
+}
+
+const releaseGmailCanvasDraftLease = `-- name: ReleaseGmailCanvasDraftLease :exec
+DELETE FROM gmail_canvas_draft_leases WHERE connection_id = $1 AND holder = $2
+`
+
+type ReleaseGmailCanvasDraftLeaseParams struct {
+ ConnectionID string `json:"connection_id"`
+ Holder string `json:"holder"`
+}
+
+func (q *Queries) ReleaseGmailCanvasDraftLease(ctx context.Context, arg ReleaseGmailCanvasDraftLeaseParams) error {
+ _, err := q.db.Exec(ctx, releaseGmailCanvasDraftLease, arg.ConnectionID, arg.Holder)
+ return err
+}
+
+const upsertGmailCanvasDraft = `-- name: UpsertGmailCanvasDraft :exec
+INSERT INTO gmail_canvas_drafts(connection_id, draft_id, document_id, source_digest)
+VALUES ($1, $2, $3, $4)
+ON CONFLICT (connection_id, draft_id) DO UPDATE
+SET document_id = EXCLUDED.document_id, source_digest = EXCLUDED.source_digest
+`
+
+type UpsertGmailCanvasDraftParams struct {
+ ConnectionID string `json:"connection_id"`
+ DraftID string `json:"draft_id"`
+ DocumentID string `json:"document_id"`
+ SourceDigest string `json:"source_digest"`
+}
+
+func (q *Queries) UpsertGmailCanvasDraft(ctx context.Context, arg UpsertGmailCanvasDraftParams) error {
+ _, err := q.db.Exec(ctx, upsertGmailCanvasDraft,
+ arg.ConnectionID,
+ arg.DraftID,
+ arg.DocumentID,
+ arg.SourceDigest,
+ )
+ return err
+}
diff --git a/apps/teamhub/internal/store/mail_canvas.sql.go b/apps/teamhub/internal/store/mail_canvas.sql.go
new file mode 100644
index 00000000..fffec085
--- /dev/null
+++ b/apps/teamhub/internal/store/mail_canvas.sql.go
@@ -0,0 +1,234 @@
+// Code generated by sqlc. DO NOT EDIT.
+// versions:
+// sqlc v1.29.0
+// source: mail_canvas.sql
+
+package store
+
+import (
+ "context"
+
+ "github.com/jackc/pgx/v5/pgtype"
+)
+
+const declineMailCanvasDelivery = `-- name: DeclineMailCanvasDelivery :one
+INSERT INTO mail_canvas_deliveries (document_id, id, account_id, connection_id, source_digest, status)
+VALUES ($1, $2, $3, NULL, $4, 'declined')
+ON CONFLICT (document_id) DO UPDATE
+SET id=EXCLUDED.id, account_id=EXCLUDED.account_id, connection_id=NULL,
+ source_digest=EXCLUDED.source_digest, status='declined', error_message='', updated_at=clock_timestamp()
+WHERE mail_canvas_deliveries.status IN ('failed', 'unknown')
+RETURNING document_id, id, account_id, connection_id, source_digest, status, draft_id, message_id, error_message, updated_at
+`
+
+type DeclineMailCanvasDeliveryParams struct {
+ DocumentID string `json:"document_id"`
+ ID string `json:"id"`
+ AccountID string `json:"account_id"`
+ SourceDigest string `json:"source_digest"`
+}
+
+func (q *Queries) DeclineMailCanvasDelivery(ctx context.Context, arg DeclineMailCanvasDeliveryParams) (MailCanvasDelivery, error) {
+ row := q.db.QueryRow(ctx, declineMailCanvasDelivery,
+ arg.DocumentID,
+ arg.ID,
+ arg.AccountID,
+ arg.SourceDigest,
+ )
+ var i MailCanvasDelivery
+ err := row.Scan(
+ &i.DocumentID,
+ &i.ID,
+ &i.AccountID,
+ &i.ConnectionID,
+ &i.SourceDigest,
+ &i.Status,
+ &i.DraftID,
+ &i.MessageID,
+ &i.ErrorMessage,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
+
+const getMailCanvasDelivery = `-- name: GetMailCanvasDelivery :one
+SELECT document_id, id, account_id, connection_id, source_digest, status, draft_id, message_id, error_message, updated_at FROM mail_canvas_deliveries WHERE document_id = $1
+`
+
+func (q *Queries) GetMailCanvasDelivery(ctx context.Context, documentID string) (MailCanvasDelivery, error) {
+ row := q.db.QueryRow(ctx, getMailCanvasDelivery, documentID)
+ var i MailCanvasDelivery
+ err := row.Scan(
+ &i.DocumentID,
+ &i.ID,
+ &i.AccountID,
+ &i.ConnectionID,
+ &i.SourceDigest,
+ &i.Status,
+ &i.DraftID,
+ &i.MessageID,
+ &i.ErrorMessage,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
+
+const getMailCanvasDeliveryByID = `-- name: GetMailCanvasDeliveryByID :one
+SELECT document_id, id, account_id, connection_id, source_digest, status, draft_id, message_id, error_message, updated_at FROM mail_canvas_deliveries WHERE id = $1
+`
+
+func (q *Queries) GetMailCanvasDeliveryByID(ctx context.Context, id string) (MailCanvasDelivery, error) {
+ row := q.db.QueryRow(ctx, getMailCanvasDeliveryByID, id)
+ var i MailCanvasDelivery
+ err := row.Scan(
+ &i.DocumentID,
+ &i.ID,
+ &i.AccountID,
+ &i.ConnectionID,
+ &i.SourceDigest,
+ &i.Status,
+ &i.DraftID,
+ &i.MessageID,
+ &i.ErrorMessage,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
+
+const mailCanvasDeliveryHolds = `-- name: MailCanvasDeliveryHolds :one
+SELECT EXISTS (
+ SELECT 1 FROM mail_canvas_deliveries
+ WHERE document_id = $1 AND status IN ('queued', 'uploading', 'sending', 'sent', 'unknown')
+)
+`
+
+// A card delivery that may have sent, or still may, owns the canvas: no other
+// path sends it.
+func (q *Queries) MailCanvasDeliveryHolds(ctx context.Context, documentID string) (bool, error) {
+ row := q.db.QueryRow(ctx, mailCanvasDeliveryHolds, documentID)
+ var exists bool
+ err := row.Scan(&exists)
+ return exists, err
+}
+
+const recordAgentMailCanvasSend = `-- name: RecordAgentMailCanvasSend :exec
+INSERT INTO mail_canvas_deliveries (document_id, id, account_id, connection_id, source_digest, status, error_message)
+VALUES ($1, $2, $3, $4, $5, $6, $7)
+ON CONFLICT (document_id) DO UPDATE
+SET id=EXCLUDED.id, account_id=EXCLUDED.account_id, connection_id=EXCLUDED.connection_id,
+ source_digest=EXCLUDED.source_digest, status=EXCLUDED.status, draft_id='', message_id='',
+ error_message=EXCLUDED.error_message, updated_at=clock_timestamp()
+WHERE mail_canvas_deliveries.status IN ('failed', 'declined')
+`
+
+type RecordAgentMailCanvasSendParams struct {
+ DocumentID string `json:"document_id"`
+ ID string `json:"id"`
+ AccountID string `json:"account_id"`
+ ConnectionID pgtype.Text `json:"connection_id"`
+ SourceDigest string `json:"source_digest"`
+ Status string `json:"status"`
+ ErrorMessage string `json:"error_message"`
+}
+
+// An Agent's confirmed send of a canvas draft, so the card never sends it
+// again; an active card delivery already refused that send.
+func (q *Queries) RecordAgentMailCanvasSend(ctx context.Context, arg RecordAgentMailCanvasSendParams) error {
+ _, err := q.db.Exec(ctx, recordAgentMailCanvasSend,
+ arg.DocumentID,
+ arg.ID,
+ arg.AccountID,
+ arg.ConnectionID,
+ arg.SourceDigest,
+ arg.Status,
+ arg.ErrorMessage,
+ )
+ return err
+}
+
+const startMailCanvasDelivery = `-- name: StartMailCanvasDelivery :one
+INSERT INTO mail_canvas_deliveries (document_id, id, account_id, connection_id, source_digest, status)
+VALUES ($1, $2, $3, $4, $5, 'queued')
+ON CONFLICT (document_id) DO UPDATE
+SET id=EXCLUDED.id, account_id=EXCLUDED.account_id, connection_id=EXCLUDED.connection_id,
+ -- A draft lives in one mailbox; another connection starts a new one.
+ draft_id=CASE WHEN mail_canvas_deliveries.connection_id IS NOT DISTINCT FROM EXCLUDED.connection_id
+ THEN mail_canvas_deliveries.draft_id ELSE '' END,
+ source_digest=EXCLUDED.source_digest, status='queued', error_message='', updated_at=clock_timestamp()
+WHERE mail_canvas_deliveries.status IN ('failed', 'unknown')
+RETURNING document_id, id, account_id, connection_id, source_digest, status, draft_id, message_id, error_message, updated_at
+`
+
+type StartMailCanvasDeliveryParams struct {
+ DocumentID string `json:"document_id"`
+ ID string `json:"id"`
+ AccountID string `json:"account_id"`
+ ConnectionID pgtype.Text `json:"connection_id"`
+ SourceDigest string `json:"source_digest"`
+}
+
+func (q *Queries) StartMailCanvasDelivery(ctx context.Context, arg StartMailCanvasDeliveryParams) (MailCanvasDelivery, error) {
+ row := q.db.QueryRow(ctx, startMailCanvasDelivery,
+ arg.DocumentID,
+ arg.ID,
+ arg.AccountID,
+ arg.ConnectionID,
+ arg.SourceDigest,
+ )
+ var i MailCanvasDelivery
+ err := row.Scan(
+ &i.DocumentID,
+ &i.ID,
+ &i.AccountID,
+ &i.ConnectionID,
+ &i.SourceDigest,
+ &i.Status,
+ &i.DraftID,
+ &i.MessageID,
+ &i.ErrorMessage,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
+
+const updateMailCanvasDelivery = `-- name: UpdateMailCanvasDelivery :one
+UPDATE mail_canvas_deliveries
+SET status=$1, draft_id=$2, message_id=$3,
+ error_message=$4, updated_at=clock_timestamp()
+WHERE id=$5 AND status=$6
+RETURNING document_id, id, account_id, connection_id, source_digest, status, draft_id, message_id, error_message, updated_at
+`
+
+type UpdateMailCanvasDeliveryParams struct {
+ Status string `json:"status"`
+ DraftID string `json:"draft_id"`
+ MessageID string `json:"message_id"`
+ ErrorMessage string `json:"error_message"`
+ ID string `json:"id"`
+ ExpectedStatus string `json:"expected_status"`
+}
+
+func (q *Queries) UpdateMailCanvasDelivery(ctx context.Context, arg UpdateMailCanvasDeliveryParams) (MailCanvasDelivery, error) {
+ row := q.db.QueryRow(ctx, updateMailCanvasDelivery,
+ arg.Status,
+ arg.DraftID,
+ arg.MessageID,
+ arg.ErrorMessage,
+ arg.ID,
+ arg.ExpectedStatus,
+ )
+ var i MailCanvasDelivery
+ err := row.Scan(
+ &i.DocumentID,
+ &i.ID,
+ &i.AccountID,
+ &i.ConnectionID,
+ &i.SourceDigest,
+ &i.Status,
+ &i.DraftID,
+ &i.MessageID,
+ &i.ErrorMessage,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
diff --git a/apps/teamhub/internal/store/models.go b/apps/teamhub/internal/store/models.go
index 12c01724..8ff94e5a 100644
--- a/apps/teamhub/internal/store/models.go
+++ b/apps/teamhub/internal/store/models.go
@@ -818,6 +818,19 @@ type ExternalMailImportDocument struct {
ConnectionID string `json:"connection_id"`
}
+type GmailCanvasDraft struct {
+ ConnectionID string `json:"connection_id"`
+ DraftID string `json:"draft_id"`
+ DocumentID string `json:"document_id"`
+ SourceDigest string `json:"source_digest"`
+}
+
+type GmailCanvasDraftLease struct {
+ ConnectionID string `json:"connection_id"`
+ Holder string `json:"holder"`
+ ExpiresAt pgtype.Timestamptz `json:"expires_at"`
+}
+
type LocalComputer struct {
ComputerID string `json:"computer_id"`
DisplayName string `json:"display_name"`
@@ -866,6 +879,19 @@ type LocalComputerModelSnapshot struct {
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
}
+type MailCanvasDelivery struct {
+ DocumentID string `json:"document_id"`
+ ID string `json:"id"`
+ AccountID string `json:"account_id"`
+ ConnectionID pgtype.Text `json:"connection_id"`
+ SourceDigest string `json:"source_digest"`
+ Status string `json:"status"`
+ DraftID string `json:"draft_id"`
+ MessageID string `json:"message_id"`
+ ErrorMessage string `json:"error_message"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+}
+
type MemoryIndexChunk struct {
ID string `json:"id"`
TenantID string `json:"tenant_id"`
diff --git a/apps/teamhub/internal/store/queries/gmail_canvas_drafts.sql b/apps/teamhub/internal/store/queries/gmail_canvas_drafts.sql
new file mode 100644
index 00000000..8fc052e0
--- /dev/null
+++ b/apps/teamhub/internal/store/queries/gmail_canvas_drafts.sql
@@ -0,0 +1,26 @@
+-- name: UpsertGmailCanvasDraft :exec
+INSERT INTO gmail_canvas_drafts(connection_id, draft_id, document_id, source_digest)
+VALUES ($1, $2, $3, $4)
+ON CONFLICT (connection_id, draft_id) DO UPDATE
+SET document_id = EXCLUDED.document_id, source_digest = EXCLUDED.source_digest;
+
+-- name: GetGmailCanvasDraft :one
+SELECT draft.document_id, draft.source_digest, document.tenant_id
+FROM gmail_canvas_drafts draft
+JOIN documents document ON document.id = draft.document_id
+WHERE draft.connection_id = $1 AND draft.draft_id = $2;
+
+-- name: AcquireGmailCanvasDraftLease :execrows
+INSERT INTO gmail_canvas_draft_leases(connection_id, holder, expires_at)
+VALUES (sqlc.arg(connection_id), sqlc.arg(holder), clock_timestamp() + make_interval(secs => sqlc.arg(seconds)::float8))
+ON CONFLICT (connection_id) DO UPDATE
+SET holder = EXCLUDED.holder, expires_at = EXCLUDED.expires_at
+WHERE gmail_canvas_draft_leases.expires_at < clock_timestamp();
+
+-- name: HoldGmailCanvasDraftLease :one
+SELECT holder FROM gmail_canvas_draft_leases
+WHERE connection_id = $1 AND holder = $2 AND expires_at > clock_timestamp()
+FOR UPDATE;
+
+-- name: ReleaseGmailCanvasDraftLease :exec
+DELETE FROM gmail_canvas_draft_leases WHERE connection_id = $1 AND holder = $2;
diff --git a/apps/teamhub/internal/store/queries/mail_canvas.sql b/apps/teamhub/internal/store/queries/mail_canvas.sql
new file mode 100644
index 00000000..9c2bbe20
--- /dev/null
+++ b/apps/teamhub/internal/store/queries/mail_canvas.sql
@@ -0,0 +1,52 @@
+-- name: GetMailCanvasDelivery :one
+SELECT * FROM mail_canvas_deliveries WHERE document_id = $1;
+
+-- name: GetMailCanvasDeliveryByID :one
+SELECT * FROM mail_canvas_deliveries WHERE id = $1;
+
+-- name: StartMailCanvasDelivery :one
+INSERT INTO mail_canvas_deliveries (document_id, id, account_id, connection_id, source_digest, status)
+VALUES ($1, $2, $3, $4, $5, 'queued')
+ON CONFLICT (document_id) DO UPDATE
+SET id=EXCLUDED.id, account_id=EXCLUDED.account_id, connection_id=EXCLUDED.connection_id,
+ -- A draft lives in one mailbox; another connection starts a new one.
+ draft_id=CASE WHEN mail_canvas_deliveries.connection_id IS NOT DISTINCT FROM EXCLUDED.connection_id
+ THEN mail_canvas_deliveries.draft_id ELSE '' END,
+ source_digest=EXCLUDED.source_digest, status='queued', error_message='', updated_at=clock_timestamp()
+WHERE mail_canvas_deliveries.status IN ('failed', 'unknown')
+RETURNING *;
+
+-- name: UpdateMailCanvasDelivery :one
+UPDATE mail_canvas_deliveries
+SET status=sqlc.arg(status), draft_id=sqlc.arg(draft_id), message_id=sqlc.arg(message_id),
+ error_message=sqlc.arg(error_message), updated_at=clock_timestamp()
+WHERE id=sqlc.arg(id) AND status=sqlc.arg(expected_status)
+RETURNING *;
+
+-- name: DeclineMailCanvasDelivery :one
+INSERT INTO mail_canvas_deliveries (document_id, id, account_id, connection_id, source_digest, status)
+VALUES ($1, $2, $3, NULL, $4, 'declined')
+ON CONFLICT (document_id) DO UPDATE
+SET id=EXCLUDED.id, account_id=EXCLUDED.account_id, connection_id=NULL,
+ source_digest=EXCLUDED.source_digest, status='declined', error_message='', updated_at=clock_timestamp()
+WHERE mail_canvas_deliveries.status IN ('failed', 'unknown')
+RETURNING *;
+
+-- name: MailCanvasDeliveryHolds :one
+-- A card delivery that may have sent, or still may, owns the canvas: no other
+-- path sends it.
+SELECT EXISTS (
+ SELECT 1 FROM mail_canvas_deliveries
+ WHERE document_id = $1 AND status IN ('queued', 'uploading', 'sending', 'sent', 'unknown')
+);
+
+-- name: RecordAgentMailCanvasSend :exec
+-- An Agent's confirmed send of a canvas draft, so the card never sends it
+-- again; an active card delivery already refused that send.
+INSERT INTO mail_canvas_deliveries (document_id, id, account_id, connection_id, source_digest, status, error_message)
+VALUES ($1, $2, $3, $4, $5, sqlc.arg(status), sqlc.arg(error_message))
+ON CONFLICT (document_id) DO UPDATE
+SET id=EXCLUDED.id, account_id=EXCLUDED.account_id, connection_id=EXCLUDED.connection_id,
+ source_digest=EXCLUDED.source_digest, status=EXCLUDED.status, draft_id='', message_id='',
+ error_message=EXCLUDED.error_message, updated_at=clock_timestamp()
+WHERE mail_canvas_deliveries.status IN ('failed', 'declined');
diff --git a/apps/teamhub/internal/voice/voice_live_apps.go b/apps/teamhub/internal/voice/voice_live_apps.go
index c6b02693..dd044a5c 100644
--- a/apps/teamhub/internal/voice/voice_live_apps.go
+++ b/apps/teamhub/internal/voice/voice_live_apps.go
@@ -276,7 +276,13 @@ func (s *Service) voiceLiveMailCanvas(ctx context.Context, session voicelive.Ses
if err != nil {
return app, canvas, agentconnectedapps.CanvasDraft{}, "", err
}
- if canvas.fields["status"] == "sent" {
+ held, err := s.queries.MailCanvasDeliveryHolds(ctx, args.DocumentID)
+ if err != nil {
+ return app, canvas, agentconnectedapps.CanvasDraft{}, "", err
+ }
+ // The card's delivery is the record of a Human send, whether or not an
+ // editor has written it into the header yet.
+ if canvas.fields["status"] == "sent" || held {
// Named, so the model can tell this canvas from the one it meant.
return app, canvas, agentconnectedapps.CanvasDraft{}, voicelive.Output(map[string]string{
"error": "already_sent", "document_id": canvas.documentID, "subject": canvas.fields["subject"], "to": canvas.fields["to"],
diff --git a/apps/teamhub/migrations/00876_bind_gmail_canvas_drafts.sql b/apps/teamhub/migrations/00876_bind_gmail_canvas_drafts.sql
new file mode 100644
index 00000000..490b9d64
--- /dev/null
+++ b/apps/teamhub/migrations/00876_bind_gmail_canvas_drafts.sql
@@ -0,0 +1,21 @@
+-- +goose Up
+CREATE TABLE gmail_canvas_drafts (
+ connection_id text NOT NULL REFERENCES external_connections(id) ON DELETE CASCADE,
+ draft_id text NOT NULL CHECK (length(draft_id) BETWEEN 1 AND 256),
+ document_id text NOT NULL REFERENCES documents(id) ON DELETE CASCADE,
+ source_digest text NOT NULL CHECK (source_digest ~ '^sha256:[0-9a-f]{64}$'),
+ PRIMARY KEY (connection_id, draft_id)
+);
+CREATE INDEX gmail_canvas_drafts_document_idx ON gmail_canvas_drafts(document_id);
+
+-- One draft save per Gmail connection at a time, held without a database
+-- connection while the upload runs; an expired lease may be taken over.
+CREATE TABLE gmail_canvas_draft_leases (
+ connection_id text PRIMARY KEY REFERENCES external_connections(id) ON DELETE CASCADE,
+ holder text NOT NULL,
+ expires_at timestamptz NOT NULL
+);
+
+-- +goose Down
+DROP TABLE gmail_canvas_draft_leases;
+DROP TABLE gmail_canvas_drafts;
diff --git a/apps/teamhub/migrations/00877_mail_canvas_delivery.sql b/apps/teamhub/migrations/00877_mail_canvas_delivery.sql
new file mode 100644
index 00000000..afb015e4
--- /dev/null
+++ b/apps/teamhub/migrations/00877_mail_canvas_delivery.sql
@@ -0,0 +1,17 @@
+-- +goose Up
+CREATE TABLE mail_canvas_deliveries (
+ document_id text PRIMARY KEY REFERENCES documents(id) ON DELETE CASCADE,
+ id text NOT NULL UNIQUE,
+ account_id text NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
+ connection_id text REFERENCES external_connections(id) ON DELETE CASCADE,
+ source_digest text NOT NULL CHECK (source_digest ~ '^sha256:[0-9a-f]{64}$'),
+ status text NOT NULL CHECK (status IN ('queued', 'uploading', 'sending', 'sent', 'failed', 'unknown', 'declined')),
+ CHECK ((status = 'declined') = (connection_id IS NULL)),
+ draft_id text NOT NULL DEFAULT '',
+ message_id text NOT NULL DEFAULT '',
+ error_message text NOT NULL DEFAULT '',
+ updated_at timestamptz NOT NULL DEFAULT clock_timestamp()
+);
+
+-- +goose Down
+DROP TABLE mail_canvas_deliveries;
diff --git a/apps/teamhub/tests/integration/connector_confirmation_test.go b/apps/teamhub/tests/integration/connector_confirmation_test.go
index 88af1523..36079a89 100644
--- a/apps/teamhub/tests/integration/connector_confirmation_test.go
+++ b/apps/teamhub/tests/integration/connector_confirmation_test.go
@@ -9,6 +9,7 @@ import (
"net/http"
"strings"
"testing"
+ "time"
"github.com/simplexai-labs/linger/apps/teamhub/internal/agentauth"
"github.com/simplexai-labs/linger/apps/teamhub/internal/agentconnectedapps"
@@ -240,6 +241,96 @@ func TestConnectorConfirmationRunsStoredCallOnceAfterApproval(t *testing.T) {
if bodies := notices(); provider.sends != 1 || status(draft.DecisionID) != "failed" || !strings.Contains(bodies[len(bodies)-1], "draft changed") {
t.Fatalf("changed draft sends=%d status=%s notices=%v", provider.sends, status(draft.DecisionID), bodies)
}
+ // A canvas edit must invalidate an unchanged remote draft, including after restart.
+ if _, err := env.pool.Exec(t.Context(), `INSERT INTO documents(id,tenant_id,title,format,owner_actor_id,owner_actor_kind,creator_actor_id,creator_actor_kind,status) VALUES('document_mail_guard','tenant_acme','Mail','blocknote','actor_acme_alice','human','actor_acme_alice','human','active')`); err != nil {
+ t.Fatal(err)
+ }
+ source := &confirmationCanvasSource{digest: "sha256:" + strings.Repeat("a", 64)}
+ service.SetCanvasReader(source)
+ built := agentconnectedapps.CanvasDraft{Raw: "raw-draft", DocumentID: "document_mail_guard", SourceDigest: source.digest}
+ if _, err := service.SaveGmailCanvasDraft(ctx, issued.AccessToken, "connection_confirm_gmail", "draft-1", built); err != nil {
+ t.Fatal(err)
+ }
+ provider.draftBody = "Draft body"
+ draftInput := agentconnectedapps.ExecuteInput{ConnectionID: "connection_confirm_gmail", ToolSlug: "GMAIL_SEND_DRAFT", ToolVersion: "20261015_00", Arguments: map[string]any{"draft_id": "draft-1"}}
+ canvasStale := submit(draftInput, "canvas-stale")
+ source.digest = "sha256:" + strings.Repeat("b", 64)
+ service = agentconnectedapps.New(env.pool, agentauth.New(env.pool), newFakeComposio(t).externalSources(t, env.pool, nil), provider)
+ service.SetCanvasReader(source)
+ decide(canvasStale, "approve", "")
+ run(canvasStale.DecisionID)
+ if status(canvasStale.DecisionID) != "failed" || provider.sends != 1 {
+ t.Fatalf("stale canvas was sent: status=%s sends=%d", status(canvasStale.DecisionID), provider.sends)
+ }
+ if _, err := service.Execute(ctx, issued.AccessToken, draftInput); err == nil {
+ t.Fatal("stale canvas accepted a new confirmation")
+ }
+ built.SourceDigest = source.digest
+ if _, err := service.SaveGmailCanvasDraft(ctx, issued.AccessToken, "connection_confirm_gmail", "draft-1", built); err != nil {
+ t.Fatal(err)
+ }
+ fresh := submit(draftInput, "canvas-fresh")
+ decide(fresh, "approve", "")
+ run(fresh.DecisionID)
+ if status(fresh.DecisionID) != "succeeded" || provider.sends != 2 {
+ t.Fatalf("updated canvas was not sent: status=%s sends=%d", status(fresh.DecisionID), provider.sends)
+ }
+ // The confirmed send is recorded on the canvas, so its chat card cannot
+ // send the same email again.
+ if countRows(t, env, `SELECT count(*) FROM mail_canvas_deliveries WHERE document_id='document_mail_guard' AND status='sent' AND connection_id='connection_confirm_gmail'`) != 1 {
+ t.Fatal("the Agent's canvas send was not recorded")
+ }
+
+ // Draft saves of one connection take turns through a lease that holds
+ // no database connection during the upload.
+ exec := func(query string, arguments ...any) {
+ t.Helper()
+ if _, err := env.pool.Exec(t.Context(), query, arguments...); err != nil {
+ t.Fatal(err)
+ }
+ }
+ binding := func() string {
+ t.Helper()
+ var digest string
+ if err := env.pool.QueryRow(t.Context(), `SELECT source_digest FROM gmail_canvas_drafts WHERE connection_id='connection_confirm_gmail' AND draft_id='draft-1'`).Scan(&digest); err != nil {
+ t.Fatal(err)
+ }
+ return digest
+ }
+ edited := built
+ edited.SourceDigest = "sha256:" + strings.Repeat("c", 64)
+ // Another save holds the lease: this one waits and gives up retryable
+ // without uploading.
+ exec(`INSERT INTO gmail_canvas_draft_leases(connection_id,holder,expires_at) VALUES('connection_confirm_gmail','other_save',clock_timestamp()+interval '1 minute')`)
+ waiting, cancel := context.WithTimeout(ctx, time.Second)
+ _, err = service.SaveGmailCanvasDraft(waiting, issued.AccessToken, "connection_confirm_gmail", "draft-1", edited)
+ cancel()
+ var busy *agentconnectedapps.Error
+ if !errors.As(err, &busy) || busy.Code != "provider_unavailable" || !busy.Retryable || provider.saves != 2 || binding() != built.SourceDigest {
+ t.Fatalf("save under another lease err=%v saves=%d binding=%s", err, provider.saves, binding())
+ }
+ // A lease a crashed save left is taken over once it expires.
+ exec(`UPDATE gmail_canvas_draft_leases SET expires_at=clock_timestamp()-interval '1 second'`)
+ if _, err := service.SaveGmailCanvasDraft(ctx, issued.AccessToken, "connection_confirm_gmail", "draft-1", edited); err != nil || binding() != edited.SourceDigest {
+ t.Fatalf("save after an expired lease err=%v binding=%s", err, binding())
+ }
+ if countRows(t, env, `SELECT count(*) FROM gmail_canvas_draft_leases`) != 0 {
+ t.Fatal("a finished save kept its lease")
+ }
+ // A save whose lease was taken over mid-upload leaves the draft unbound
+ // to its content, so no send trusts it.
+ provider.onSave = func() {
+ exec(`UPDATE gmail_canvas_draft_leases SET holder='other_save'`)
+ }
+ lost := built
+ lost.SourceDigest = "sha256:" + strings.Repeat("d", 64)
+ _, err = service.SaveGmailCanvasDraft(ctx, issued.AccessToken, "connection_confirm_gmail", "draft-1", lost)
+ provider.onSave = nil
+ var uncertain *agentconnectedapps.Error
+ if !errors.As(err, &uncertain) || uncertain.Code != "tool_execution_failed" || binding() != edited.SourceDigest {
+ t.Fatalf("save that lost its lease err=%v binding=%s", err, binding())
+ }
+
}
// An idempotent kind declares Rerun: a run that stopped midway runs again on
@@ -301,6 +392,9 @@ func TestDecisionRerunsAnIdempotentKindAfterAnInterruptedRun(t *testing.T) {
type confirmationToolProvider struct {
sends int
draftBody string
+ // saves counts draft uploads; onSave, when set, runs during one.
+ saves int
+ onSave func()
}
func (p *confirmationToolProvider) SearchTools(context.Context, composio.ToolSearchRequest) ([]composio.Tool, error) {
@@ -328,3 +422,16 @@ func (p *confirmationToolProvider) ExecuteTool(_ context.Context, _, _, slug, _
p.sends++
return composio.ToolExecution{Successful: true, Data: map[string]any{"id": "sent-1"}}, nil
}
+
+type confirmationCanvasSource struct{ digest string }
+
+func (s *confirmationCanvasSource) SourceDigest(context.Context, string, string, string) (string, error) {
+ return s.digest, nil
+}
+func (p *confirmationToolProvider) SaveGmailDraft(context.Context, string, string, string) (composio.GmailDraft, error) {
+ p.saves++
+ if p.onSave != nil {
+ p.onSave()
+ }
+ return composio.GmailDraft{DraftID: "draft-1"}, nil
+}
diff --git a/apps/teamhub/tests/integration/mail_canvas_test.go b/apps/teamhub/tests/integration/mail_canvas_test.go
new file mode 100644
index 00000000..fe2c2460
--- /dev/null
+++ b/apps/teamhub/tests/integration/mail_canvas_test.go
@@ -0,0 +1,256 @@
+package integration_test
+
+import (
+ "encoding/json"
+ "net/http"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgxpool"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/app"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/composio"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/config"
+ teamhubinternal "github.com/simplexai-labs/linger/contracts-go/teamhubinternal"
+)
+
+// The Human sends a Gmail canvas from its chat card: editing never reaches
+// Gmail, Send uploads and sends exactly the reviewed version once, and Don't
+// send is final.
+func TestHumanSendsAGmailCanvasOnlyWhenSendIsClicked(t *testing.T) {
+ allowParallelIntegrationTest(t)
+ var computes atomic.Int32
+ replaced := make(chan string, 32)
+ var bodies *pgxpool.Pool
+ runtime := canvasRuntime(t, &computes, replaced, func() *pgxpool.Pool { return bodies })
+ composioFake := newFakeComposio(t)
+ var mu sync.Mutex
+ var saves, sends int
+ failNextUpload, failNextSend, draftGone := false, false, false
+ composioFake.setIntercept(func(w http.ResponseWriter, r *http.Request) bool {
+ if r.Method != http.MethodPost || r.URL.Path != "/api/v3.1/tools/execute/proxy" {
+ return false
+ }
+ var request struct {
+ Endpoint string `json:"endpoint"`
+ }
+ if json.NewDecoder(r.Body).Decode(&request) != nil {
+ return false
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ data := json.RawMessage(`{"id":"draft-1","message":{"id":"message-1","threadId":"thread-1"}}`)
+ if failNextUpload && !strings.HasSuffix(request.Endpoint, "/drafts/send") {
+ failNextUpload = false
+ w.WriteHeader(http.StatusBadRequest)
+ _ = json.NewEncoder(w).Encode(map[string]any{"error": map[string]any{"message": "rejected"}})
+ return true
+ }
+ if draftGone && !strings.HasSuffix(request.Endpoint, "/drafts/send") {
+ draftGone = false
+ w.WriteHeader(http.StatusNotFound)
+ _ = json.NewEncoder(w).Encode(map[string]any{"error": map[string]any{"message": "not found"}})
+ return true
+ }
+ if failNextSend && strings.HasSuffix(request.Endpoint, "/drafts/send") {
+ failNextSend = false
+ w.WriteHeader(http.StatusBadGateway)
+ _ = json.NewEncoder(w).Encode(map[string]any{"error": map[string]any{"message": "upstream"}})
+ return true
+ }
+ if strings.HasSuffix(request.Endpoint, "/drafts/send") {
+ sends++
+ data = json.RawMessage(`{"id":"sent-1"}`)
+ } else {
+ saves++
+ }
+ _ = json.NewEncoder(w).Encode(map[string]any{"status": http.StatusOK, "data": data})
+ return true
+ })
+ counts := func() (int, int) {
+ mu.Lock()
+ defer mu.Unlock()
+ return saves, sends
+ }
+ env, alice, _, sessionID := newVoiceLiveRoomWith(t, []appOption{starting(app.JobQueue)}, func(cfg *config.Config) {
+ cfg.RoomDocument.RuntimeURL = runtime.URL
+ composioFake.configure(cfg)
+ })
+ bodies = env.pool
+ composioFake.seedAccount(t, env.pool, "ca_mail_gmail", "account_alice", "gmail", composio.ConnectionActive)
+ if _, err := env.pool.Exec(t.Context(), `
+ INSERT INTO external_connections(id,account_id,provider,upstream_connection_id,status,revision,remote_principal_key,identity_label,toolkit_slug,auth_config_id,auto_reminders) VALUES('connection_mail_gmail','account_alice','gmail','ca_mail_gmail','active',1,'gmail:[email protected]','[email protected]','gmail','ac_gmail',false);
+ INSERT INTO external_connection_agent_grants(id,connection_id,tenant_id,agent_actor_id,represented_human_actor_id,status) VALUES('grant_mail_gmail','connection_mail_gmail','tenant_acme','actor_acme_official','actor_acme_alice','active')`); err != nil {
+ t.Fatal(err)
+ }
+ voice := func(callID, name string, arguments map[string]any) map[string]string {
+ t.Helper()
+ encoded, _ := json.Marshal(arguments)
+ var result teamhubinternal.VoiceLiveToolResult
+ decode(t, voiceRuntimeCall(t, env, http.MethodPost, "/internal/v1/voice/live-tool-calls", map[string]any{
+ "voice_session_id": sessionID, "turn_id": "lt_" + callID, "call_id": callID, "name": name, "arguments": string(encoded),
+ }, http.StatusOK), &result)
+ var output map[string]string
+ if err := json.Unmarshal([]byte(result.Output), &output); err != nil {
+ t.Fatalf("%s=%s", callID, result.Output)
+ }
+ return output
+ }
+ open := func(callID, subject string) string {
+ t.Helper()
+ output := voice(callID, "open_email_canvas", map[string]any{"to": "[email protected]", "subject": subject, "body": "Hi Amy,\n\nSee you Wednesday."})
+ if output["document_id"] == "" {
+ t.Fatalf("open=%v", output)
+ }
+ return output["document_id"]
+ }
+ type mailState struct {
+ Status string `json:"status"`
+ Subject string `json:"subject"`
+ To string `json:"to"`
+ Error string `json:"error"`
+ SourceDigest string `json:"source_digest"`
+ }
+ read := func(documentID string) mailState {
+ t.Helper()
+ status, _, body := env.request(alice, http.MethodGet, "/v0/documents/"+documentID+"/mail", nil, "")
+ var state mailState
+ if status != http.StatusOK || json.Unmarshal(body, &state) != nil {
+ t.Fatalf("read mail=%d %s", status, body)
+ }
+ return state
+ }
+ send := func(documentID, requestID, digest string) (int, []byte) {
+ status, _, body := env.request(alice, http.MethodPost, "/v0/documents/"+documentID+"/mail", map[string]string{
+ "connection_id": "connection_mail_gmail", "request_id": requestID, "source_digest": digest,
+ }, "")
+ return status, body
+ }
+
+ documentID := open("mail-1", "Wed pickup")
+ draft := read(documentID)
+ if draft.Status != "draft" || draft.Subject != "Wed pickup" || draft.To != "[email protected]" || !strings.HasPrefix(draft.SourceDigest, "sha256:") {
+ t.Fatalf("draft=%+v", draft)
+ }
+ // Opening and reading the email never reaches Gmail.
+ if s, n := counts(); s != 0 || n != 0 {
+ t.Fatalf("before Send saves=%d sends=%d", s, n)
+ }
+ // A version the Human did not review is refused.
+ if status, body := send(documentID, "request-stale-0000001", "sha256:"+strings.Repeat("0", 64)); status != http.StatusConflict {
+ t.Fatalf("stale digest=%d %s", status, body)
+ }
+ settle := func(documentID string) string {
+ t.Helper()
+ deadline := time.Now().Add(20 * time.Second)
+ for {
+ if status := read(documentID).Status; status != "queued" && status != "uploading" && status != "sending" {
+ return status
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("delivery did not settle: %+v", read(documentID))
+ }
+ time.Sleep(100 * time.Millisecond)
+ }
+ }
+ // A rejected upload sent nothing, so the email can be sent again.
+ mu.Lock()
+ failNextUpload = true
+ mu.Unlock()
+ if status, body := send(documentID, "request-fail-00000001", draft.SourceDigest); status != http.StatusAccepted {
+ t.Fatalf("send=%d %s", status, body)
+ }
+ if status := settle(documentID); status != "failed" {
+ t.Fatalf("rejected upload=%s", status)
+ }
+ if s, n := counts(); s != 0 || n != 0 {
+ t.Fatalf("after rejected upload saves=%d sends=%d", s, n)
+ }
+ if status, body := send(documentID, "request-send-00000001", draft.SourceDigest); status != http.StatusAccepted {
+ t.Fatalf("send=%d %s", status, body)
+ }
+ deadline := time.Now().Add(20 * time.Second)
+ for read(documentID).Status != "sent" {
+ if time.Now().After(deadline) {
+ var job string
+ _ = env.pool.QueryRow(t.Context(), `SELECT state||' attempt='||attempt||' queue='||queue||' errors='||coalesce(errors::text,'') FROM river_job WHERE kind='mail.canvas_delivery'`).Scan(&job)
+ t.Fatalf("delivery did not finish: %+v job=%s", read(documentID), job)
+ }
+ time.Sleep(100 * time.Millisecond)
+ }
+ if s, n := counts(); s != 1 || n != 1 {
+ t.Fatalf("after Send saves=%d sends=%d", s, n)
+ }
+ // The card's delivery is the record: voice cannot send it again, even
+ // though no editor wrote the sent status into the canvas header.
+ if again := voice("mail-voice", "send_email_canvas", map[string]any{"document_id": documentID, "confirmed": true}); again["error"] != "already_sent" {
+ t.Fatalf("voice resend=%v", again)
+ }
+ // The same click replays its receipt; another one cannot send it again.
+ if status, body := send(documentID, "request-send-00000001", draft.SourceDigest); status != http.StatusAccepted || !strings.Contains(string(body), `"sent"`) {
+ t.Fatalf("replayed send=%d %s", status, body)
+ }
+ if status, body := send(documentID, "request-send-00000002", draft.SourceDigest); status != http.StatusConflict {
+ t.Fatalf("second send=%d %s", status, body)
+ }
+ if status, _, body := env.request(alice, http.MethodPost, "/v0/documents/"+documentID+"/mail/decline", nil, ""); status != http.StatusConflict {
+ t.Fatalf("decline after send=%d %s", status, body)
+ }
+
+ // Don't send is final and never reaches Gmail.
+ declinedID := open("mail-2", "Thu pickup")
+ if status, _, body := env.request(alice, http.MethodPost, "/v0/documents/"+declinedID+"/mail/decline", nil, ""); status != http.StatusOK || !strings.Contains(string(body), `"declined"`) {
+ t.Fatalf("decline=%d %s", status, body)
+ }
+ if status, body := send(declinedID, "request-send-00000003", read(declinedID).SourceDigest); status != http.StatusConflict {
+ t.Fatalf("send after decline=%d %s", status, body)
+ }
+ if s, n := counts(); s != 1 || n != 1 {
+ t.Fatalf("after decline saves=%d sends=%d", s, n)
+ }
+
+ // An unconfirmed send is unknown; after checking Gmail the Human may send
+ // it again instead of being stuck.
+ unsureID := open("mail-3", "Fri pickup")
+ mu.Lock()
+ failNextSend = true
+ mu.Unlock()
+ if status, body := send(unsureID, "request-send-00000004", read(unsureID).SourceDigest); status != http.StatusAccepted {
+ t.Fatalf("send=%d %s", status, body)
+ }
+ if status := settle(unsureID); status != "unknown" {
+ t.Fatalf("unconfirmed send=%s", status)
+ }
+ if again := voice("mail-voice-3", "send_email_canvas", map[string]any{"document_id": unsureID, "confirmed": true}); again["error"] != "already_sent" {
+ t.Fatalf("voice send of an unknown delivery=%v", again)
+ }
+ // A transient upload error keeps the draft and says nothing was sent.
+ mu.Lock()
+ failNextUpload = true
+ mu.Unlock()
+ if status, body := send(unsureID, "request-send-00000007", read(unsureID).SourceDigest); status != http.StatusAccepted {
+ t.Fatalf("send again after unknown=%d %s", status, body)
+ }
+ if status := settle(unsureID); status != "failed" || !strings.Contains(read(unsureID).Error, "Nothing was sent") {
+ t.Fatalf("transient upload error=%s %+v", status, read(unsureID))
+ }
+ // Gmail no longer has the earlier draft, as after a send that went out:
+ // the card says it may have been sent instead of "nothing was sent".
+ mu.Lock()
+ draftGone = true
+ mu.Unlock()
+ if status, body := send(unsureID, "request-send-00000005", read(unsureID).SourceDigest); status != http.StatusAccepted {
+ t.Fatalf("send again after unknown=%d %s", status, body)
+ }
+ if status := settle(unsureID); status != "failed" || !strings.Contains(read(unsureID).Error, "may already have been sent") {
+ t.Fatalf("lost draft=%s %+v", status, read(unsureID))
+ }
+ if status, body := send(unsureID, "request-send-00000006", read(unsureID).SourceDigest); status != http.StatusAccepted {
+ t.Fatalf("send after checking Gmail=%d %s", status, body)
+ }
+ if status := settle(unsureID); status != "sent" {
+ t.Fatalf("resend after unknown=%s", status)
+ }
+}
diff --git a/apps/teamhub/tests/integration/voice_live_test.go b/apps/teamhub/tests/integration/voice_live_test.go
index 3b3cc009..59652e15 100644
--- a/apps/teamhub/tests/integration/voice_live_test.go
+++ b/apps/teamhub/tests/integration/voice_live_test.go
@@ -27,6 +27,13 @@ const voiceLiveRuntimeToken = "voice-live-test-token"
// newVoiceLiveRoom opens Alice's chat_live session in a group Room whose reply
// Agent is her AnotherMe, after proving the Room is ineligible without one.
func newVoiceLiveRoom(t *testing.T, configure ...func(*config.Config)) (*testEnv, *http.Client, string, string) {
+ t.Helper()
+ return newVoiceLiveRoomWith(t, nil, configure...)
+}
+
+// newVoiceLiveRoomWith is newVoiceLiveRoom with extra App options, such as
+// starting background work the test observes.
+func newVoiceLiveRoomWith(t *testing.T, options []appOption, configure ...func(*config.Config)) (*testEnv, *http.Client, string, string) {
t.Helper()
providerAPI := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/protobuf")
@@ -40,7 +47,7 @@ func newVoiceLiveRoom(t *testing.T, configure ...func(*config.Config)) (*testEnv
for _, more := range configure {
more(cfg)
}
- }, withVoiceMedia(media))
+ }, append([]appOption{withVoiceMedia(media)}, options...)...)
provider, err := voicemedia.NewLiveKitProvider(voicemedia.LiveKitConfig{APIURL: providerAPI.URL, PublicURL: providerAPI.URL, APIKey: "test", APISecret: "test"}, env.pool)
if err != nil {
t.Fatal(err)
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index 29124f5b..f409164a 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -39,6 +39,24 @@ build:assets` to check the initial JS budget.
## Important Conventions
+- Gmail and Outlook message approvals show the subject and recipients once.
+ The subject row toggles the preview and owns its hover highlight; the
+ recipient line stays outside the control. The shared AutoHeight transition
+ and chevron rotation use the chat resize timing and reduced-motion setting.
+ Expanding replaces the compact recipient line with read-only
+ From/To/Cc/Bcc headers, followed by the full body and attachments. An empty
+ Cc row reads None; Bcc appears only when populated. Email
+ actions are Send and Don't send; declining does not request a reason.
+- A gmail canvas message segment renders as its email card
+ (`rooms/chat/message-mail-canvas.tsx`), laid out like a message approval:
+ subject row with open-in-panel and expand controls, recipient line, then
+ Send and Don't send, or one receipt line once decided; an unknown result
+ keeps Send again and Don't send. Only members who can edit see the actions,
+ and with several Gmail accounts a Send from picker chooses the sender.
+ Expanding mounts the same collaborative editor as the side panel; Send waits
+ until it is saved and posts the digest the card last loaded, refreshed after
+ each durable save. Clicking Send is what uploads to Gmail; the side-panel
+ canvas has no Send.
- Active product data comes from TeamHub, never retired Workspace APIs. Web has
no fixture backend and no build mode that swaps TeamHub out.
- Unit tests that need TeamHub use `createTestTeamHubRuntime`
diff --git a/apps/web/src/features/rooms/cards/decision-card.test.tsx b/apps/web/src/features/rooms/cards/decision-card.test.tsx
index 61fcd4f8..372d0930 100644
--- a/apps/web/src/features/rooms/cards/decision-card.test.tsx
+++ b/apps/web/src/features/rooms/cards/decision-card.test.tsx
@@ -167,16 +167,16 @@ function openSummary() {
}
describe("DecisionCard", () => {
- it("heads the box with the title and shows the email as one summary row that opens to the message", () => {
+ it("shows the subject and recipient once and expands into a complete email", () => {
renderCard(
connectorCard(
messageDetail({
attachments: ["plan.pdf", "budget.xlsx"],
- bcc: ["[email protected]"],
+ bcc: ["<[email protected]>"],
body: "Hello Bob,\n\nThe launch moves to Friday.",
subject: "Launch date",
+ to: ["<[email protected]>"],
}),
),
);
@@ -186,32 +186,48 @@ describe("DecisionCard", () => {
expect(
within(box).getByRole("heading", {
level: 3,
- name: "Send an email to [email protected]",
+ name: "Launch date",
}),
).toBeVisible();
- expect(
- screen.getAllByText("Send an email to [email protected]"),
- ).toHaveLength(1);
+ expect(screen.getAllByText("Launch date")).toHaveLength(1);
+ expect(screen.getAllByText(/[email protected]/)).toHaveLength(1);
+ expect(screen.getByText("To [email protected]")).toBeVisible();
+ expect(screen.queryByText(/[email protected]/)).not.toBeInTheDocument();
expect(document.querySelector(".card-prompt")).toBeNull();
const row = within(box).getByRole("button", { expanded: false });
- expect(row).toHaveTextContent("[email protected] · Launch date");
- expect(row).toHaveTextContent("Gmail · [email protected]");
+ expect(row).toHaveAccessibleName("Launch date");
+ expect(within(row).getByText("Launch date")).toBeVisible();
+ expect(
+ within(row).queryByText("To [email protected]"),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "Add a reason" }),
+ ).not.toBeInTheDocument();
expect(
screen.queryByRole("region", { name: "Message preview" }),
).not.toBeInTheDocument();
fireEvent.click(row);
expect(row).toHaveAttribute("aria-expanded", "true");
+ expect(row).toHaveAccessibleName("Launch date");
const preview = messagePreview();
for (const [label, value] of [
+ ["From", "[email protected]"],
["To", "[email protected]"],
["Bcc", "[email protected]"],
- ["Subject", "Launch date"],
] as const) {
expect(within(preview).getByText(label)).toBeInTheDocument();
expect(within(preview).getByText(value)).toBeInTheDocument();
}
+ expect(screen.getAllByText("Launch date")).toHaveLength(1);
+ expect(
+ screen.getByText("To [email protected]").closest('[aria-hidden="true"]'),
+ ).not.toBeNull();
+ expect(within(preview).getByTestId("message-body")).not.toHaveClass(
+ "max-h-80",
+ "overflow-auto",
+ );
expect(within(preview).queryByText("Where")).not.toBeInTheDocument();
expect(
within(preview).getByText("Hello Bob,\n\nThe launch moves to Friday.", {
@@ -233,6 +249,66 @@ describe("DecisionCard", () => {
expect(
screen.queryByRole("region", { name: "Message preview" }),
).not.toBeInTheDocument();
+ expect(screen.getByText("To [email protected]")).toBeVisible();
+ });
+
+ it("declines email without a reason and blocks repeated decisions while submitting", async () => {
+ let finish!: () => void;
+ const pending = new Promise<void>((resolve) => {
+ finish = resolve;
+ });
+ const { onDecision } = renderCard(
+ connectorCard(),
+ sponsor.id,
+ vi.fn(() => pending),
+ );
+ expect(screen.queryByRole("textbox")).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "Add a reason" }),
+ ).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "Don't send" }));
+ expect(onDecision).toHaveBeenCalledExactlyOnceWith({
+ decision: "deny",
+ expectedVersion: 1,
+ feedback: undefined,
+ messageId: "message_1",
+ requestId: "decision_1",
+ });
+ expect(screen.getByRole("button", { name: "Send" })).toBeDisabled();
+ expect(screen.getByRole("button", { name: "Don't send" })).toBeDisabled();
+ finish();
+ await vi.waitFor(() =>
+ expect(screen.getByRole("button", { name: "Send" })).toBeEnabled(),
+ );
+ });
+
+ it("uses the email layout for Outlook and keeps an empty Cc row visible", async () => {
+ renderCard(
+ connectorCard({
+ ...messageDetail({
+ }),
+ account: "<[email protected]>",
+ app: "outlook",
+ }),
+ );
+ expect(screen.getByRole("heading", { name: /^No subject/ })).toBeVisible();
+ expect(
+ screen.getByText("To [email protected], Carol <[email protected]>"),
+ ).toBeVisible();
+ openSummary();
+ await vi.waitFor(() => expect(messagePreview()).toBeVisible());
+ expect(
+ within(messagePreview()).getByText("[email protected]"),
+ ).toBeVisible();
+ expect(
+ within(messagePreview()).getByText(
+ ),
+ ).toBeVisible();
+ expect(screen.getByText("Cc")).toBeVisible();
+ expect(screen.getByText("None")).toBeVisible();
+ expect(screen.queryByText("Bcc")).not.toBeInTheDocument();
});
it("names the app by its readable name and falls back to its key", () => {
@@ -273,6 +349,7 @@ describe("DecisionCard", () => {
expect(source).toContain("<p>Hi <b>Bob</b></p>");
expect(source).toContain("p{color:red}");
expect(source).toContain("Content-Security-Policy");
+ expect(source).toContain("padding:16px 0");
expect(source).not.toMatch(/<script|onerror|javascript:/i);
expect(source).toContain(
'<a href="https://example.com/doc" target="_blank" rel="noopener noreferrer">doc</a>',
@@ -678,7 +755,10 @@ describe("DecisionCard", () => {
expect(line.closest("p")?.querySelector("svg")).toHaveClass(tone);
// The heading and the collapsed summary row stay.
expect(
- screen.getByRole("heading", { level: 3, name: card.title }),
+ screen.getByRole("heading", {
+ level: 3,
+ name: card.connector_write?.message ? "No subject" : card.title,
+ }),
).toBeVisible();
expect(document.querySelector(".card-prompt")).toBeNull();
expect(screen.getByRole("button", { expanded: false })).toBeVisible();
diff --git a/apps/web/src/features/rooms/cards/decision-card.tsx b/apps/web/src/features/rooms/cards/decision-card.tsx
index d87b9c4a..481a4d12 100644
--- a/apps/web/src/features/rooms/cards/decision-card.tsx
+++ b/apps/web/src/features/rooms/cards/decision-card.tsx
@@ -13,6 +13,7 @@ import {
} from "@hugeicons/core-free-icons";
import { lazy, type ReactNode, Suspense, useState } from "react";
+import { Button } from "@/components/ui/button";
import { Icon, type IconSvgElement } from "@/components/ui/icon";
import type { TeamHubMessageCard } from "@/features/teamhub/teamhub-types";
@@ -27,7 +28,10 @@ import { CardBox, CardDone, type ReceiptTone } from "./card-shell";
import { ConnectedAppIcon } from "./connected-app-identity";
import { connectedAppDisplayName } from "./connected-app-names";
import { AgentChangeDecisionView } from "./decision-agent-change-view";
-import { ConnectorWriteDecisionView } from "./decision-connector-write-view";
+import {
+ ConnectorWriteDecisionView,
+ EmailDecisionView,
+} from "./decision-connector-write-view";
import {
OpenCreatedRoomLink,
RoomCreationDecisionView,
@@ -166,6 +170,12 @@ function ApprovalDecision({
const [decisionError, setDecisionError] = useState<string | null>(null);
const state = decisionState(card, now);
const roomCreation = card.kind === "room_creation";
+ const write = card.connector_write;
+ const email =
+ write?.kind === "message" &&
+ (write.app === "gmail" || write.app === "outlook")
+ ? write.message
+ : undefined;
const canDecide =
state === "pending" &&
Boolean(currentActorId) &&
@@ -212,14 +222,18 @@ function ApprovalDecision({
return (
<>
- <CardBox heading={card.title} label={label}>
- <CardRow
- detail={summary.detail}
- icon={summary.icon}
- onToggle={() => setOpen((current) => !current)}
- open={open}
- title={summary.title}
- />
+ <CardBox heading={email ? undefined : card.title} label={label}>
+ {email ? (
+ <EmailDecisionView account={write?.account ?? ""} message={email} />
+ ) : (
+ <CardRow
+ detail={summary.detail}
+ icon={summary.icon}
+ onToggle={() => setOpen((current) => !current)}
+ open={open}
+ title={summary.title}
+ />
+ )}
{/* Why the review stopped the call: what a person weighs before
allowing it, so it stays in view. */}
{card.runtime_permission?.rationale?.trim() ? (
@@ -227,7 +241,7 @@ function ApprovalDecision({
{card.runtime_permission.rationale}
</p>
) : null}
- <CardRowDetails open={open}>
+ <CardRowDetails open={!email && open}>
{state === "pending" ? null : screenshot}
{card.connector_write ? (
<ConnectorWriteDecisionView view={card.connector_write} />
@@ -250,14 +264,39 @@ function ApprovalDecision({
) : null}
{canDecide ? (
<CardActions>
- <DecisionActions
- approveLabel={words.approve}
- denyLabel={words.deny}
- disabled={submitting}
- onApprove={() => void decide("approve")}
- onDeny={(reason) => void decide("deny", reason)}
- reasonRequired={roomCreation}
- />
+ {email ? (
+ <div
+ aria-label="Approval actions"
+ className="flex gap-2"
+ role="group"
+ >
+ <Button
+ disabled={submitting}
+ onClick={() => void decide("approve")}
+ size="large"
+ tone="primary"
+ >
+ {words.approve}
+ </Button>
+ <Button
+ disabled={submitting}
+ onClick={() => void decide("deny")}
+ size="large"
+ tone="ghost"
+ >
+ {words.deny}
+ </Button>
+ </div>
+ ) : (
+ <DecisionActions
+ approveLabel={words.approve}
+ denyLabel={words.deny}
+ disabled={submitting}
+ onApprove={() => void decide("approve")}
+ onDeny={(reason) => void decide("deny", reason)}
+ reasonRequired={roomCreation}
+ />
+ )}
</CardActions>
) : done ? (
<div className="flex min-w-0 items-center justify-between gap-2">
diff --git a/apps/web/src/features/rooms/cards/decision-connector-write-view.tsx b/apps/web/src/features/rooms/cards/decision-connector-write-view.tsx
index 41c28e21..a5ecde2f 100644
--- a/apps/web/src/features/rooms/cards/decision-connector-write-view.tsx
+++ b/apps/web/src/features/rooms/cards/decision-connector-write-view.tsx
@@ -1,11 +1,17 @@
import DOMPurify from "dompurify";
-import { Attachment01Icon } from "@hugeicons/core-free-icons";
-import { Fragment, useMemo, useState } from "react";
+import {
+ ArrowDown01Icon,
+ Attachment01Icon,
+ Mail01Icon,
+} from "@hugeicons/core-free-icons";
+import { Fragment, useId, useMemo, useState } from "react";
+import { AutoHeight } from "@/components/ui/auto-height";
import { Icon } from "@/components/ui/icon";
+import { cn } from "@/lib/cn";
import { MessageMarkdown } from "../chat/message-markdown";
-import { FullCallBlock } from "./approval-card-parts";
+import { CardRowDetails, FullCallBlock } from "./approval-card-parts";
import type { DecisionMessageCard } from "./decision-card";
import { SlackMrkdwn } from "./slack-mrkdwn";
@@ -13,6 +19,64 @@ type ConnectorWriteView = NonNullable<DecisionMessageCard["connector_write"]>;
type ConnectorWriteMessage = NonNullable<ConnectorWriteView["message"]>;
type ConnectorWriteField = NonNullable<ConnectorWriteView["fields"]>[number];
+/** Email headers replace the compact recipient line when the preview opens. */
+export function EmailDecisionView({
+ account,
+ message,
+}: {
+ account: string;
+ message: ConnectorWriteMessage;
+}) {
+ const [open, setOpen] = useState(false);
+ const previewId = useId();
+ return (
+ <>
+ <h3>
+ <button
+ aria-controls={previewId}
+ aria-expanded={open}
+ className="-mx-2 flex min-h-9 w-[calc(100%+1rem)] items-center gap-2 rounded-lg px-2 py-1.5 text-left transition-colors duration-150 hover:bg-accent focus-visible:outline-2 focus-visible:outline-offset-[-2px] focus-visible:outline-app-focus motion-reduce:transition-none"
+ onClick={() => setOpen((current) => !current)}
+ type="button"
+ >
+ <Icon
+ className="shrink-0 text-app-muted"
+ icon={Mail01Icon}
+ size={16}
+ />
+ <span className="min-w-0 flex-1 text-sm font-semibold text-app-ink [overflow-wrap:anywhere]">
+ {message.subject?.trim() || "No subject"}
+ </span>
+ <Icon
+ className={cn(
+ "shrink-0 text-app-muted transition-transform duration-(--chat-resize-duration) ease-(--app-out-quint) motion-reduce:transition-none",
+ open && "rotate-180",
+ )}
+ icon={ArrowDown01Icon}
+ size={14}
+ />
+ </button>
+ </h3>
+ {message.to?.length ? (
+ <AutoHeight open={!open}>
+ <p className="pt-1 text-sm text-app-muted [overflow-wrap:anywhere]">
+ To {message.to.map(displayEmailAddress).join(", ")}
+ </p>
+ </AutoHeight>
+ ) : null}
+ <div id={previewId}>
+ <CardRowDetails open={open}>
+ <MessagePreview emailFrom={account} message={message} />
+ </CardRowDetails>
+ </div>
+ </>
+ );
+}
+
+function displayEmailAddress(address: string) {
+ return address.trim().replace(/^<([^<>]+)>$/, "$1");
+}
+
/**
* The full view of one connected app write that TeamHub holds: the message or
* changed fields for a tool with its own layout, and otherwise the full call,
@@ -37,36 +101,74 @@ export function ConnectorWriteDecisionView({
}
/** The message exactly as it will be sent: headers, body, attachments. */
-function MessagePreview({ message }: { message: ConnectorWriteMessage }) {
+function MessagePreview({
+ emailFrom,
+ message,
+}: {
+ emailFrom?: string;
+ message: ConnectorWriteMessage;
+}) {
+ const email = emailFrom !== undefined;
+ function recipients(addresses?: string[]) {
+ return (email ? addresses?.map(displayEmailAddress) : addresses)?.join(
+ ", ",
+ );
+ }
const rows: [string, string | undefined][] = [
- ["To", message.to?.join(", ")],
- ["Cc", message.cc?.join(", ")],
- ["Bcc", message.bcc?.join(", ")],
- ["Subject", message.subject],
+ [
+ "From",
+ emailFrom === undefined ? undefined : displayEmailAddress(emailFrom),
+ ],
+ ["To", recipients(message.to)],
+ ["Cc", recipients(message.cc) || (email ? "None" : undefined)],
+ ["Bcc", recipients(message.bcc)],
+ ["Subject", email ? undefined : message.subject],
["Where", message.destination],
];
const shown = rows.filter((row): row is [string, string] => Boolean(row[1]));
return (
<section
aria-label="Message preview"
- className="overflow-hidden rounded-lg border border-app-border bg-app-surface"
+ className={cn(
+ email
+ ? "mt-2"
+ : "overflow-hidden rounded-lg border border-app-border bg-app-surface",
+ )}
>
{shown.length ? (
- <dl className="grid grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-0.5 border-b border-app-border px-3 py-2 text-xs leading-5">
+ <dl
+ className={cn(
+ "border-b border-app-border",
+ email
+ ? "divide-y divide-app-border text-sm"
+ : "grid grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-0.5 px-3 py-2 text-xs leading-5",
+ )}
+ >
{shown.map(([label, value]) => (
- <Fragment key={label}>
+ <div
+ className={
+ email
+ ? "grid grid-cols-[3rem_minmax(0,1fr)] gap-x-3 py-3"
+ : "contents"
+ }
+ key={label}
+ >
<dt className="text-app-muted">{label}</dt>
<dd
className={`[overflow-wrap:anywhere] text-app-ink ${label === "Subject" ? "font-semibold" : ""}`}
>
{value}
</dd>
- </Fragment>
+ </div>
))}
</dl>
) : null}
{message.body.trim() ? (
- <MessageBody body={message.body} format={message.format} />
+ <MessageBody
+ body={message.body}
+ expanded={email}
+ format={message.format}
+ />
) : (
<p className="px-3 py-2.5 text-xs text-app-muted">No message text.</p>
)}
@@ -96,15 +198,18 @@ function MessagePreview({ message }: { message: ConnectorWriteMessage }) {
function MessageBody({
body,
+ expanded = false,
format,
}: {
body: string;
+ expanded?: boolean;
format: ConnectorWriteMessage["format"];
}) {
- if (format === "html") return <HtmlMessageBody html={body} />;
+ if (format === "html")
+ return <HtmlMessageBody expanded={expanded} html={body} />;
return (
<div
- className="max-h-80 overflow-auto px-3 py-2.5"
+ className={expanded ? "py-4" : "max-h-80 overflow-auto px-3 py-2.5"}
data-testid="message-body"
>
{format === "markdown" ? (
@@ -127,11 +232,20 @@ const htmlBodyMaxHeight = 320;
* An HTML email in its own sandboxed document, so its styles stay inside the
* preview. Nothing in it runs or loads: DOMPurify strips scripts, the
* sandbox has no allow-scripts, and the policy blocks remote resources. The
- * frame grows with the email up to a cap, then scrolls.
+ * frame grows with an expanded email; compact message previews cap its height.
*/
-function HtmlMessageBody({ html }: { html: string }) {
+function HtmlMessageBody({
+ expanded,
+ html,
+}: {
+ expanded: boolean;
+ html: string;
+}) {
const [height, setHeight] = useState(120);
- const source = useMemo(() => htmlEmailDocument(html), [html]);
+ const source = useMemo(
+ () => htmlEmailDocument(html, expanded),
+ [html, expanded],
+ );
return (
<iframe
className="block w-full border-0 bg-white"
@@ -141,7 +255,7 @@ function HtmlMessageBody({ html }: { html: string }) {
setHeight(
Math.min(
Math.max(root.scrollHeight, htmlBodyMinHeight),
- htmlBodyMaxHeight,
+ expanded ? Infinity : htmlBodyMaxHeight,
),
);
}}
@@ -155,7 +269,7 @@ function HtmlMessageBody({ html }: { html: string }) {
);
}
-function htmlEmailDocument(html: string) {
+function htmlEmailDocument(html: string, expanded: boolean) {
const root = DOMPurify.sanitize(html, {
RETURN_DOM: true,
WHOLE_DOCUMENT: true,
@@ -174,8 +288,7 @@ function htmlEmailDocument(html: string) {
charset.setAttribute("charset", "utf-8");
// The email's own styles come later and win.
const base = owner.createElement("style");
- base.textContent =
- "html{color-scheme:light}body{margin:0;padding:10px 12px;background:#fff;color:#202020;font:14px/1.5 Inter,system-ui,sans-serif;overflow-wrap:anywhere}img{max-width:100%;height:auto}";
+ base.textContent = `html{color-scheme:light}body{margin:0;padding:${expanded ? "16px 0" : "10px 12px"};background:#fff;color:#202020;font:14px/1.5 Inter,system-ui,sans-serif;overflow-wrap:anywhere}img{max-width:100%;height:auto}`;
head.prepend(charset, policy, base);
for (const link of root.querySelectorAll("a[href]")) {
link.setAttribute("target", "_blank");
diff --git a/apps/web/src/features/rooms/chat/message-mail-canvas.tsx b/apps/web/src/features/rooms/chat/message-mail-canvas.tsx
new file mode 100644
index 00000000..76250a14
--- /dev/null
+++ b/apps/web/src/features/rooms/chat/message-mail-canvas.tsx
@@ -0,0 +1,292 @@
+import {
+ AlertCircleIcon,
+ ArrowDown01Icon,
+ ArrowExpand01Icon,
+ Cancel01Icon,
+ HelpCircleIcon,
+ Loading03Icon,
+ Mail01Icon,
+ Tick02Icon,
+} from "@hugeicons/core-free-icons";
+import {
+ useEffect,
+ useId,
+ useRef,
+ useState,
+ useSyncExternalStore,
+ type ReactNode,
+} from "react";
+
+import { AutoHeight } from "@/components/ui/auto-height";
+import { Button } from "@/components/ui/button";
+import { Icon } from "@/components/ui/icon";
+import { Select, SelectItem } from "@/components/ui/select";
+import { useTeamHubRuntime } from "@/features/teamhub/teamhub-runtime";
+import { useWikiDocumentLinks } from "@/features/wiki/wiki-document-links";
+import { cn } from "@/lib/cn";
+import { CardActions, CardRowDetails } from "../cards/approval-card-parts";
+import { CardBox, CardDone } from "../cards/card-shell";
+import {
+ progressLabel,
+ useMailCanvasSend,
+} from "../documents/canvas/canvas-mail-send";
+import "../documents/room-document-blocknote.css";
+import { UnifiedDocumentBody } from "../documents/unified-document-body";
+import { useUnifiedDocumentPageModel } from "../documents/use-unified-document-page-model";
+
+const iconButton =
+ "inline-flex size-7 shrink-0 items-center justify-center rounded-md text-app-muted transition-colors duration-150 hover:bg-accent hover:text-app-ink focus-visible:outline-2 focus-visible:outline-offset-[-2px] focus-visible:outline-app-focus motion-reduce:transition-none";
+
+/**
+ * A gmail canvas in the timeline is the email itself, laid out like an
+ * approval card: subject, recipients, Send. Expanded it is the same editor
+ * as the side panel; anything that is not a gmail canvas renders `fallback`.
+ */
+export function MessageMailCanvas({
+ documentId,
+ fallback,
+ onOpen,
+ tenantId,
+}: {
+ documentId: string;
+ fallback: ReactNode;
+ onOpen: () => void;
+ tenantId: string;
+}) {
+ const { client } = useTeamHubRuntime();
+ const [open, setOpen] = useState(false);
+ // The editor stays mounted once opened, so its unsaved edits count even
+ // while the card is collapsed again.
+ const [editorSaved, setEditorSaved] = useState(true);
+ const mail = useMailCanvasSend(client, documentId, editorSaved);
+ const { refresh } = mail;
+ const editorId = useId();
+ if (!mail.mail) return fallback;
+ const { subject, to } = mail.mail;
+ return (
+ <CardBox label="Email">
+ <h3 className="-mx-2 flex min-h-9 w-[calc(100%+1rem)] items-center gap-1 rounded-lg pr-1 transition-colors duration-150 hover:bg-accent motion-reduce:transition-none">
+ <button
+ aria-controls={editorId}
+ aria-expanded={open}
+ className="flex min-w-0 flex-1 items-center gap-2 rounded-lg py-1.5 pl-2 text-left focus-visible:outline-2 focus-visible:outline-offset-[-2px] focus-visible:outline-app-focus"
+ onClick={() => setOpen((current) => !current)}
+ type="button"
+ >
+ <Icon
+ className="shrink-0 text-app-muted"
+ icon={Mail01Icon}
+ size={16}
+ />
+ <span className="min-w-0 flex-1 text-sm font-semibold text-app-ink [overflow-wrap:anywhere]">
+ {subject.trim() || "No subject"}
+ </span>
+ </button>
+ <button
+ aria-label="Open in side panel"
+ className={iconButton}
+ onClick={onOpen}
+ title="Open in side panel"
+ type="button"
+ >
+ <Icon icon={ArrowExpand01Icon} size={14} />
+ </button>
+ <button
+ aria-controls={editorId}
+ aria-expanded={open}
+ aria-label={open ? "Collapse email" : "Expand email"}
+ className={iconButton}
+ onClick={() => setOpen((current) => !current)}
+ type="button"
+ >
+ <Icon
+ className={cn(
+ "transition-transform duration-(--chat-resize-duration) ease-(--app-out-quint) motion-reduce:transition-none",
+ open && "rotate-180",
+ )}
+ icon={ArrowDown01Icon}
+ size={14}
+ />
+ </button>
+ </h3>
+ <AutoHeight open={!open}>
+ <p className="pt-1 text-sm text-app-muted [overflow-wrap:anywhere]">
+ {to ? `To ${to}` : "No recipients"}
+ </p>
+ </AutoHeight>
+ <div id={editorId}>
+ <CardRowDetails open={open}>
+ <MailCanvasEditor
+ documentId={documentId}
+ onSaved={refresh}
+ onSavedChange={setEditorSaved}
+ tenantId={tenantId}
+ />
+ </CardRowDetails>
+ </div>
+ <MailCardFooter mail={mail} />
+ </CardBox>
+ );
+}
+
+/** Opens the collaborative session only while the card is expanded. */
+function MailCanvasEditor({
+ documentId,
+ onSaved,
+ onSavedChange,
+ tenantId,
+}: {
+ documentId: string;
+ onSaved: () => void;
+ onSavedChange: (saved: boolean) => void;
+ tenantId: string;
+}) {
+ const model = useUnifiedDocumentPageModel({ documentId, tenantId });
+ const contentRef = useRef<HTMLDivElement | null>(null);
+ const wikiLinks = useWikiDocumentLinks(model.client, undefined, contentRef);
+ return (
+ <div className="-mx-1">
+ {model.session ? (
+ <SaveStateProbe
+ onSaved={onSaved}
+ onSavedChange={onSavedChange}
+ session={model.session}
+ />
+ ) : null}
+ <div className="flex justify-end">
+ <span ref={model.setMailAttachmentsPortalTarget} />
+ </div>
+ <div className="room-document-main flex max-h-[520px] min-h-0 flex-col [&_.room-document-content-lane]:px-1 [&_.room-document-layout]:pb-2">
+ <UnifiedDocumentBody
+ documentContentRef={contentRef}
+ isWikiPage={false}
+ knowledgeTitle={undefined}
+ model={model}
+ wikiLinks={wikiLinks}
+ />
+ </div>
+ </div>
+ );
+}
+
+/**
+ * Reports whether the editor has unsaved edits, and asks for the email's new
+ * digest each time a change becomes durable, so Send pins what is shown.
+ */
+function SaveStateProbe({
+ onSaved,
+ onSavedChange,
+ session,
+}: {
+ onSaved: () => void;
+ onSavedChange: (saved: boolean) => void;
+ session: NonNullable<
+ ReturnType<typeof useUnifiedDocumentPageModel>["session"]
+ >;
+}) {
+ const save = useSyncExternalStore(
+ session.subscribeSaveState,
+ session.getSaveSnapshot,
+ session.getSaveSnapshot,
+ );
+ const saved = save.status === "Saved" && save.protocolError === undefined;
+ useEffect(() => {
+ onSavedChange(saved);
+ }, [onSavedChange, saved]);
+ const sequence = save.durableSequence;
+ useEffect(() => {
+ if (saved && sequence !== undefined) onSaved();
+ }, [onSaved, saved, sequence]);
+ return null;
+}
+
+/**
+ * The same receipts and buttons as an approval card for an email: one line
+ * once it is decided, Send and Don't send while it waits. An unknown result
+ * keeps both, so the Human can act after checking Gmail.
+ */
+function MailCardFooter({
+ mail,
+}: {
+ mail: ReturnType<typeof useMailCanvasSend>;
+}) {
+ const { status } = mail;
+ const error = mail.mail?.error;
+ if (status === "sent")
+ return <CardDone icon={Tick02Icon} text="Sent" tone="success" />;
+ if (status === "declined")
+ return <CardDone icon={Cancel01Icon} text="Not sent" tone="muted" />;
+ if (mail.busy)
+ return (
+ <CardDone
+ icon={Loading03Icon}
+ text={progressLabel[status ?? "queued"] ?? "Sending…"}
+ tone="muted"
+ />
+ );
+ const receipt =
+ status === "unknown" ? (
+ <CardDone
+ icon={HelpCircleIcon}
+ text={error ? `Result unknown: ${error}` : "Result unknown"}
+ tone="warning"
+ />
+ ) : status === "failed" ? (
+ <CardDone
+ icon={AlertCircleIcon}
+ text={error ? `Failed: ${error}` : "Failed"}
+ tone="danger"
+ />
+ ) : null;
+ // Only someone who may change the email decides it.
+ if (!mail.canEdit) return receipt;
+ return (
+ <>
+ {receipt}
+ <CardActions>
+ <div aria-label="Approval actions" className="flex gap-2" role="group">
+ <Button
+ disabled={!mail.canSend || mail.declining}
+ onClick={mail.send}
+ size="large"
+ tone="primary"
+ >
+ {status === "unknown" ? "Send again" : "Send"}
+ </Button>
+ <Button
+ disabled={mail.declining}
+ onClick={mail.decline}
+ size="large"
+ tone="ghost"
+ >
+ Don&apos;t send
+ </Button>
+ </div>
+ {mail.accounts.length > 1 && mail.account ? (
+ <Select
+ aria-label="Send from"
+ onValueChange={mail.choose}
+ value={mail.account.id}
+ variant="pill"
+ >
+ {mail.accounts.map((account) => (
+ <SelectItem key={account.id} value={account.id}>
+ {account.identity_label || "Gmail account"}
+ </SelectItem>
+ ))}
+ </Select>
+ ) : null}
+ {mail.note ? (
+ <span className="text-xs text-app-muted" role="status">
+ {mail.note}
+ </span>
+ ) : null}
+ </CardActions>
+ {mail.problem && status !== "failed" ? (
+ <p className="pb-1.5 text-xs text-app-danger" role="alert">
+ {mail.problem}
+ </p>
+ ) : null}
+ </>
+ );
+}
diff --git a/apps/web/src/features/rooms/chat/message-row.tsx b/apps/web/src/features/rooms/chat/message-row.tsx
index 48666ea7..ed6486a1 100644
--- a/apps/web/src/features/rooms/chat/message-row.tsx
+++ b/apps/web/src/features/rooms/chat/message-row.tsx
@@ -45,6 +45,7 @@ import {
import { cn } from "@/lib/cn";
import { artifactFileTypeLabel } from "../files/artifact-file-kind";
import { MessageFileAttachment } from "../files/message-file-attachment";
+import { MessageMailCanvas } from "./message-mail-canvas";
import { selectArtifactRenderer } from "../files/artifact-renderer-policy";
import { chatImageSize, useDecodedImage } from "../files/local-message-images";
import {
@@ -470,7 +471,7 @@ function ConversationMessageRow({
// An attached file already knows its type and version, so it shows as
// what it is before the Document metadata arrives.
const attachment = attachmentByDocument.get(block.segment.document_id);
- return (
+ const file = (
<MessageFileAttachment
{...documentFile(block.segment.document_id, block.segment.content)}
// A live Document opens in its editor rather than previewing.
@@ -489,6 +490,18 @@ function ConversationMessageRow({
}
/>
);
+ // A gmail canvas shows as the email itself; other canvases as files.
+ return block.segment.presentation === "canvas" ? (
+ <MessageMailCanvas
+ documentId={block.segment.document_id}
+ fallback={file}
+ key={block.segment.document_id}
+ onOpen={() => onOpenMessageFile(block.segment)}
+ tenantId={tenantId}
+ />
+ ) : (
+ file
+ );
}
const attachedName = block.segment.filename ?? block.segment.content;
return (
diff --git a/apps/web/src/features/rooms/chat/room-chat.test.tsx b/apps/web/src/features/rooms/chat/room-chat.test.tsx
index e139d80a..cc38d0ab 100644
--- a/apps/web/src/features/rooms/chat/room-chat.test.tsx
+++ b/apps/web/src/features/rooms/chat/room-chat.test.tsx
@@ -1076,6 +1076,138 @@ describe("Room Chat", () => {
);
});
+ it("shows a gmail canvas as the email, with subject, recipients and Send", async () => {
+ const runtime = createTestTeamHubRuntime();
+ const document = seedRoomDocument(runtime, "room-chat-mail-canvas");
+ runtime.server.on("GET", "/v0/documents/{documentId}/mail", () => ({
+ source_digest: `sha256:${"0".repeat(64)}`,
+ can_edit: true,
+ status: "draft" as const,
+ subject: "Updated invitation",
+ }));
+ // A second Gmail account: Send says which one it sends from.
+ const [gmail] = runtime.seed.externalSources.connections.filter(
+ (connection) => connection.provider === "gmail",
+ );
+ runtime.seed.externalSources.connections.push({
+ ...gmail!,
+ id: "external-connection-gmail-work",
+ identity_label: "[email protected]",
+ });
+ let sentFrom: unknown;
+ runtime.server.on("POST", "/v0/documents/{documentId}/mail", ({ body }) => {
+ sentFrom = body;
+ return {
+ can_edit: true,
+ source_digest: `sha256:${"0".repeat(64)}`,
+ status: "queued" as const,
+ subject: "Updated invitation",
+ };
+ });
+ const queryClient = testQueryClient();
+ renderRoomChat(runtime, queryClient);
+ await screen.findByText(/Reviewed the checklist/);
+ appendCommittedMessage(queryClient, {
+ ...message("message-mail-canvas", "Invitation"),
+ segments: [
+ {
+ content: "Invitation",
+ document_id: document.id,
+ presentation: "canvas",
+ type: "document",
+ },
+ ],
+ });
+
+ const email = await screen.findByRole("region", { name: "Email" });
+ expect(email).toHaveTextContent("Updated invitation");
+ expect(email).toHaveTextContent("To [email protected]");
+ expect(within(email).getByRole("button", { name: "Send" })).toBeVisible();
+ expect(
+ within(email).getByRole("button", { name: "Don't send" }),
+ ).toBeVisible();
+ expect(
+ await within(email).findByRole("combobox", { name: "Send from" }),
+ ).toHaveTextContent("[email protected]");
+ fireEvent.click(screen.getByRole("button", { name: "Open in side panel" }));
+ await waitFor(() =>
+ expect(openPanelTab).toHaveBeenCalledWith(
+ expect.objectContaining({ documentId: document.id, kind: "file" }),
+ ),
+ );
+
+ runtime.server.on(
+ "POST",
+ "/v0/documents/{documentId}/mail/decline",
+ () => ({
+ can_edit: true,
+ source_digest: `sha256:${"0".repeat(64)}`,
+ status: "declined" as const,
+ subject: "Updated invitation",
+ }),
+ );
+ fireEvent.click(within(email).getByRole("button", { name: "Don't send" }));
+ expect(await within(email).findByText("Not sent")).toBeVisible();
+ expect(within(email).queryByRole("button", { name: "Send" })).toBeNull();
+ expect(sentFrom).toBeUndefined();
+ });
+
+ it("sends the digest the card showed, and hides the actions from members who cannot edit", async () => {
+ const runtime = createTestTeamHubRuntime();
+ const document = seedRoomDocument(runtime, "room-chat-mail-readonly");
+ const shown = `sha256:${"1".repeat(64)}`;
+ let canEdit = true;
+ runtime.server.on("GET", "/v0/documents/{documentId}/mail", () => ({
+ can_edit: canEdit,
+ source_digest: shown,
+ status: "draft" as const,
+ subject: "Pricing",
+ }));
+ let posted: { source_digest?: string } | undefined;
+ runtime.server.on("POST", "/v0/documents/{documentId}/mail", ({ body }) => {
+ posted = body as { source_digest?: string };
+ return {
+ can_edit: true,
+ source_digest: shown,
+ status: "sent" as const,
+ subject: "Pricing",
+ };
+ });
+ const queryClient = testQueryClient();
+ renderRoomChat(runtime, queryClient);
+ await screen.findByText(/Reviewed the checklist/);
+ appendCommittedMessage(queryClient, {
+ ...message("message-mail-readonly", "Pricing"),
+ segments: [
+ {
+ content: "Pricing",
+ document_id: document.id,
+ presentation: "canvas",
+ type: "document",
+ },
+ ],
+ });
+ const email = await screen.findByRole("region", { name: "Email" });
+ const send = await within(email).findByRole("button", { name: "Send" });
+ await waitFor(() => expect(send).toBeEnabled());
+ fireEvent.click(send);
+ expect(await within(email).findByText("Sent")).toBeVisible();
+ expect(posted?.source_digest).toBe(shown);
+
+ canEdit = false;
+ await queryClient.resetQueries({ queryKey: ["mail-canvas", document.id] });
+ await waitFor(() =>
+ expect(
+ within(email).queryByRole("button", { name: "Don't send" }),
+ ).toBeNull(),
+ );
+ });
+
it("warms only the Document surface chunk once a Document card is shown", async () => {
const preload = vi
.spyOn(documentRoutePreload, "preloadUnifiedDocumentPage")
diff --git a/apps/web/src/features/rooms/documents/AGENTS.md b/apps/web/src/features/rooms/documents/AGENTS.md
index ade1b49d..12fe8156 100644
--- a/apps/web/src/features/rooms/documents/AGENTS.md
+++ b/apps/web/src/features/rooms/documents/AGENTS.md
@@ -28,3 +28,14 @@
- Test state invariants through the collaboration-session interface and test
the real browser workflow with Playwright. Do not inspect provider or
IndexedDB internals from component tests.
+- Gmail canvases use the Mail sidebar header, an editable 15px semibold Subject above
+ the From/To/Cc fields and collaborative body, without the generic Document title or
+ author row. Save status still comes from the durable session snapshot.
+ Formatting uses the existing editor controls. The Mail header paperclip uploads
+ file attachments (15 MiB total) through the existing Document Asset flow.
+ File blocks stay authoritative; the client presents them below the body with
+ sizes and remove controls, and reports their count in the header. Canvas has no
+ sending toolbar; the email's chat card sends it, and once its delivery
+ reports sent the editor writes `status: sent` into the header. Sent canvases stay read-only, suppress the editing indicator, and show
+ empty recipient fields as None. Attachment list spacing stays inside the
+ measured height so its resize animation cannot clip the last file.
diff --git a/apps/web/src/features/rooms/documents/canvas/canvas-header.test.tsx b/apps/web/src/features/rooms/documents/canvas/canvas-header.test.tsx
index aceb2998..3112372b 100644
--- a/apps/web/src/features/rooms/documents/canvas/canvas-header.test.tsx
+++ b/apps/web/src/features/rooms/documents/canvas/canvas-header.test.tsx
@@ -90,6 +90,11 @@ describe("CanvasHeader", () => {
expect(screen.getByLabelText("To")).toHaveValue("[email protected]");
expect(screen.getByLabelText("Cc")).toHaveValue("");
const subject = screen.getByLabelText("Subject");
+ expect(subject).toHaveClass("font-semibold");
+ expect(
+ subject.compareDocumentPosition(screen.getByLabelText("To")) &
+ Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
fireEvent.focus(subject);
fireEvent.change(subject, { target: { value: "Pricing follow-up" } });
fireEvent.keyDown(subject, { key: "Enter" });
@@ -137,6 +142,19 @@ describe("CanvasHeader", () => {
expect(screen.queryByText("Agent is editing…")).not.toBeInTheDocument();
});
+ it("keeps sent mail free of editing prompts when delivery status arrives remotely", () => {
+ const { change, editor } = fakeEditor(
+ "canvas: gmail\nsubject: Pricing\nstatus: draft",
+ );
+ render(
+ <Harness editable={false} awareness={awarenessOf(1)} editor={editor} />,
+ );
+ change("yjs-remote", "canvas: gmail\nsubject: Pricing\nstatus: sent");
+ expect(screen.getByText("Sent")).toBeVisible();
+ expect(screen.queryByText("Agent is editing…")).toBeNull();
+ expect(screen.getByLabelText("Cc")).toHaveAttribute("placeholder", "None");
+ });
+
it("does not credit the Agent with another person's edits", () => {
const { change, editor } = fakeEditor("canvas: gmail\nsubject: Pricing");
render(<Harness awareness={awarenessOf(2)} editor={editor} />);
diff --git a/apps/web/src/features/rooms/documents/canvas/canvas-header.tsx b/apps/web/src/features/rooms/documents/canvas/canvas-header.tsx
index 8d174db4..17d34ebc 100644
--- a/apps/web/src/features/rooms/documents/canvas/canvas-header.tsx
+++ b/apps/web/src/features/rooms/documents/canvas/canvas-header.tsx
@@ -1,6 +1,13 @@
import { LinkSquare02Icon, PencilEdit01Icon } from "@hugeicons/core-free-icons";
import { Icon } from "@/components/ui/icon";
-import { useEffect, useLayoutEffect, useRef, useState } from "react";
+import { cn } from "@/lib/cn";
+import {
+ useEffect,
+ useLayoutEffect,
+ useRef,
+ useState,
+ type ReactNode,
+} from "react";
import type { RoomDocumentCollaborationSession } from "../room-document-collaboration";
import type { RoomDocumentEditor } from "../room-document-comment-schema";
@@ -62,11 +69,13 @@ export function CanvasHeader({
canvas,
editable,
editor,
+ sender,
}: {
agentEditing: boolean;
canvas: CanvasDocument;
editable: boolean;
editor: RoomDocumentEditor;
+ sender?: ReactNode;
}) {
const save = (key: string, value: string) => {
if ((canvas.fields[key] ?? "") === value) return;
@@ -77,6 +86,8 @@ export function CanvasHeader({
}),
});
};
+ const mail = canvas.target.id === "gmail";
+ const showAgentEditing = agentEditing && canvas.status !== "sent";
const fields =
canvas.target.fields.length > 0
? canvas.target.fields
@@ -89,59 +100,111 @@ export function CanvasHeader({
return (
<section
aria-label={`${canvas.target.label} canvas`}
- className="mb-6"
+ className="mb-5"
data-canvas-target={canvas.target.id}
>
- <div className="flex min-h-8 items-center gap-2 text-[12px] text-app-muted">
- <span className="font-medium text-app-ink">{canvas.target.label}</span>
- <CanvasStatus canvas={canvas} />
- {agentEditing ? (
- <span
- className="ml-auto inline-flex items-center gap-1"
- role="status"
- >
- <Icon icon={PencilEdit01Icon} size={14} />
- Agent is editing…
+ {!mail || showAgentEditing ? (
+ <div className="flex min-h-8 items-center gap-2 text-xs text-app-muted">
+ {canvas.target.id !== "gmail" ? (
+ <span className="font-medium text-app-ink">
+ {canvas.target.label}
+ </span>
+ ) : null}
+ {!mail ? <CanvasStatus canvas={canvas} /> : null}
+ {showAgentEditing ? (
+ <span
+ className="ml-auto inline-flex items-center gap-1"
+ role="status"
+ >
+ <Icon icon={PencilEdit01Icon} size={14} />
+ Agent is editing…
+ </span>
+ ) : null}
+ </div>
+ ) : null}
+ {mail ? (
+ <div className="mb-1 flex items-center gap-2">
+ <div className="min-w-0 flex-1">
+ <label className="sr-only" htmlFor="canvas-field-subject">
+ Subject
+ </label>
+ <CanvasField
+ className="text-[15px] font-semibold"
+ editable={editable}
+ id="canvas-field-subject"
+ onSave={(value) => save("subject", value)}
+ placeholder="Subject"
+ value={canvas.fields.subject ?? ""}
+ />
+ </div>
+ <span className="shrink-0 text-xs text-app-muted">
+ <CanvasStatus canvas={canvas} compact />
</span>
- ) : null}
- </div>
- {/* Mail-client style: one hairline-separated row per field, no card. */}
- <dl className="border-t border-app-border">
- {fields.map((field) => (
- <div
- className="flex items-center gap-3 border-b border-app-border"
- key={field.key}
- >
- <dt className="w-16 shrink-0 text-sm text-app-muted">
- <label htmlFor={`canvas-field-${field.key}`}>{field.label}</label>
- </dt>
- <dd className="min-w-0 flex-1">
- <CanvasField
- editable={editable}
- id={`canvas-field-${field.key}`}
- onSave={(value) => save(field.key, value)}
- placeholder={field.placeholder}
- value={canvas.fields[field.key] ?? ""}
- />
+ </div>
+ ) : null}
+ <dl>
+ {sender ? (
+ <div className="flex min-h-11 items-center gap-3">
+ <dt className="w-14 shrink-0 text-sm text-app-muted">From</dt>
+ <dd className="min-w-0 flex-1 text-sm text-app-ink [overflow-wrap:anywhere]">
+ {sender}
</dd>
</div>
- ))}
+ ) : null}
+ {fields
+ .filter((field) => !mail || field.key !== "subject")
+ .map((field) => (
+ <div
+ className={cn(
+ "flex items-center gap-3",
+ !mail &&
+ "border-b border-app-border transition-colors duration-150 focus-within:border-app-muted/60 motion-reduce:transition-none",
+ )}
+ key={field.key}
+ >
+ <dt className="w-14 shrink-0 text-sm text-app-muted">
+ <label htmlFor={`canvas-field-${field.key}`}>
+ {field.label}
+ </label>
+ </dt>
+ <dd className="min-w-0 flex-1">
+ <CanvasField
+ editable={editable}
+ id={`canvas-field-${field.key}`}
+ onSave={(value) => save(field.key, value)}
+ placeholder={field.placeholder}
+ value={canvas.fields[field.key] ?? ""}
+ />
+ </dd>
+ </div>
+ ))}
</dl>
</section>
);
}
-function CanvasStatus({ canvas }: { canvas: CanvasDocument }) {
+function CanvasStatus({
+ canvas,
+ compact = false,
+}: {
+ canvas: CanvasDocument;
+ compact?: boolean;
+}) {
if (canvas.status === "editing") return null;
const label = canvas.status === "sent" ? "Sent" : "Draft saved";
return canvas.link ? (
<a
+ aria-label={label}
className="inline-flex items-center gap-1 underline-offset-2 hover:underline"
href={canvas.link}
rel="noreferrer"
target="_blank"
>
- {label}
+ <span
+ className={compact && canvas.status === "draft" ? "sr-only" : undefined}
+ >
+ {label}
+ </span>
<Icon icon={LinkSquare02Icon} size={12} />
</a>
) : (
@@ -150,12 +213,14 @@ function CanvasStatus({ canvas }: { canvas: CanvasDocument }) {
}
function CanvasField({
+ className = "text-sm",
editable,
id,
onSave,
placeholder,
value,
}: {
+ className?: string;
editable: boolean;
id: string;
onSave: (value: string) => void;
@@ -170,7 +235,10 @@ function CanvasField({
}, [value]);
return (
<input
- className="h-11 w-full bg-transparent text-sm text-app-ink outline-none placeholder:text-app-muted"
+ className={cn(
+ "h-11 w-full border-0 bg-transparent text-app-ink outline-none shadow-none focus:outline-none focus:ring-0 placeholder:text-app-muted",
+ className,
+ )}
id={id}
onBlur={() => {
focused.current = false;
@@ -184,7 +252,7 @@ function CanvasField({
if (event.key === "Enter" && !event.nativeEvent.isComposing)
event.currentTarget.blur();
}}
- placeholder={placeholder}
+ placeholder={editable ? placeholder : "None"}
readOnly={!editable}
value={draft}
/>
diff --git a/apps/web/src/features/rooms/documents/canvas/canvas-mail-attachments.test.tsx b/apps/web/src/features/rooms/documents/canvas/canvas-mail-attachments.test.tsx
new file mode 100644
index 00000000..b09c2f47
--- /dev/null
+++ b/apps/web/src/features/rooms/documents/canvas/canvas-mail-attachments.test.tsx
@@ -0,0 +1,222 @@
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import {
+ act,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { createTestTeamHubRuntime } from "@/test/teamhub-test-runtime";
+import { uploadRoomDocumentAsset } from "../room-document-assets";
+import type {
+ RoomDocumentEditor,
+ RoomDocumentPartialBlock,
+} from "../room-document-comment-schema";
+import { CanvasMailAttachments } from "./canvas-mail-attachments";
+
+vi.mock("../room-document-assets", () => ({
+ uploadRoomDocumentAsset: vi.fn(),
+}));
+afterEach(() => vi.resetAllMocks());
+
+function setup(initialFiles: RoomDocumentPartialBlock[] = [], size = 1024) {
+ const runtime = createTestTeamHubRuntime();
+ runtime.server.on(
+ "GET",
+ "/v0/document-assets/{documentAssetId}",
+ ({ params }) => ({
+ id: params.documentAssetId,
+ filename: "brief.pdf",
+ size_bytes: size,
+ status: "available",
+ }),
+ );
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ const listeners = new Set<() => void>();
+ let blocks = [
+ { id: "body", type: "paragraph", props: {}, content: [], children: [] },
+ ...initialFiles,
+ ] as RoomDocumentEditor["document"];
+ const notify = () => listeners.forEach((listener) => listener());
+ const editor = {
+ get document() {
+ return blocks;
+ },
+ getBlock: (id: string) => blocks.find((block) => block.id === id),
+ onChange: (listener: () => void) => {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ },
+ insertBlocks: vi.fn((inserted: RoomDocumentPartialBlock[]) => {
+ blocks = [
+ ...blocks,
+ ...inserted.map((block, index) => ({
+ ...block,
+ id: `uploaded_${index}`,
+ children: [],
+ })),
+ ] as RoomDocumentEditor["document"];
+ notify();
+ }),
+ removeBlocks: vi.fn((ids: string[]) => {
+ blocks = blocks.filter((block) => !ids.includes(block.id));
+ notify();
+ }),
+ resolveFileUrl: vi.fn(async () => "blob:attachment"),
+ };
+ const portal = document.createElement("span");
+ const host = document.createElement("div");
+ host.append(portal);
+ document.body.append(host);
+ const view = (editable = true) => (
+ <QueryClientProvider client={queryClient}>
+ <CanvasMailAttachments
+ client={runtime.client}
+ documentId="document_1"
+ editor={editor as unknown as RoomDocumentEditor}
+ editable={editable}
+ portalTarget={portal}
+ scope="test"
+ />
+ </QueryClientProvider>
+ );
+ const result = render(view(), {
+ container: host.appendChild(document.createElement("div")),
+ baseElement: host,
+ });
+ return {
+ ...result,
+ editor,
+ portal,
+ view,
+ remote: (files: RoomDocumentPartialBlock[]) =>
+ act(() => {
+ blocks = [
+ ...blocks.filter((block) => block.type !== "file"),
+ ...files,
+ ] as RoomDocumentEditor["document"];
+ notify();
+ }),
+ };
+}
+
+function storedFile(
+ id = "attached",
+ name = "brief.pdf",
+): RoomDocumentPartialBlock {
+ return {
+ id,
+ type: "file",
+ props: { name, url: `document-asset:${id}` },
+ children: [],
+ };
+}
+
+function choose(
+ file = new File(["brief"], "brief.pdf", { type: "application/pdf" }),
+) {
+ fireEvent.change(
+ screen.getByLabelText("Email attachments", { selector: "input" }),
+ { target: { files: [file] } },
+ );
+}
+
+describe("Mail attachments", () => {
+ it("uploads durable file blocks, counts them in the header, and removes them without changing the body", async () => {
+ vi.mocked(uploadRoomDocumentAsset).mockResolvedValue(
+ "document-asset:asset_new",
+ );
+ const { editor, portal } = setup();
+ const input = screen.getByLabelText("Email attachments", {
+ selector: "input",
+ });
+ const pick = vi.spyOn(input as HTMLInputElement, "click");
+ fireEvent.click(screen.getByRole("button", { name: "Add attachments" }));
+ expect(pick).toHaveBeenCalledOnce();
+ choose();
+ await screen.findByRole("button", { name: "Remove brief.pdf" });
+ expect(portal).toHaveTextContent("1");
+ expect(editor.document.at(-1)).toMatchObject({
+ type: "file",
+ props: { name: "brief.pdf", url: "document-asset:asset_new" },
+ });
+ expect(await screen.findByText("1 KB")).toBeVisible();
+ fireEvent.click(screen.getByRole("button", { name: "Remove brief.pdf" }));
+ expect(editor.document.map((block) => block.id)).toEqual(["body"]);
+ expect(portal).not.toHaveTextContent("1");
+ });
+
+ it("keeps an image chosen as an attachment in a file block", async () => {
+ vi.mocked(uploadRoomDocumentAsset).mockResolvedValue(
+ "document-asset:asset_image",
+ );
+ const { editor } = setup();
+ choose(new File(["image"], "diagram.png", { type: "image/png" }));
+ await screen.findByRole("button", { name: "Remove diagram.png" });
+ expect(editor.document.at(-1)?.type).toBe("file");
+ });
+
+ it("shows an upload failure without inserting a broken block and allows a retry", async () => {
+ vi.mocked(uploadRoomDocumentAsset)
+ .mockRejectedValueOnce(new Error("Upload unavailable"))
+ .mockResolvedValueOnce("document-asset:asset_retry");
+ const { editor } = setup();
+ choose();
+ expect(await screen.findByRole("alert")).toHaveTextContent(
+ "Upload unavailable",
+ );
+ expect(editor.insertBlocks).not.toHaveBeenCalled();
+ choose();
+ await screen.findByRole("button", { name: "Remove brief.pdf" });
+ expect(screen.queryByRole("alert")).toBeNull();
+ });
+
+ it("includes existing attachments in the size limit before uploading", async () => {
+ const { editor } = setup([storedFile()], 15 << 20);
+ choose();
+ expect(await screen.findByRole("alert")).toHaveTextContent("15 MB");
+ expect(uploadRoomDocumentAsset).not.toHaveBeenCalled();
+ expect(editor.insertBlocks).not.toHaveBeenCalled();
+ });
+
+ it("reflects collaborative file changes and hides mutations in read-only mode", async () => {
+ const { remote, portal, rerender, view } = setup();
+ remote([storedFile()]);
+ await screen.findByRole("button", { name: "Remove brief.pdf" });
+ expect(portal).toHaveTextContent("1");
+ rerender(view(false));
+ expect(
+ screen.queryByRole("button", { name: "Add attachments" }),
+ ).toBeNull();
+ expect(
+ screen.queryByRole("button", { name: "Remove brief.pdf" }),
+ ).toBeNull();
+ expect(screen.getByRole("button", { name: "brief.pdf" })).toBeVisible();
+ });
+
+ it.each(["readonly", "unmount"])(
+ "does not insert an upload that completes after %s",
+ async (transition) => {
+ let finish!: (url: string) => void;
+ vi.mocked(uploadRoomDocumentAsset).mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const { editor, unmount, rerender, view } = setup();
+ choose();
+ await waitFor(() =>
+ expect(uploadRoomDocumentAsset).toHaveBeenCalledOnce(),
+ );
+ if (transition === "unmount") unmount();
+ else rerender(view(false));
+ await act(async () => finish("document-asset:asset_late"));
+ expect(editor.insertBlocks).not.toHaveBeenCalled();
+ },
+ );
+});
diff --git a/apps/web/src/features/rooms/documents/canvas/canvas-mail-attachments.tsx b/apps/web/src/features/rooms/documents/canvas/canvas-mail-attachments.tsx
new file mode 100644
index 00000000..f1836147
--- /dev/null
+++ b/apps/web/src/features/rooms/documents/canvas/canvas-mail-attachments.tsx
@@ -0,0 +1,264 @@
+import {
+ Attachment01Icon,
+ Cancel01Icon,
+ File01Icon,
+} from "@hugeicons/core-free-icons";
+import { parseRoomDocumentAssetReference } from "@linger/document-model";
+import {
+ queryOptions,
+ useQueries,
+ useQueryClient,
+} from "@tanstack/react-query";
+import { useLayoutEffect, useRef, useState } from "react";
+import { createPortal } from "react-dom";
+
+import { AutoHeight } from "@/components/ui/auto-height";
+import { Button } from "@/components/ui/button";
+import { Icon } from "@/components/ui/icon";
+import { teamHubData } from "@/features/teamhub/teamhub-api";
+import type { TeamHubClient } from "@/features/teamhub/teamhub-client";
+import { formatBytes } from "@/lib/format-bytes";
+import { uploadRoomDocumentAsset } from "../room-document-assets";
+import type { RoomDocumentEditor } from "../room-document-comment-schema";
+
+const maxAttachmentBytes = 15 << 20;
+
+function fileBlocks(blocks: RoomDocumentEditor["document"]) {
+ const files: { id: string; name: string; url: string }[] = [];
+ for (const block of blocks) {
+ if (block.type === "file" && block.props.url) {
+ files.push({
+ id: block.id,
+ name: block.props.name,
+ url: block.props.url,
+ });
+ }
+ files.push(...fileBlocks(block.children));
+ }
+ return files;
+}
+
+function assetQuery(client: TeamHubClient, reference: string) {
+ return queryOptions({
+ queryKey: ["document-asset", reference],
+ staleTime: Infinity,
+ queryFn: () => {
+ const documentAssetId = parseRoomDocumentAssetReference(reference);
+ if (!documentAssetId) throw new Error("Attachment reference is invalid.");
+ return teamHubData(
+ client.api.GET("/v0/document-assets/{documentAssetId}", {
+ params: { path: { documentAssetId } },
+ }),
+ );
+ },
+ });
+}
+
+export function CanvasMailAttachments({
+ client,
+ documentId,
+ editable,
+ editor,
+ portalTarget,
+ scope,
+}: {
+ client: TeamHubClient;
+ documentId: string;
+ editable: boolean;
+ editor: RoomDocumentEditor;
+ portalTarget?: HTMLElement | null;
+ scope: string;
+}) {
+ const queryClient = useQueryClient();
+ const [attachments, setAttachments] = useState(() =>
+ fileBlocks(editor.document),
+ );
+ const [uploading, setUploading] = useState(false);
+ const [error, setError] = useState<string>();
+ const input = useRef<HTMLInputElement>(null);
+ const busy = useRef(false);
+ const canEdit = useRef(editable);
+ const active = useRef(true);
+ useLayoutEffect(() => {
+ canEdit.current = editable;
+ }, [editable]);
+ useLayoutEffect(() => {
+ active.current = true;
+ const refresh = () => setAttachments(fileBlocks(editor.document));
+ refresh();
+ const unsubscribe = editor.onChange(refresh);
+ return () => {
+ active.current = false;
+ unsubscribe();
+ };
+ }, [editor]);
+ const metadata = useQueries({
+ queries: attachments.map((file) => assetQuery(client, file.url)),
+ });
+
+ async function add(files: File[]) {
+ if (!canEdit.current || busy.current || files.length === 0) return;
+ busy.current = true;
+ setUploading(true);
+ setError(undefined);
+ try {
+ if (files.some((file) => file.size === 0))
+ throw new Error("Empty files cannot be attached.");
+ const existing = await Promise.all(
+ fileBlocks(editor.document).map((file) =>
+ queryClient.ensureQueryData(assetQuery(client, file.url)),
+ ),
+ );
+ const total =
+ existing.reduce((sum, asset) => sum + asset.size_bytes, 0) +
+ files.reduce((sum, file) => sum + file.size, 0);
+ if (total > maxAttachmentBytes)
+ throw new Error("Attachments must total 15 MB or less.");
+ // Insert only durable assets; a failed upload must not leave a file placeholder.
+ for (const file of files) {
+ if (!active.current || !canEdit.current) return;
+ const url = await uploadRoomDocumentAsset(client, documentId, file);
+ if (!active.current || !canEdit.current) return;
+ const last = editor.document.at(-1);
+ if (!last)
+ throw new Error("The email is no longer available for editing.");
+ editor.insertBlocks(
+ [{ type: "file", props: { name: file.name, url } }],
+ last.id,
+ "after",
+ );
+ }
+ } catch (failure) {
+ if (active.current)
+ setError(
+ failure instanceof Error
+ ? failure.message
+ : "Could not attach the file. Try again.",
+ );
+ } finally {
+ busy.current = false;
+ if (active.current) setUploading(false);
+ }
+ }
+
+ async function download(file: { url: string; name: string }) {
+ setError(undefined);
+ try {
+ if (!editor.resolveFileUrl)
+ throw new Error("The attachment is not available for download.");
+ const url = await editor.resolveFileUrl(file.url);
+ if (!active.current) return;
+ const link = document.createElement("a");
+ link.href = url;
+ link.download = file.name || "attachment";
+ link.click();
+ } catch (failure) {
+ if (active.current)
+ setError(
+ failure instanceof Error
+ ? failure.message
+ : "Could not download the attachment.",
+ );
+ }
+ }
+
+ return (
+ <>
+ {attachments.length > 0 ? (
+ <style>
+ {attachments
+ .map(
+ (file) =>
+ `[data-knowledge-scope=${JSON.stringify(scope)}] .bn-block[data-id=${JSON.stringify(file.id)}] > .bn-block-content { display: none; }`,
+ )
+ .join("\n")}
+ </style>
+ ) : null}
+ {editable && portalTarget
+ ? createPortal(
+ <>
+ <input
+ ref={input}
+ aria-label="Email attachments"
+ className="hidden"
+ type="file"
+ multiple
+ onChange={(event) => {
+ const files = Array.from(event.currentTarget.files ?? []);
+ event.currentTarget.value = "";
+ void add(files);
+ }}
+ />
+ <Button
+ aria-label="Add attachments"
+ title="Add attachments"
+ tone="ghost"
+ size={attachments.length ? "compact" : "compactIcon"}
+ loading={uploading}
+ onClick={() => input.current?.click()}
+ >
+ {!uploading ? <Icon icon={Attachment01Icon} size={16} /> : null}
+ {attachments.length > 0 ? (
+ <span>{attachments.length}</span>
+ ) : null}
+ </Button>
+ </>,
+ portalTarget,
+ )
+ : null}
+ <AutoHeight>
+ {attachments.length > 0 || uploading || error ? (
+ <section aria-label="Email attachments" className="space-y-2 pt-5">
+ {attachments.map((file, index) => (
+ <div
+ key={file.id}
+ className="flex min-w-0 items-center gap-2 rounded-md bg-app-surface-soft px-3 py-2 text-sm"
+ >
+ <Icon
+ icon={File01Icon}
+ size={16}
+ className="shrink-0 text-app-muted"
+ />
+ <button
+ type="button"
+ className="min-w-0 flex-1 text-left [overflow-wrap:anywhere] hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ onClick={() => void download(file)}
+ >
+ {file.name || metadata[index]?.data?.filename || "Attachment"}
+ </button>
+ {metadata[index]?.data ? (
+ <span className="shrink-0 text-xs text-app-muted">
+ {formatBytes(metadata[index].data.size_bytes)}
+ </span>
+ ) : null}
+ {editable ? (
+ <Button
+ aria-label={`Remove ${file.name || "attachment"}`}
+ tone="ghost"
+ size="compactIcon"
+ onClick={() => {
+ if (canEdit.current && editor.getBlock(file.id))
+ editor.removeBlocks([file.id]);
+ }}
+ >
+ <Icon icon={Cancel01Icon} size={14} />
+ </Button>
+ ) : null}
+ </div>
+ ))}
+ {uploading ? (
+ <p role="status" className="text-xs text-app-muted">
+ Uploading attachments…
+ </p>
+ ) : null}
+ {error ? (
+ <p role="alert" className="text-xs text-destructive">
+ {error}
+ </p>
+ ) : null}
+ </section>
+ ) : null}
+ </AutoHeight>
+ </>
+ );
+}
diff --git a/apps/web/src/features/rooms/documents/canvas/canvas-mail-send.tsx b/apps/web/src/features/rooms/documents/canvas/canvas-mail-send.tsx
new file mode 100644
index 00000000..91f65d72
--- /dev/null
+++ b/apps/web/src/features/rooms/documents/canvas/canvas-mail-send.tsx
@@ -0,0 +1,190 @@
+import type { components } from "@linger/wire-contracts/teamhub-public/types";
+import {
+ queryOptions,
+ useMutation,
+ useQuery,
+ useQueryClient,
+} from "@tanstack/react-query";
+import { useCallback, useEffect, useState } from "react";
+
+import { externalConnectionsQueryOptions } from "@/features/apps/connected-apps-queries";
+import { teamHubData } from "@/features/teamhub/teamhub-api";
+import type { TeamHubClient } from "@/features/teamhub/teamhub-client";
+import { TeamHubError } from "@/features/teamhub/teamhub-error";
+import type { RoomDocumentEditor } from "../room-document-comment-schema";
+import { type CanvasDocument, canvasText } from "./canvas-document";
+
+export type MailCanvasState = components["schemas"]["MailCanvasState"];
+
+const inFlight = new Set<MailCanvasState["status"]>([
+ "queued",
+ "uploading",
+ "sending",
+]);
+
+/** Local email and delivery status; editing never contacts Gmail. */
+export function mailCanvasQueryOptions(
+ client: TeamHubClient,
+ documentId: string,
+) {
+ return queryOptions({
+ queryKey: ["mail-canvas", documentId],
+ queryFn: () =>
+ teamHubData(
+ client.api.GET("/v0/documents/{documentId}/mail", {
+ params: { path: { documentId } },
+ }),
+ ),
+ // The email's latest content may still be rendering right after an edit.
+ retry: (failures, error) =>
+ failures < 5 && error instanceof TeamHubError && error.status === 503,
+ retryDelay: 500,
+ refetchInterval: (query) =>
+ query.state.data && inFlight.has(query.state.data.status) ? 1_500 : false,
+ });
+}
+
+export const progressLabel: Partial<Record<MailCanvasState["status"], string>> =
+ {
+ queued: "Preparing…",
+ uploading: "Uploading to Gmail…",
+ sending: "Sending…",
+ };
+
+/**
+ * Sending a gmail canvas: what is saved in Linger is uploaded to Gmail and
+ * sent only when `send` runs, so the Human sends exactly what they see.
+ * `saved` says the editor showing the email, if any, has nothing unsaved.
+ */
+export function useMailCanvasSend(
+ client: TeamHubClient,
+ documentId: string,
+ saved: boolean,
+) {
+ const queryClient = useQueryClient();
+ const connections = useQuery(externalConnectionsQueryOptions(client));
+ const accounts =
+ connections.data?.connections.filter(
+ (connection) =>
+ connection.provider === "gmail" && connection.status === "active",
+ ) ?? [];
+ const [chosen, setChosen] = useState<string>();
+ const account =
+ accounts.find((connection) => connection.id === chosen) ?? accounts[0];
+ const mail = useQuery(mailCanvasQueryOptions(client, documentId));
+ const status = mail.data?.status;
+ const refresh = useCallback(
+ () =>
+ void queryClient.invalidateQueries({
+ queryKey: ["mail-canvas", documentId],
+ }),
+ [documentId, queryClient],
+ );
+ const mutation = useMutation({
+ mutationFn: async () => {
+ if (!account) throw new Error("Connect Gmail before sending.");
+ if (!mail.data) throw new Error("The email is still loading.");
+ // The digest of the email as this card last showed it: if anything
+ // changed since, TeamHub refuses and the card shows the new version.
+ return teamHubData(
+ client.api.POST("/v0/documents/{documentId}/mail", {
+ params: { path: { documentId } },
+ body: {
+ connection_id: account.id,
+ request_id: crypto.randomUUID(),
+ source_digest: mail.data.source_digest,
+ },
+ }),
+ );
+ },
+ onError: refresh,
+ onSuccess: (state) =>
+ queryClient.setQueryData(["mail-canvas", documentId], state),
+ });
+ const decline = useMutation({
+ mutationFn: () =>
+ teamHubData(
+ client.api.POST("/v0/documents/{documentId}/mail/decline", {
+ params: { path: { documentId } },
+ }),
+ ),
+ onError: refresh,
+ onSuccess: (state) =>
+ queryClient.setQueryData(["mail-canvas", documentId], state),
+ });
+ const busy =
+ mutation.isPending || (status !== undefined && inFlight.has(status));
+ const problem = mutation.error
+ ? mutation.error instanceof TeamHubError && mutation.error.status === 409
+ ? mutation.error.message || "The email changed. Review it and send again."
+ : mutation.error.message
+ : decline.error
+ ? decline.error.message
+ : status === "failed"
+ ? mail.data?.error
+ : undefined;
+ const canEdit = mail.data?.can_edit === true;
+ const canSend =
+ canEdit &&
+ saved &&
+ account !== undefined &&
+ Boolean(mail.data?.subject.trim()) &&
+ Boolean(mail.data?.to.trim()) &&
+ (status === "draft" || status === "failed" || status === "unknown");
+ const note = busy
+ ? (progressLabel[status ?? "queued"] ?? "Preparing…")
+ : !account && connections.isSuccess
+ ? "Connect Gmail to send"
+ : !saved
+ ? "Saving…"
+ : undefined;
+ return {
+ account,
+ accounts,
+ busy,
+ canEdit,
+ canSend,
+ choose: setChosen,
+ decline: () => decline.mutate(),
+ declining: decline.isPending,
+ mail: mail.data,
+ note,
+ problem: busy ? undefined : problem,
+ /** Ask for the latest digest after the editor saved a change. */
+ refresh,
+ send: () => mutation.mutate(),
+ status,
+ };
+}
+
+/**
+ * Records a delivery in the canvas header, so Agents and other readers see
+ * the email went out and the editor turns read-only. Shows nothing: Send
+ * lives on the email's card in the chat.
+ */
+export function CanvasMailSentSync({
+ canvas,
+ client,
+ documentId,
+ editable,
+ editor,
+}: {
+ canvas: CanvasDocument;
+ client: TeamHubClient;
+ documentId: string;
+ editable: boolean;
+ editor: RoomDocumentEditor;
+}) {
+ const status = useQuery(mailCanvasQueryOptions(client, documentId)).data
+ ?.status;
+ useEffect(() => {
+ if (status !== "sent" || canvas.status === "sent" || !editable) return;
+ editor.updateBlock(canvas.blockId, {
+ content: canvasText({
+ ...canvas,
+ fields: { ...canvas.fields, status: "sent" },
+ }),
+ });
+ }, [canvas, editable, editor, status]);
+ return null;
+}
diff --git a/apps/web/src/features/rooms/documents/canvas/canvas-mail-sender.tsx b/apps/web/src/features/rooms/documents/canvas/canvas-mail-sender.tsx
new file mode 100644
index 00000000..404de932
--- /dev/null
+++ b/apps/web/src/features/rooms/documents/canvas/canvas-mail-sender.tsx
@@ -0,0 +1,19 @@
+import { useQuery } from "@tanstack/react-query";
+
+import { externalConnectionsQueryOptions } from "@/features/apps/connected-apps-queries";
+import type { TeamHubClient } from "@/features/teamhub/teamhub-client";
+
+export function CanvasMailSender({ client }: { client: TeamHubClient }) {
+ const connections = useQuery(externalConnectionsQueryOptions(client));
+ const accounts = connections.data?.connections.filter(
+ (connection) =>
+ connection.provider === "gmail" && connection.status === "active",
+ );
+ return (
+ <span>
+ {accounts?.length === 1
+ ? accounts[0]?.identity_label || "Connected Gmail account"
+ : "Gmail account"}
+ </span>
+ );
+}
diff --git a/apps/web/src/features/rooms/documents/canvas/canvas-targets.ts b/apps/web/src/features/rooms/documents/canvas/canvas-targets.ts
index dfacea54..44295b52 100644
--- a/apps/web/src/features/rooms/documents/canvas/canvas-targets.ts
+++ b/apps/web/src/features/rooms/documents/canvas/canvas-targets.ts
@@ -19,7 +19,7 @@ export const canvasTargets: Record<string, CanvasTarget> = {
label: "Gmail",
fields: [
{ key: "to", label: "To", placeholder: "[email protected]" },
- { key: "cc", label: "Cc" },
+ { key: "cc", label: "Cc", placeholder: "Add recipients" },
{ key: "subject", label: "Subject" },
],
},
diff --git a/apps/web/src/features/rooms/documents/room-document-blocknote-editor.tsx b/apps/web/src/features/rooms/documents/room-document-blocknote-editor.tsx
index e2ed6cc6..013fb872 100644
--- a/apps/web/src/features/rooms/documents/room-document-blocknote-editor.tsx
+++ b/apps/web/src/features/rooms/documents/room-document-blocknote-editor.tsx
@@ -86,6 +86,9 @@ import {
canvasHiddenBlockRule,
useCanvas,
} from "./canvas/canvas-header";
+import { CanvasMailAttachments } from "./canvas/canvas-mail-attachments";
+import { CanvasMailSentSync } from "./canvas/canvas-mail-send";
+import { CanvasMailSender } from "./canvas/canvas-mail-sender";
const ignoreCommentsOpenChange = () => undefined;
@@ -93,6 +96,7 @@ export interface RoomDocumentBlockNoteEditorProps {
client: TeamHubClient;
commentsOpen?: boolean;
commentsPortalTarget?: HTMLElement | null;
+ mailAttachmentsPortalTarget?: HTMLElement | null;
canComment: boolean;
currentActorId: string;
documentId: string;
@@ -101,6 +105,7 @@ export interface RoomDocumentBlockNoteEditorProps {
surfaceEditorRef?: MutableRefObject<RoomDocumentEditor | null>;
/** Reports whether the Document is a canvas that has already been sent. */
onCanvasSentChange?: (sent: boolean) => void;
+ onCanvasTargetChange?: (target?: string) => void;
onHeadingsChange?: (headings: RoomDocumentHeading[]) => void;
onCommentsOpenChange?: (open: boolean) => void;
onReadOnlySessionResync?: () => void;
@@ -122,12 +127,14 @@ export function RoomDocumentBlockNoteEditor({
canComment,
commentsOpen,
commentsPortalTarget,
+ mailAttachmentsPortalTarget,
currentActorId,
documentId,
editable,
knowledgeDocumentTitle,
surfaceEditorRef,
onCanvasSentChange,
+ onCanvasTargetChange,
onHeadingsChange,
onCommentsOpenChange,
onReadOnlySessionResync,
@@ -367,6 +374,10 @@ export function RoomDocumentBlockNoteEditor({
const { agentEditing, canvas } = useCanvas(editor, session.awareness);
const canvasRule = canvasHiddenBlockRule(knowledge.scope, canvas);
const canvasSent = canvas?.status === "sent";
+ const canvasTarget = canvas?.target.id;
+ useLayoutEffect(() => {
+ onCanvasTargetChange?.(canvasTarget);
+ }, [canvasTarget, onCanvasTargetChange]);
useEffect(() => {
onCanvasSentChange?.(canvasSent);
}, [canvasSent, onCanvasSentChange]);
@@ -386,6 +397,7 @@ export function RoomDocumentBlockNoteEditor({
aria-label="Room Document editor"
className="room-document-blocknote relative min-h-[420px]"
data-editable={String(editable)}
+ data-canvas-target={canvasTarget}
data-empty={String(isEmptyDocument)}
data-knowledge-presentation={
knowledgeTitle !== undefined ? "true" : undefined
@@ -460,6 +472,11 @@ export function RoomDocumentBlockNoteEditor({
canvas={canvas}
editable={editable}
editor={editor}
+ sender={
+ canvasTarget === "gmail" ? (
+ <CanvasMailSender client={client} />
+ ) : undefined
+ }
/>
) : null}
<BlockNoteView
@@ -542,6 +559,26 @@ export function RoomDocumentBlockNoteEditor({
threadStore={threadStore}
/>
</BlockNoteView>
+ {canvasTarget === "gmail" ? (
+ <CanvasMailAttachments
+ key={`${documentId}:${editable && !canvasSent}`}
+ client={client}
+ documentId={documentId}
+ editable={editable && !canvasSent}
+ editor={editor}
+ portalTarget={mailAttachmentsPortalTarget}
+ scope={knowledge.scope}
+ />
+ ) : null}
+ {canvasTarget === "gmail" && canvas ? (
+ <CanvasMailSentSync
+ canvas={canvas}
+ client={client}
+ documentId={documentId}
+ editable={editable}
+ editor={editor}
+ />
+ ) : null}
{!readOnlyCommentPending && (
<ReadOnlySelectionCommentControl
anchorRef={readOnlyAnchorRef}
diff --git a/apps/web/src/features/rooms/documents/room-document-blocknote.css b/apps/web/src/features/rooms/documents/room-document-blocknote.css
index 4684eacf..2e0cee28 100644
--- a/apps/web/src/features/rooms/documents/room-document-blocknote.css
+++ b/apps/web/src/features/rooms/documents/room-document-blocknote.css
@@ -115,6 +115,14 @@
width: 100%;
}
+.room-document-header[data-mail-canvas] .room-document-header-identity {
+ flex: 1 1 0;
+}
+
+.room-document-header[data-mail-canvas] .room-document-header-actions {
+ flex: 0 0 auto;
+}
+
.room-document-layout--knowledge {
/* 768px reading column plus horizontal padding. */
max-width: calc(768px + 80px);
@@ -690,6 +698,12 @@
font-family: inherit;
}
+.room-document-blocknote[data-canvas-target="gmail"] .bn-editor {
+ min-height: 80px;
+ font-size: var(--chat-card-text-size);
+ line-height: 1.7;
+}
+
.room-document-blocknote .bn-editor {
min-height: 420px;
padding: 0;
diff --git a/apps/web/src/features/rooms/documents/room-document-surface.test.tsx b/apps/web/src/features/rooms/documents/room-document-surface.test.tsx
index 7f694b64..cf9e6cc4 100644
--- a/apps/web/src/features/rooms/documents/room-document-surface.test.tsx
+++ b/apps/web/src/features/rooms/documents/room-document-surface.test.tsx
@@ -82,6 +82,7 @@ vi.mock("./room-document-blocknote-editor-loader", () => ({
knowledgeDocumentTitle,
surfaceEditorRef,
onCanvasSentChange,
+ onCanvasTargetChange,
onHeadingsChange,
}: {
commentsOpen?: boolean;
@@ -97,6 +98,7 @@ vi.mock("./room-document-blocknote-editor-loader", () => ({
} | null;
};
onCanvasSentChange?: (sent: boolean) => void;
+ onCanvasTargetChange?: (target?: string) => void;
onHeadingsChange: (headings: unknown[]) => void;
}) => {
const editor = {
@@ -159,6 +161,9 @@ vi.mock("./room-document-blocknote-editor-loader", () => ({
<button onClick={() => onCanvasSentChange?.(true)} type="button">
Report sent canvas
</button>
+ <button onClick={() => onCanvasTargetChange?.("gmail")} type="button">
+ Report mail canvas
+ </button>
</div>
);
},
@@ -264,6 +269,32 @@ describe("Unified Document legacy convergence", () => {
expect(screen.getByRole("menuitem", { name: "Edit" })).toBeDisabled();
});
+ it("uses the Mail header and removes generic document chrome for a mail canvas", async () => {
+ const runtime = createDocumentTestRuntime();
+ const document = seedRoomDocument(runtime, "mail-canvas-layout");
+ showDocument(runtime, { ...document, can_edit_native_content: true });
+ renderUnifiedDocumentPage(
+ runtime,
+ `/t/tenant-northstar/documents/${document.id}`,
+ );
+ await screen.findByTestId("document-body");
+ fireEvent.click(screen.getByRole("button", { name: "Report mail canvas" }));
+ expect(await screen.findByText("Mail", { exact: true })).toBeVisible();
+ expect(
+ screen.queryByRole("button", { name: "Document mode" }),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "Table of contents" }),
+ ).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "Report sent canvas" }));
+ await waitFor(() =>
+ expect(screen.getByTestId("document-body")).toHaveAttribute(
+ "data-editable",
+ "false",
+ ),
+ );
+ });
+
it.each(["wiki_page", "wiki_source"] as const)(
"defaults only generated Wiki pages to knowledge reading, not %s source editing",
async (bindingKind) => {
diff --git a/apps/web/src/features/rooms/documents/unified-document-body.tsx b/apps/web/src/features/rooms/documents/unified-document-body.tsx
index b91070be..65eda557 100644
--- a/apps/web/src/features/rooms/documents/unified-document-body.tsx
+++ b/apps/web/src/features/rooms/documents/unified-document-body.tsx
@@ -135,10 +135,12 @@ function UnifiedDocumentEditorLayout({
client,
commentsOpen,
commentsPortalTarget,
+ mailAttachmentsPortalTarget,
consumeAutoFocusTitle,
editorRef,
isEditing,
onCanvasSentChange,
+ onCanvasTargetChange,
queryClient,
roomId,
resyncSession,
@@ -146,31 +148,34 @@ function UnifiedDocumentEditorLayout({
setHeadings,
tenantId,
} = model;
+ const mailCanvas = model.canvasTarget === "gmail";
return (
<div
className={`room-document-layout mx-auto min-h-full${knowledgeTitle !== undefined ? " room-document-layout--knowledge" : ""}`}
>
<div
- className={`room-document-content-lane mx-auto ${knowledgeTitle !== undefined ? "mb-6 border-b border-app-border pb-5" : "mb-3"}`}
+ className={`room-document-content-lane mx-auto ${mailCanvas ? "" : knowledgeTitle !== undefined ? "mb-6 border-b border-app-border pb-5" : "mb-3"}`}
>
<RoomDocumentConnectionStatus
onRetry={resyncSession}
session={session}
/>
- <UnifiedDocumentDraftTitle
- // eslint-disable-next-line jsx-a11y/no-autofocus -- the field is focused on purpose because the user just opened this dialog or inline editor
- autoFocus={autoFocusTitle}
- client={client}
- document={document}
- editorRef={editorRef}
- isEditing={isEditing}
- onAutoFocusConsumed={consumeAutoFocusTitle}
- queryClient={queryClient}
- session={session}
- tenantId={tenantId}
- />
+ {!mailCanvas ? (
+ <UnifiedDocumentDraftTitle
+ // eslint-disable-next-line jsx-a11y/no-autofocus -- the field is focused on purpose because the user just opened this dialog or inline editor
+ autoFocus={autoFocusTitle}
+ client={client}
+ document={document}
+ editorRef={editorRef}
+ isEditing={isEditing}
+ onAutoFocusConsumed={consumeAutoFocusTitle}
+ queryClient={queryClient}
+ session={session}
+ tenantId={tenantId}
+ />
+ ) : null}
</div>
- {knowledgeTitle === undefined ? (
+ {knowledgeTitle === undefined && !mailCanvas ? (
<div className="room-document-content-lane mx-auto mb-8 flex min-h-8 flex-wrap items-center gap-2 text-sm text-app-muted">
<span>By {document.owner.display_name}</span>
<span aria-hidden="true">·</span>
@@ -181,7 +186,9 @@ function UnifiedDocumentEditorLayout({
/>
</div>
) : null}
- <div className="room-document-content-lane mx-auto mb-4">
+ <div
+ className={`room-document-content-lane mx-auto${mailCanvas ? "" : " mb-4"}`}
+ >
<RoomDocumentRecoveryButton name={document.title} session={session} />
</div>
<ActiveRoomDocumentEditor
@@ -189,12 +196,14 @@ function UnifiedDocumentEditorLayout({
client={client}
commentsOpen={commentsOpen}
commentsPortalTarget={commentsPortalTarget}
+ mailAttachmentsPortalTarget={mailAttachmentsPortalTarget}
currentActorId={actorId}
documentId={document.id}
editorRef={editorRef}
isEditing={isEditing}
knowledgeDocumentTitle={knowledgeTitle}
onCanvasSentChange={onCanvasSentChange}
+ onCanvasTargetChange={onCanvasTargetChange}
onCommentsOpenChange={setCommentsOpen}
onHeadingsChange={setHeadings}
onReadOnlySessionResync={resyncSession}
@@ -375,12 +384,14 @@ function ActiveRoomDocumentEditor({
client,
commentsOpen,
commentsPortalTarget,
+ mailAttachmentsPortalTarget,
currentActorId,
documentId,
isEditing,
knowledgeDocumentTitle,
editorRef,
onCanvasSentChange,
+ onCanvasTargetChange,
onHeadingsChange,
onCommentsOpenChange,
onReadOnlySessionResync,
@@ -392,12 +403,14 @@ function ActiveRoomDocumentEditor({
client: ReturnType<typeof useTeamHubRuntime>["client"];
commentsOpen: boolean;
commentsPortalTarget: HTMLDivElement | null;
+ mailAttachmentsPortalTarget: HTMLSpanElement | null;
currentActorId: string;
documentId: string;
isEditing: boolean;
knowledgeDocumentTitle?: string;
editorRef: MutableRefObject<RoomDocumentEditor | null>;
onCanvasSentChange: (sent: boolean) => void;
+ onCanvasTargetChange: (target?: string) => void;
onHeadingsChange: (headings: RoomDocumentHeading[]) => void;
onCommentsOpenChange: (open: boolean) => void;
onReadOnlySessionResync: () => void;
@@ -416,12 +429,14 @@ function ActiveRoomDocumentEditor({
client={client}
commentsOpen={commentsOpen}
commentsPortalTarget={commentsPortalTarget}
+ mailAttachmentsPortalTarget={mailAttachmentsPortalTarget}
currentActorId={currentActorId}
documentId={documentId}
editable={isEditing && save.canEdit}
knowledgeDocumentTitle={knowledgeDocumentTitle}
surfaceEditorRef={editorRef}
onCanvasSentChange={onCanvasSentChange}
+ onCanvasTargetChange={onCanvasTargetChange}
onHeadingsChange={onHeadingsChange}
onCommentsOpenChange={onCommentsOpenChange}
onReadOnlySessionResync={onReadOnlySessionResync}
@@ -457,7 +472,7 @@ function RoomDocumentConnectionStatus({
);
}
-function RoomDocumentSaveIndicator({
+export function RoomDocumentSaveIndicator({
alwaysVisible = false,
isEditing,
session,
diff --git a/apps/web/src/features/rooms/documents/unified-document-header.tsx b/apps/web/src/features/rooms/documents/unified-document-header.tsx
index e6666e87..d04fa465 100644
--- a/apps/web/src/features/rooms/documents/unified-document-header.tsx
+++ b/apps/web/src/features/rooms/documents/unified-document-header.tsx
@@ -7,6 +7,7 @@ import {
TableOfContentsIcon,
Tick02Icon,
ViewIcon,
+ Mail01Icon,
} from "@hugeicons/core-free-icons";
import { useQuery } from "@tanstack/react-query";
import {
@@ -42,6 +43,7 @@ import { RoomDocumentPresence } from "./room-document-presence";
import { collaborationColor } from "./room-document-presence-model";
import { DocumentActionsMenu } from "./room-document-actions-menu";
import type { UnifiedDocumentPageModel } from "./use-unified-document-page-model";
+import { RoomDocumentSaveIndicator } from "./unified-document-body";
interface UnifiedDocumentPageHeaderProps {
documentContentRef: MutableRefObject<HTMLDivElement | null>;
@@ -94,6 +96,8 @@ export function UnifiedDocumentPageHeader({
duplicatePending={duplicatePending}
exportPending={exportPending}
canvasSent={canvasSent}
+ mailCanvas={model.canvasTarget === "gmail"}
+ setMailAttachmentsPortalTarget={model.setMailAttachmentsPortalTarget}
isEditing={isEditing}
onComments={() => setCommentsOpen((value) => !value)}
onCopyLink={() =>
@@ -170,6 +174,8 @@ function UnifiedDocumentHeader({
duplicatePending,
exportPending,
canvasSent,
+ mailCanvas,
+ setMailAttachmentsPortalTarget,
isEditing,
onComments,
onCopyLink,
@@ -197,6 +203,8 @@ function UnifiedDocumentHeader({
duplicatePending: boolean;
exportPending: boolean;
canvasSent: boolean;
+ mailCanvas: boolean;
+ setMailAttachmentsPortalTarget: (element: HTMLSpanElement | null) => void;
isEditing: boolean;
onComments: () => void;
onCopyLink: () => void;
@@ -238,7 +246,10 @@ function UnifiedDocumentHeader({
/>
) : null;
return (
- <header className="room-document-header border-b border-app-border/60">
+ <header
+ className="room-document-header border-b border-app-border/60"
+ data-mail-canvas={mailCanvas || undefined}
+ >
<div className="room-document-header-identity">
{!sidebar ? (
<>
@@ -256,7 +267,12 @@ function UnifiedDocumentHeader({
</Button>
</>
) : null}
- {document ? (
+ {mailCanvas ? (
+ <span className="flex items-center gap-2 text-sm font-medium text-app-ink">
+ <Icon icon={Mail01Icon} size={16} />
+ Mail
+ </span>
+ ) : document ? (
<div className="room-document-header-file">
<span className="truncate text-sm font-semibold text-app-ink">
{documentFileName(document)}
@@ -279,7 +295,23 @@ function UnifiedDocumentHeader({
)}
</div>
<div className="room-document-header-actions">
- {!isWikiPage ? presence : null}
+ {mailCanvas && session ? (
+ <span className="mr-2 text-xs text-app-muted">
+ <RoomDocumentSaveIndicator
+ alwaysVisible
+ isEditing={isEditing}
+ session={session}
+ />
+ </span>
+ ) : !isWikiPage ? (
+ presence
+ ) : null}
+ {mailCanvas ? (
+ <span
+ className="inline-flex items-center"
+ ref={setMailAttachmentsPortalTarget}
+ />
+ ) : null}
{document && !isWikiPage ? (
<Button
aria-label="Share"
@@ -308,7 +340,7 @@ function UnifiedDocumentHeader({
<Icon icon={Comment01Icon} />
</Button>
) : null}
- {!sidebar ? (
+ {!sidebar && !mailCanvas ? (
<Button
aria-label="Table of contents"
aria-pressed={tocOpen}
@@ -321,7 +353,8 @@ function UnifiedDocumentHeader({
</Button>
) : null}
{!sidebar ? actionsMenu : null}
- {!isWikiPage &&
+ {!mailCanvas &&
+ !isWikiPage &&
session &&
document?.format === "blocknote" &&
document.representation_format !== "html" ? (
diff --git a/apps/web/src/features/rooms/documents/use-unified-document-page-model.ts b/apps/web/src/features/rooms/documents/use-unified-document-page-model.ts
index 83076de6..d6c4a1dc 100644
--- a/apps/web/src/features/rooms/documents/use-unified-document-page-model.ts
+++ b/apps/web/src/features/rooms/documents/use-unified-document-page-model.ts
@@ -48,6 +48,20 @@ export function useUnifiedDocumentPageModel(sidebar?: {
// A sent mail canvas is final: editing it no longer changes what went out.
const [sentCanvasDocumentId, setSentCanvasDocumentId] = useState<string>();
const canvasSent = sentCanvasDocumentId === documentId;
+ const [canvasIdentity, setCanvasIdentity] = useState<{
+ documentId: string;
+ target?: string;
+ }>();
+ const [mailAttachmentsPortalTarget, setMailAttachmentsPortalTarget] =
+ useState<HTMLSpanElement | null>(null);
+ const canvasTarget =
+ canvasIdentity?.documentId === documentId
+ ? canvasIdentity.target
+ : undefined;
+ const onCanvasTargetChange = useCallback(
+ (target?: string) => setCanvasIdentity({ documentId, target }),
+ [documentId],
+ );
const onCanvasSentChange = useCallback(
(sent: boolean) => setSentCanvasDocumentId(sent ? documentId : undefined),
[documentId],
@@ -60,6 +74,9 @@ export function useUnifiedDocumentPageModel(sidebar?: {
actor: data.actor,
autoFocusTitle: route.autoFocusTitle,
canvasSent,
+ canvasTarget,
+ mailAttachmentsPortalTarget,
+ setMailAttachmentsPortalTarget,
client,
commentsOpen: panels.commentsOpen,
commentsPortalTarget: panels.commentsPortalTarget,
@@ -78,6 +95,7 @@ export function useUnifiedDocumentPageModel(sidebar?: {
headings: panels.headings,
historyOpen: panels.historyOpen,
onCanvasSentChange,
+ onCanvasTargetChange,
isEditing: isEditing && !session?.readOnly,
isSharedDocument: data.isSharedDocument,
queryClient,
diff --git a/contracts/generated/go/teamhubpublic/openapi.gen.go b/contracts/generated/go/teamhubpublic/openapi.gen.go
index 2a873400..48e7d12e 100644
--- a/contracts/generated/go/teamhubpublic/openapi.gen.go
+++ b/contracts/generated/go/teamhubpublic/openapi.gen.go
@@ -2576,6 +2576,42 @@ func (e LocalSkillScanRequestRuntimeType) Valid() bool {
}
}
+// Defines values for MailCanvasStateStatus.
+const (
+ MailCanvasStateStatusDeclined MailCanvasStateStatus = "declined"
+ MailCanvasStateStatusDraft MailCanvasStateStatus = "draft"
+ MailCanvasStateStatusFailed MailCanvasStateStatus = "failed"
+ MailCanvasStateStatusQueued MailCanvasStateStatus = "queued"
+ MailCanvasStateStatusSending MailCanvasStateStatus = "sending"
+ MailCanvasStateStatusSent MailCanvasStateStatus = "sent"
+ MailCanvasStateStatusUnknown MailCanvasStateStatus = "unknown"
+ MailCanvasStateStatusUploading MailCanvasStateStatus = "uploading"
+)
+
+// Valid indicates whether the value is a known member of the MailCanvasStateStatus enum.
+func (e MailCanvasStateStatus) Valid() bool {
+ switch e {
+ case MailCanvasStateStatusDeclined:
+ return true
+ case MailCanvasStateStatusDraft:
+ return true
+ case MailCanvasStateStatusFailed:
+ return true
+ case MailCanvasStateStatusQueued:
+ return true
+ case MailCanvasStateStatusSending:
+ return true
+ case MailCanvasStateStatusSent:
+ return true
+ case MailCanvasStateStatusUnknown:
+ return true
+ case MailCanvasStateStatusUploading:
+ return true
+ default:
+ return false
+ }
+}
+
// Defines values for MemoryEntryKind.
const (
MemoryEntryKindDaily MemoryEntryKind = "daily"
@@ -3910,22 +3946,22 @@ func (e WorkItemPriority) Valid() bool {
// Defines values for WorkItemResolution.
const (
- WorkItemResolutionCompleted WorkItemResolution = "completed"
- WorkItemResolutionDuplicate WorkItemResolution = "duplicate"
- WorkItemResolutionFailed WorkItemResolution = "failed"
- WorkItemResolutionNotPlanned WorkItemResolution = "not_planned"
+ Completed WorkItemResolution = "completed"
+ Duplicate WorkItemResolution = "duplicate"
+ Failed WorkItemResolution = "failed"
+ NotPlanned WorkItemResolution = "not_planned"
)
// Valid indicates whether the value is a known member of the WorkItemResolution enum.
func (e WorkItemResolution) Valid() bool {
switch e {
- case WorkItemResolutionCompleted:
+ case Completed:
return true
- case WorkItemResolutionDuplicate:
+ case Duplicate:
return true
- case WorkItemResolutionFailed:
+ case Failed:
return true
- case WorkItemResolutionNotPlanned:
+ case NotPlanned:
return true
default:
return false
@@ -6564,6 +6600,23 @@ type LoginRequest struct {
Password *string `json:"password,omitempty"`
}
+// MailCanvasState defines model for MailCanvasState.
+type MailCanvasState struct {
+ // CanEdit Whether the caller may send or decline this email.
+ CanEdit bool `json:"can_edit"`
+ Error *string `json:"error,omitempty"`
+ MessageId *string `json:"message_id,omitempty"`
+
+ // SourceDigest Fingerprint of the saved email; Send must echo it so only the reviewed version goes out.
+ SourceDigest string `json:"source_digest"`
+ Status MailCanvasStateStatus `json:"status"`
+ Subject string `json:"subject"`
+ To string `json:"to"`
+}
+
+// MailCanvasStateStatus defines model for MailCanvasState.Status.
+type MailCanvasStateStatus string
+
// ManifestVersion Immutable strict Semantic Version for a Skill Manifest.
type ManifestVersion = string
@@ -7974,6 +8027,14 @@ type SaveVoiceProviderKeyRequest struct {
ApiKey string `json:"api_key"`
}
+// SendMailCanvasRequest defines model for SendMailCanvasRequest.
+type SendMailCanvasRequest struct {
+ // ConnectionId Opaque, case-sensitive identifier. Clients must not infer type or time from it.
+ ConnectionId Id `json:"connection_id"`
+ RequestId string `json:"request_id"`
+ SourceDigest string `json:"source_digest"`
+}
+
// Session defines model for Session.
type Session struct {
// AccountId Opaque, case-sensitive identifier. Clients must not infer type or time from it.
@@ -9672,6 +9733,9 @@ type RevokeDocumentLinkShareJSONRequestBody = RevokeDocumentLinkShare
// SetDocumentLinkShareJSONRequestBody defines body for SetDocumentLinkShare for application/json ContentType.
type SetDocumentLinkShareJSONRequestBody = SetDocumentLinkShare
+// SendMailCanvasJSONRequestBody defines body for SendMailCanvas for application/json ContentType.
+type SendMailCanvasJSONRequestBody = SendMailCanvasRequest
+
// RemoveDocumentFromRoomJSONRequestBody defines body for RemoveDocumentFromRoom for application/json ContentType.
type RemoveDocumentFromRoomJSONRequestBody = DocumentRoomBindingRemoveRequest
diff --git a/contracts/generated/typescript/src/generated/teamhub-public/types.ts b/contracts/generated/typescript/src/generated/teamhub-public/types.ts
index 01284482..156910b9 100644
--- a/contracts/generated/typescript/src/generated/teamhub-public/types.ts
+++ b/contracts/generated/typescript/src/generated/teamhub-public/types.ts
@@ -3092,6 +3092,45 @@ export interface paths {
patch?: never;
trace?: never;
};
+ "/v0/documents/{documentId}/mail": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ documentId: components["parameters"]["DocumentId"];
+ };
+ cookie?: never;
+ };
+ /** Read the local email and its delivery status without contacting Gmail. */
+ get: operations["getMailCanvas"];
+ put?: never;
+ /** Upload and send the exact local email the Human reviewed. */
+ post: operations["sendMailCanvas"];
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
+ "/v0/documents/{documentId}/mail/decline": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ documentId: components["parameters"]["DocumentId"];
+ };
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ /** Record that the Human chose not to send this email. */
+ post: operations["declineMailCanvas"];
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/v0/documents/{documentId}/open": {
parameters: {
query?: never;
@@ -7289,6 +7328,31 @@ export interface components {
status: "restored" | "already_current";
history_entry: components["schemas"]["DocumentHistoryEntry"];
};
+ MailCanvasState: {
+ /** @enum {string} */
+ status:
+ | "draft"
+ | "queued"
+ | "uploading"
+ | "sending"
+ | "sent"
+ | "failed"
+ | "unknown"
+ | "declined";
+ subject: string;
+ to: string;
+ error?: string;
+ message_id?: string;
+ /** @description Whether the caller may send or decline this email. */
+ can_edit: boolean;
+ /** @description Fingerprint of the saved email; Send must echo it so only the reviewed version goes out. */
+ source_digest: string;
+ };
+ SendMailCanvasRequest: {
+ connection_id: components["schemas"]["Id"];
+ request_id: string;
+ source_digest: string;
+ };
RoomDocumentCollaborationCredential: {
document_id: components["schemas"]["Id"];
/** @description Signed connection token, opaque to the browser, that Document Runtime verifies when the connection opens. */
@@ -13245,6 +13309,90 @@ export interface operations {
409: components["responses"]["Conflict"];
};
};
+ getMailCanvas: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ documentId: components["parameters"]["DocumentId"];
+ };
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description Local draft or delivery receipt. */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["MailCanvasState"];
+ };
+ };
+ 401: components["responses"]["Unauthenticated"];
+ 404: components["responses"]["NotFound"];
+ 503: components["responses"]["ServiceUnavailable"];
+ };
+ };
+ sendMailCanvas: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ documentId: components["parameters"]["DocumentId"];
+ };
+ cookie?: never;
+ };
+ requestBody: {
+ content: {
+ "application/json": components["schemas"]["SendMailCanvasRequest"];
+ };
+ };
+ responses: {
+ /** @description Delivery accepted. Editing alone never creates a Gmail draft. */
+ 202: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["MailCanvasState"];
+ };
+ };
+ 400: components["responses"]["BadRequest"];
+ 401: components["responses"]["Unauthenticated"];
+ 403: components["responses"]["Forbidden"];
+ 404: components["responses"]["NotFound"];
+ 409: components["responses"]["Conflict"];
+ 503: components["responses"]["ServiceUnavailable"];
+ };
+ };
+ declineMailCanvas: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ documentId: components["parameters"]["DocumentId"];
+ };
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description The email is marked as not sent; Send is no longer offered. */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["MailCanvasState"];
+ };
+ };
+ 401: components["responses"]["Unauthenticated"];
+ 403: components["responses"]["Forbidden"];
+ 404: components["responses"]["NotFound"];
+ 409: components["responses"]["Conflict"];
+ 503: components["responses"]["ServiceUnavailable"];
+ };
+ };
openDocument: {
parameters: {
query?: never;
diff --git a/contracts/openapi/components/mail-canvas.yaml b/contracts/openapi/components/mail-canvas.yaml
new file mode 100644
index 00000000..4d7e8fdb
--- /dev/null
+++ b/contracts/openapi/components/mail-canvas.yaml
@@ -0,0 +1,35 @@
+components:
+ schemas:
+ MailCanvasState:
+ type: object
+ additionalProperties: false
+ required: [status, subject, to, source_digest, can_edit]
+ properties:
+ status:
+ type: string
+ enum:
+ [draft, queued, uploading, sending, sent, failed, unknown, declined]
+ subject: { type: string }
+ to: { type: string }
+ error: { type: string }
+ message_id: { type: string }
+ can_edit:
+ type: boolean
+ description: Whether the caller may send or decline this email.
+ source_digest:
+ type: string
+ description: Fingerprint of the saved email; Send must echo it so only the reviewed version goes out.
+ SendMailCanvasRequest:
+ type: object
+ additionalProperties: false
+ required: [connection_id, request_id, source_digest]
+ properties:
+ connection_id:
+ $ref: "./common.yaml#/components/schemas/Id"
+ request_id:
+ type: string
+ minLength: 16
+ maxLength: 120
+ source_digest:
+ type: string
+ pattern: "^sha256:[0-9a-f]{64}$"
diff --git a/contracts/openapi/teamhub-public/teamhub-api.openapi.yaml b/contracts/openapi/teamhub-public/teamhub-api.openapi.yaml
index 31ccd04c..26252f77 100644
--- a/contracts/openapi/teamhub-public/teamhub-api.openapi.yaml
+++ b/contracts/openapi/teamhub-public/teamhub-api.openapi.yaml
@@ -3961,6 +3961,79 @@ paths:
$ref: '../components/common.yaml#/components/responses/NotFound'
'409':
$ref: '../components/common.yaml#/components/responses/Conflict'
+ /v0/documents/{documentId}/mail:
+ parameters:
+ - $ref: '#/components/parameters/DocumentId'
+ get:
+ tags: [Documents]
+ operationId: getMailCanvas
+ summary: Read the local email and its delivery status without contacting Gmail.
+ responses:
+ '200':
+ description: Local draft or delivery receipt.
+ content:
+ application/json:
+ schema:
+ $ref: '../components/mail-canvas.yaml#/components/schemas/MailCanvasState'
+ '401':
+ $ref: '../components/common.yaml#/components/responses/Unauthenticated'
+ '404':
+ $ref: '../components/common.yaml#/components/responses/NotFound'
+ '503':
+ $ref: '../components/common.yaml#/components/responses/ServiceUnavailable'
+ post:
+ tags: [Documents]
+ operationId: sendMailCanvas
+ summary: Upload and send the exact local email the Human reviewed.
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '../components/mail-canvas.yaml#/components/schemas/SendMailCanvasRequest'
+ responses:
+ '202':
+ description: Delivery accepted. Editing alone never creates a Gmail draft.
+ content:
+ application/json:
+ schema:
+ $ref: '../components/mail-canvas.yaml#/components/schemas/MailCanvasState'
+ '400':
+ $ref: '../components/common.yaml#/components/responses/BadRequest'
+ '401':
+ $ref: '../components/common.yaml#/components/responses/Unauthenticated'
+ '403':
+ $ref: '../components/common.yaml#/components/responses/Forbidden'
+ '404':
+ $ref: '../components/common.yaml#/components/responses/NotFound'
+ '409':
+ $ref: '../components/common.yaml#/components/responses/Conflict'
+ '503':
+ $ref: '../components/common.yaml#/components/responses/ServiceUnavailable'
+ /v0/documents/{documentId}/mail/decline:
+ parameters:
+ - $ref: '#/components/parameters/DocumentId'
+ post:
+ tags: [Documents]
+ operationId: declineMailCanvas
+ summary: Record that the Human chose not to send this email.
+ responses:
+ '200':
+ description: The email is marked as not sent; Send is no longer offered.
+ content:
+ application/json:
+ schema:
+ $ref: '../components/mail-canvas.yaml#/components/schemas/MailCanvasState'
+ '401':
+ $ref: '../components/common.yaml#/components/responses/Unauthenticated'
+ '403':
+ $ref: '../components/common.yaml#/components/responses/Forbidden'
+ '404':
+ $ref: '../components/common.yaml#/components/responses/NotFound'
+ '409':
+ $ref: '../components/common.yaml#/components/responses/Conflict'
+ '503':
+ $ref: '../components/common.yaml#/components/responses/ServiceUnavailable'
/v0/documents/{documentId}/open:
parameters:
- $ref: '#/components/parameters/DocumentId'
diff --git a/skills/builtin/canvas/1.0.3/SKILL.md b/skills/builtin/canvas/1.0.3/SKILL.md
new file mode 100644
index 00000000..d3b0409d
--- /dev/null
+++ b/skills/builtin/canvas/1.0.3/SKILL.md
@@ -0,0 +1,136 @@
+---
+name: canvas
+description: Draft content that will be sent to an outside platform (first target - a new Gmail email) on a canvas the user watches and edits in the Room side panel. Use when the user asks you to write or prepare a new email; reply to an existing email with teamhub gmail reply instead.
+---
+
+# Canvas
+
+A canvas is an ordinary Room Document that the user sees open in the side
+panel while you write. You and the user both edit it; when the user decides,
+you deliver it to its target platform. Targets are listed under `targets/`;
+read the matching guide before delivering.
+
+## Shape
+
+The first block is a fenced code block that starts with `canvas: <target>`,
+followed by `key: value` lines, one per line. Everything after it is the content
+to deliver.
+
+````markdown
+```
+canvas: gmail
+cc:
+subject: Following up on last week's quote
+status: editing
+link:
+external_id:
+```
+
+Hi Lisa,
+...
+````
+
+Shared lines for every target:
+
+- `status`: `editing` while drafting, `draft` once saved on the platform as a
+ draft, `sent` once delivered.
+- `link`: an `https://` link to the draft or delivered item, when you have one.
+- `external_id`: the platform's ID for the draft or item.
+
+The target guide lists its own fields. Write every line when you open the
+canvas, leaving a value empty rather than inventing it, so each can later be
+filled in place; ask the user for anything you need.
+
+## Open a canvas
+
+1. Write the canvas to a local Markdown file and create the Document:
+ `teamhub docs create --title "<short title>" --file ./canvas.md`.
+ Put every image the content needs in that Markdown, where it belongs in
+ the body (`![Card](./card.png)`, path relative to the Markdown file);
+ `docs create` uploads it into the canvas.
+2. Open it for the user with a canvas message (it also shows as a card):
+
+ ```json
+ {"segments":[{"type":"document","document_id":"<document-id>","content":"<short title>","presentation":"canvas"}]}
+ ```
+
+ `teamhub message send --message-file ./open-canvas.json`
+
+Open one canvas per piece of content and keep working on the same canvas for
+follow-up requests. Everything that goes out with the content, images and
+attached files included, lives in the canvas: never paste the body into the
+chat and never send its images or files as chat attachments. If an image or
+file cannot be placed in the canvas, say so plainly instead of posting it in
+the chat.
+
+## Edit while the user watches
+
+- Every request to change the canvas (rewrite the text, change one paragraph,
+ replace an image, ...) starts by reading the latest canvas, because the user may
+ have edited it since: `teamhub docs get <document-id> --format blocks -o ./canvas.json`.
+ This gives the current text and the block IDs; the first block is the canvas header.
+- Within that request, an edit that returns `"status":"applied"` succeeded; make the
+ next change without reading the canvas again. Read it again only when an edit is
+ rejected as a conflict, when you need the ID of a block you just added (for example
+ an image you will replace later), and once after your last change to check the result.
+- Change content with `teamhub docs update <document-id> --command <action>`
+ (`block_replace`, `block_insert_after`, `append`, `str_replace`, ...).
+- Change one header line with `str_replace` on that line, narrowed to the
+ header block: `--block-id <header-block-id> --pattern "subject: Old" --content "subject: New"`.
+ `str_replace` changes one line at a time and its text cannot contain a line
+ break, so change several header lines with one `str_replace` each.
+- Make small, frequent edits so the user sees progress.
+
+## Images
+
+Images live in the canvas as image blocks (PNG, JPEG, GIF or WebP, up to 10 MiB).
+
+- Add one: `teamhub docs image put <document-id> ./card.png --after <block-id> [--caption "..."]`.
+- Change one (recolor, crop, a new version): save the original with
+ `teamhub docs image get <document-id> <image-block-id> -o ./original.png`, make the new
+ image, then `teamhub docs image put <document-id> ./new.png --replace <image-block-id>`.
+ The image keeps its place and width.
+ - Crop, resize, rotate, recolor or compress with the `imagemagick` skill.
+ - Generate an image, or change it by description (new background, new style), only
+ with your model's own image generation, using the original as reference. If you
+ cannot generate images, say so plainly and offer what `imagemagick` can do.
+- Undo a replacement: the previous image stays available for about a day. Find its Asset
+ in the earlier `--format blocks` export and put it back with
+ `teamhub docs update <document-id> --command image_replace --block-id <block-id> --asset-id <old-asset-id>`.
+- Image block IDs and Assets come from `teamhub docs get <document-id> --format blocks`.
+
+## Attached files
+
+A file the content carries (a PDF, a deck, a spreadsheet) is a file block in
+the canvas; the target guide says how it is delivered.
+
+- Add one: `teamhub docs file put <document-id> ./proposal.pdf --after <block-id>`.
+ It takes PDF, Office (docx, xlsx, pptx), ZIP, CSV, Markdown, text or image
+ files up to 15 MiB each; an unsupported file is refused.
+- Put file blocks at the end of the content, after the signature, unless the
+ user wants them elsewhere.
+- Remove one with `teamhub docs update <document-id> --command block_delete --block-id <file-block-id>`.
+- The user may also drop a file into the canvas themselves; it is delivered
+ the same way.
+
+## The user's edits win
+
+The user may type in the canvas at the same time. An edit made against an
+older version is rejected as a conflict: never retry it blindly and never
+overwrite what the user wrote. Read the canvas again, keep the user's text,
+and redo only what is still needed. If the user changed something you were
+asked to change, follow the user's version.
+
+## Deliver
+
+Follow the target guide: it says whether the user delivers from the canvas
+card or you deliver with a command.
+
+- Without a Send button in the target guide: if the user has not said how to
+ deliver, save it on the platform as a draft; if the user says to send it,
+ send it. After delivering, update the header: `status`, `link` and
+ `external_id`.
+- Tell the user in one short sentence what you did and where to find it.
+
+Only report a draft or delivery as done after the command succeeded.
diff --git a/skills/builtin/canvas/1.0.3/targets/gmail.md b/skills/builtin/canvas/1.0.3/targets/gmail.md
new file mode 100644
index 00000000..33c1d33e
--- /dev/null
+++ b/skills/builtin/canvas/1.0.3/targets/gmail.md
@@ -0,0 +1,42 @@
+# Target: gmail
+
+A gmail canvas is for a new email only. To answer an email someone sent, use
+`teamhub gmail reply` instead; a canvas draft does not join that thread.
+
+Fields in the canvas header:
+
+- `to`: recipient emails, separated by commas only (never semicolons).
+- `cc`: carbon-copy emails, separated by commas only; may be empty.
+- `subject`: one line.
+
+The email body is everything after the header block. Images in the canvas go
+into the email body as inline images, exactly as they appear in the canvas.
+File blocks in the canvas go as attachments, under their file names; their
+lines do not appear in the body. Attach files only through the canvas: never
+use `teamhub gmail send --attach` or `teamhub gmail draft --attach` for a
+canvas email, since the draft and the email are rebuilt from the canvas.
+
+## Send
+
+The canvas card in the chat has a Send button. Editing the canvas only saves
+it in Linger; when the user clicks Send, Linger uploads the canvas, its inline
+images and attachments included, to Gmail and sends it exactly as the user
+sees it, then marks the header `status: sent`.
+
+- Do not save a Gmail draft and do not send a canvas email yourself: no
+ `teamhub gmail canvas-draft`, `teamhub gmail draft` or `teamhub gmail send`
+ for it.
+- When the canvas is ready, or the user asks you to send it, tell them in one
+ short sentence to review it and click Send on the email card.
+- Never set `status`, `link` or `external_id` yourself.
+
+Images must stay under 5 MiB in total; shrink large ones first (for example
+with `imagemagick`). Attachments must stay under 15 MiB in total; for larger
+files, share a link in the body instead.
+
+## Gmail not connected or not sent
+
+If Gmail is not connected, the card says so and Send stays off; tell the user
+to connect Gmail in Connected apps. If the card says the email was not sent or
+asks to check Gmail, do not resend it yourself; tell the user what the card
+says.
diff --git a/skills/builtin/catalog.yaml b/skills/builtin/catalog.yaml
index 559d844c..8390ca84 100644
--- a/skills/builtin/catalog.yaml
+++ b/skills/builtin/catalog.yaml
@@ -94,11 +94,14 @@ skills:
version: 1.0.0
package_path: builtin/proactive-response/1.0.0
- skill_id: simplexai_canvas
- bootstrap_manifest_id: skill_manifest_simplexai_canvas_1_0_2
+ bootstrap_manifest_id: skill_manifest_simplexai_canvas_1_0_3
default_agent_types:
- anotherme
- general
manifests:
+ - manifest_id: skill_manifest_simplexai_canvas_1_0_3
+ version: 1.0.3
+ package_path: builtin/canvas/1.0.3
- manifest_id: skill_manifest_simplexai_canvas_1_0_2
version: 1.0.2
package_path: builtin/canvas/1.0.2