Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.
fix(teamhub): tell Outlook sent mail by its folder, not the identity label
shoudi zhengc0aff1bb8c2d
diff --git a/apps/teamhub/internal/composio/mail_admission_test.go b/apps/teamhub/internal/composio/mail_admission_test.goindex 741d54a0..171c8890 100644--- a/apps/teamhub/internal/composio/mail_admission_test.go+++ b/apps/teamhub/internal/composio/mail_admission_test.go@@ -89,15 +89,15 @@ func TestGmailMailImportFiltersSendersWithoutReadingTheirBodies(t *testing.T) {func TestOutlookMailImportKeepsFocusedAndOwnMail(t *testing.T) {end := time.Date(2026, 10, 29, 12, 0, 0, 0, time.UTC)- item := func(id, from, classification string) map[string]any {- return map[string]any{"id": id, "subject": "Re " + id, "receivedDateTime": end.Add(-time.Hour).Format(time.RFC3339), "parentFolderId": "inbox",+ item := func(id, folder, from, classification string) map[string]any {+ return map[string]any{"id": id, "subject": "Re " + id, "receivedDateTime": end.Add(-time.Hour).Format(time.RFC3339), "parentFolderId": folder,"inferenceClassification": classification, "from": map[string]any{"emailAddress": map[string]string{"address": from}},"body": map[string]string{"contentType": "text", "content": fmt.Sprintf("Body of %s.", id)}}}client := mailImportClient(t, func(request proxyRequest) any {switch request.Endpoint {- case "https://graph.microsoft.com/v1.0/me":- return map[string]string{"id": "alice", "mail": "[email protected]"}+ case "/v1.0/me/mailFolders/sentitems":+ return map[string]string{"id": "sent"}case "/v1.0/me/mailFolders/junkemail":return map[string]string{"id": "junk"}case "/v1.0/me/mailFolders/deleteditems":@@ -109,10 +109,10 @@ func TestOutlookMailImportKeepsFocusedAndOwnMail(t *testing.T) {}}return map[string]any{"value": []any{- item("focused", "[email protected]", "focused"),- item("other", "[email protected]", "other"),- item("sent", "[email protected]", "other"),- item("robot", "[email protected]", "focused"),+ item("focused", "inbox", "[email protected]", "focused"),+ item("other", "inbox", "[email protected]", "other"),+ item("sent", "sent", "[email protected]", "other"),+ item("robot", "inbox", "[email protected]", "focused"),}}})page, err := client.FetchMailImportPage(context.Background(), "account", "outlook", MailImportPageOptions{Start: MailImportStart(end), End: end, Limit: 10})diff --git a/apps/teamhub/internal/composio/mail_import.go b/apps/teamhub/internal/composio/mail_import.goindex ddc6c44e..3e671a24 100644--- a/apps/teamhub/internal/composio/mail_import.go+++ b/apps/teamhub/internal/composio/mail_import.go@@ -171,9 +171,8 @@ func (c *Client) fetchGmailImportMessage(ctx context.Context, accountID, id stri}type outlookImportCursor struct {- Link string `json:"link"`- Email string `json:"email"`- Junk, Deleted string+ Link string `json:"link"`+ Junk, Deleted, Sent string}func (c *Client) fetchOutlookImportPage(ctx context.Context, accountID string, options MailImportPageOptions) (MailImportPage, error) {@@ -183,19 +182,14 @@ func (c *Client) fetchOutlookImportPage(ctx context.Context, accountID string, oreturn MailImportPage{}, errors.New("invalid Outlook import cursor")}} else {- identity, err := c.IdentifyOutlook(ctx, accountID)- if err != nil {- return MailImportPage{}, err- }- cursor.Email = strings.ToLower(strings.TrimSpace(identity.Label))for _, folder := range []struct {name stringtarget *string- }{{"junkemail", &cursor.Junk}, {"deleteditems", &cursor.Deleted}} {+ }{{"junkemail", &cursor.Junk}, {"deleteditems", &cursor.Deleted}, {"sentitems", &cursor.Sent}} {var response struct {ID string `json:"id"`}- if err = c.mailImportCall(ctx, options, proxyRequest{ConnectedAccountID: accountID, Endpoint: "/v1.0/me/mailFolders/" + folder.name, Method: http.MethodGet, Parameters: []proxyParameter{{Name: "$select", Value: "id", Type: "query"}}}, &response, "read Outlook excluded folder"); err != nil {+ if err := c.mailImportCall(ctx, options, proxyRequest{ConnectedAccountID: accountID, Endpoint: "/v1.0/me/mailFolders/" + folder.name, Method: http.MethodGet, Parameters: []proxyParameter{{Name: "$select", Value: "id", Type: "query"}}}, &response, "read Outlook well-known folder"); err != nil {return MailImportPage{}, err}if response.ID == "" {@@ -204,7 +198,7 @@ func (c *Client) fetchOutlookImportPage(ctx context.Context, accountID string, o*folder.target = response.ID}}- if cursor.Email == "" || cursor.Junk == "" || cursor.Deleted == "" {+ if cursor.Junk == "" || cursor.Deleted == "" || cursor.Sent == "" {return MailImportPage{}, errors.New("incomplete Outlook import cursor")}request, err := graphPollRequest(accountID, cursor.Link)@@ -254,7 +248,10 @@ func (c *Client) fetchOutlookImportPage(ctx context.Context, accountID string, opage.Skipped++continue}- owner := strings.EqualFold(item.From.EmailAddress.Address, cursor.Email)+ // The mailbox's Sent Items folder, not an address, marks the owner's+ // mail: the sign-in address may differ from the mailbox address. Sent+ // mail the owner moved out of Sent Items counts as received.+ owner := item.ParentFolderID == cursor.Sent// Focused is filtered here rather than in $filter, which Graph may// refuse beside the received-time order; the owner's mail always enters.if item.IsDraft || item.ParentFolderID == cursor.Junk || item.ParentFolderID == cursor.Deleted || received.Before(options.Start) || !received.Before(options.End) ||@@ -382,7 +379,10 @@ type OutlookIdentity struct {ID, Label string}-// IdentifyOutlook returns the signed-in mailbox, which also tells sent mail from received mail.+// IdentifyOutlook returns the signed-in mailbox. The label is display only:+// Graph leaves mail empty for a personal account signed in with another+// provider's address, whose userPrincipalName is that sign-in address, so the+// sender of the newest Sent Items message names the mailbox before it.func (c *Client) IdentifyOutlook(ctx context.Context, accountID string) (OutlookIdentity, error) {var wire struct {ID string `json:"id"`@@ -393,6 +393,14 @@ func (c *Client) IdentifyOutlook(ctx context.Context, accountID string) (Outlookreturn OutlookIdentity{}, err}label := wire.Mail+ if label == "" {+ // A failed read fails identification rather than falling back, so a+ // throttled check keeps the stored label instead of the sign-in address.+ var err error+ if label, err = c.outlookSentAddress(ctx, accountID); err != nil {+ return OutlookIdentity{}, err+ }+ }if label == "" {label = wire.Principal}@@ -401,3 +409,24 @@ func (c *Client) IdentifyOutlook(ctx context.Context, accountID string) (Outlook}return OutlookIdentity{wire.ID, label}, nil}++// outlookSentAddress returns the sender of the newest Sent Items message, or+// "" when Sent Items is empty.+func (c *Client) outlookSentAddress(ctx context.Context, accountID string) (string, error) {+ var wire struct {+ Value []struct {+ From outlookRecipient `json:"from"`+ } `json:"value"`+ }+ if err := c.proxy(ctx, proxyRequest{ConnectedAccountID: accountID, Endpoint: "/v1.0/me/mailFolders/sentitems/messages", Method: http.MethodGet, Parameters: []proxyParameter{+ {Name: "$top", Value: "1", Type: "query"},+ {Name: "$orderby", Value: "sentDateTime desc", Type: "query"},+ {Name: "$select", Value: "from", Type: "query"},+ }}, &wire, "read Outlook sent mailbox address"); err != nil {+ return "", err+ }+ if len(wire.Value) == 0 {+ return "", nil+ }+ return strings.TrimSpace(wire.Value[0].From.EmailAddress.Address), nil+}diff --git a/apps/teamhub/internal/composio/mail_import_test.go b/apps/teamhub/internal/composio/mail_import_test.goindex cdb317f5..294c7bf0 100644--- a/apps/teamhub/internal/composio/mail_import_test.go+++ b/apps/teamhub/internal/composio/mail_import_test.go@@ -106,8 +106,8 @@ func TestOutlookMailImportReadsBodiesAndContinues(t *testing.T) {listCalls := 0client := mailImportClient(t, func(request proxyRequest) any {switch request.Endpoint {- case "https://graph.microsoft.com/v1.0/me":- return map[string]string{"id": "alice", "mail": "[email protected]"}+ case "/v1.0/me/mailFolders/sentitems":+ return map[string]string{"id": "sent"}case "/v1.0/me/mailFolders/junkemail":return map[string]string{"id": "junk"}case "/v1.0/me/mailFolders/deleteditems":@@ -310,8 +310,8 @@ func TestOutlookMailImportSkipsMalformedItems(t *testing.T) {}client := mailImportClient(t, func(request proxyRequest) any {switch request.Endpoint {- case "https://graph.microsoft.com/v1.0/me":- return map[string]string{"id": "alice", "mail": "[email protected]"}+ case "/v1.0/me/mailFolders/sentitems":+ return map[string]string{"id": "sent"}case "/v1.0/me/mailFolders/junkemail":return map[string]string{"id": "junk"}case "/v1.0/me/mailFolders/deleteditems":@@ -327,3 +327,126 @@ func TestOutlookMailImportSkipsMalformedItems(t *testing.T) {t.Fatalf("page=%+v", page)}}++func outlookFolderClient(t *testing.T, messages []any) *Client {+ t.Helper()+ return mailImportClient(t, func(request proxyRequest) any {+ switch request.Endpoint {+ case "/v1.0/me/mailFolders/sentitems":+ return map[string]string{"id": "sent"}+ case "/v1.0/me/mailFolders/junkemail":+ return map[string]string{"id": "junk"}+ case "/v1.0/me/mailFolders/deleteditems":+ return map[string]string{"id": "trash"}+ case "/v1.0/me/messages":+ return map[string]any{"value": messages}+ }+ t.Errorf("unexpected endpoint %s", request.Endpoint)+ return nil+ })+}++func TestOutlookMailImportTellsSentMailByFolder(t *testing.T) {+ end := time.Date(2026, 10, 29, 12, 0, 0, 0, time.UTC)+ item := func(id, folder, from, classification string) map[string]any {+ return map[string]any{"id": id, "subject": "Hi", "receivedDateTime": end.Add(-time.Hour).Format(time.RFC3339), "parentFolderId": folder, "inferenceClassification": classification, "from": map[string]any{"emailAddress": map[string]string{"address": from}}, "body": map[string]string{"contentType": "text", "content": "Hello there, a real message."}}+ }+ // The sign-in address sends to the mailbox; the mailbox address sends+ // from Sent Items. Only the folder decides direction.+ client := outlookFolderClient(t, []any{+ item("sent-other", "sent", "[email protected]", "other"),+ item("received-focused", "inbox", "[email protected]", "focused"),+ item("received-other", "inbox", "[email protected]", "other"),+ item("sent-noreply", "sent", "[email protected]", "other"),+ })+ page, err := client.FetchMailImportPage(context.Background(), "account", "outlook", MailImportPageOptions{Start: MailImportStart(end), End: end, Limit: 10})+ if err != nil {+ t.Fatal(err)+ }+ directions := map[string]string{}+ for _, document := range page.Documents {+ body := string(document.Markdown)+ switch {+ case strings.Contains(body, "- Direction: outbound"):+ directions[document.RemoteID] = "outbound"+ case strings.Contains(body, "- Direction: inbound"):+ directions[document.RemoteID] = "inbound"+ default:+ t.Fatalf("no direction in %s", body)+ }+ }+ want := map[string]string{"message:sent-other": "outbound", "message:received-focused": "inbound", "message:sent-noreply": "outbound"}+ if fmt.Sprint(directions) != fmt.Sprint(want) {+ t.Fatalf("directions=%v, want %v", directions, want)+ }+ if page.Read != 4 || page.NextCursor != "" {+ t.Fatalf("page=%+v", page)+ }+}++func TestOutlookMailImportRejectsCursorWithoutSentFolder(t *testing.T) {+ end := time.Date(2026, 10, 29, 12, 0, 0, 0, time.UTC)+ client := outlookFolderClient(t, nil)+ _, err := client.FetchMailImportPage(context.Background(), "account", "outlook", MailImportPageOptions{Start: MailImportStart(end), End: end, Limit: 10,+ Cursor: `{"link":"https://graph.microsoft.com/v1.0/me/messages?$skip=1","email":"[email protected]","Junk":"junk","Deleted":"trash"}`})+ if err == nil || err.Error() != "incomplete Outlook import cursor" {+ t.Fatalf("err=%v", err)+ }+}++func TestIdentifyOutlookLabel(t *testing.T) {+ for _, test := range []struct {+ name, mail string+ sent any+ want string+ fails bool+ }{+ {"mail", "[email protected]", map[string]any{"value": []any{map[string]any{"from": map[string]any{"emailAddress": map[string]string{"address": "[email protected]"}}}}}, "[email protected]", false},+ {"sent items sender", "", map[string]any{"value": []any{map[string]any{"from": map[string]any{"emailAddress": map[string]string{"address": "[email protected]"}}}}}, "[email protected]", false},+ {"empty sent items", "", map[string]any{"value": []any{}}, "[email protected]", false},+ {"sent items error", "", nil, "", true},+ } {+ t.Run(test.name, func(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ var request proxyRequest+ if err := json.NewDecoder(r.Body).Decode(&request); err != nil {+ t.Error(err)+ return+ }+ switch request.Endpoint {+ case "https://graph.microsoft.com/v1.0/me":+ _ = json.NewEncoder(w).Encode(map[string]any{"status": 200, "data": map[string]string{"id": "graph-id", "mail": test.mail, "userPrincipalName": "[email protected]"}})+ case "/v1.0/me/mailFolders/sentitems/messages":+ if test.sent == nil {+ w.WriteHeader(http.StatusInternalServerError)+ return+ }+ _ = json.NewEncoder(w).Encode(map[string]any{"status": 200, "data": test.sent})+ default:+ t.Errorf("unexpected endpoint %s", request.Endpoint)+ }+ }))+ defer server.Close()+ client, err := New(Config{APIKey: "test", EnvironmentKey: "test", BaseURL: server.URL, HTTPClient: server.Client()})+ if err != nil {+ t.Fatal(err)+ }+ client.SetConnectionAuthority(func(context.Context, string) (ConnectionBinding, error) {+ return ConnectionBinding{}, nil+ })+ identity, err := client.IdentifyOutlook(context.Background(), "account")+ if test.fails {+ if err == nil {+ t.Fatalf("identity=%+v, want the Sent Items error", identity)+ }+ return+ }+ if err != nil {+ t.Fatal(err)+ }+ if identity.ID != "graph-id" || identity.Label != test.want {+ t.Fatalf("identity=%+v, want label %s", identity, test.want)+ }+ })+ }+}diff --git a/apps/teamhub/migrations/00879_reimport_outlook_mail_by_sent_folder.sql b/apps/teamhub/migrations/00879_reimport_outlook_mail_by_sent_folder.sqlnew file mode 100644index 00000000..e632a5a4--- /dev/null+++ b/apps/teamhub/migrations/00879_reimport_outlook_mail_by_sent_folder.sql@@ -0,0 +1,45 @@+-- +goose Up+-- Outlook mail direction now comes from the mailbox's Sent Items folder+-- instead of the identity label, which for a personal account signed in with+-- another provider's address is that sign-in address, not the mailbox. Every+-- Outlook snapshot is dropped so it is read again with the right direction.+--+-- A running import's next page finds no running snapshot and ends. An active+-- Connection that had a snapshot gets a mail connection job, which starts a+-- new one; nothing else starts it without the user. Re-imported messages+-- replace their Wiki sources by the same mailbox key.+--+-- The jobs wait 30 minutes: this migration runs before the rolling update, and+-- a pod still on the old direction logic that took one would complete the+-- import wrongly with nothing left to reset it.+CREATE TEMPORARY TABLE outlook_mail_reimport AS+SELECT connection.id, connection.account_id, actor.tenant_id, connection.status = 'active' AS active+FROM external_connections connection+LEFT JOIN actors actor ON actor.account_id = connection.account_id AND actor.kind = 'human'+WHERE connection.provider = 'outlook' AND connection.mail_import_revision IS NOT NULL;++DELETE FROM external_mail_import_documents document+USING outlook_mail_reimport reimport+WHERE document.connection_id = reimport.id;++UPDATE external_connections connection+SET mail_import_status = NULL, mail_import_revision = NULL, mail_import_tenant_id = NULL,+ mail_import_error_code = NULL, mail_import_cursor = NULL, mail_import_read = NULL,+ mail_import_provider_calls = NULL, mail_synced_until = NULL+FROM outlook_mail_reimport reimport+WHERE connection.id = reimport.id;++INSERT INTO river_job(kind, queue, args, max_attempts, state, scheduled_at)+SELECT 'external.mail_connection', 'external',+ jsonb_build_object('account_id', reimport.account_id, 'tenant_id', reimport.tenant_id, 'connection_id', reimport.id), 10,+ 'scheduled', now() + interval '30 minutes'+FROM outlook_mail_reimport reimport+WHERE reimport.active AND reimport.tenant_id IS NOT NULL+ORDER BY reimport.id;++SELECT notify_river_queue('external');++DROP TABLE outlook_mail_reimport;++-- +goose Down+-- The dropped snapshots are not restored; the next import reads them again.diff --git a/apps/teamhub/tests/integration/outlook_mail_reimport_migration_test.go b/apps/teamhub/tests/integration/outlook_mail_reimport_migration_test.gonew file mode 100644index 00000000..d2b9b72b--- /dev/null+++ b/apps/teamhub/tests/integration/outlook_mail_reimport_migration_test.go@@ -0,0 +1,77 @@+package integration_test++import (+ "os"+ "path/filepath"+ "testing"++ "github.com/jackc/pgx/v5/pgxpool"+)++// The migration drops every Outlook snapshot and queues a new one for each+// active Outlook Connection that had one, 30 minutes out so pods on the old+// logic finish rolling first; Gmail snapshots stay.+func TestOutlookMailReimportMigrationResetsOnlyOutlook(t *testing.T) {+ allowParallelIntegrationTest(t)+ ctx := t.Context()+ pool, err := pgxpool.New(ctx, newIntegrationDatabase(t))+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(pool.Close)+ for _, connection := range []struct{ id, provider, status string }{+ {"reimport-outlook-active", "outlook", "active"},+ {"reimport-outlook-expired", "outlook", "expired"},+ {"reimport-gmail-active", "gmail", "active"},+ } {+ if _, err = pool.Exec(ctx, `INSERT INTO external_connections(id,account_id,provider,upstream_connection_id,status,+ mail_import_status,mail_import_revision,mail_import_tenant_id,mail_import_cursor,mail_import_read,mail_import_provider_calls,mail_synced_until)+ SELECT $1,account_id,$2,'upstream-'||$1,$3,'completed',0,tenant_id,'',1,3,now() FROM actors WHERE id='actor_acme_alice'`,+ connection.id, connection.provider, connection.status); err != nil {+ t.Fatal(err)+ }+ if _, err = pool.Exec(ctx, `INSERT INTO external_mail_import_documents(connection_id,remote_id,ordinal,document) VALUES($1,'message:1',0,'{}')`, connection.id); err != nil {+ t.Fatal(err)+ }+ }+ migration, err := os.ReadFile(filepath.Join(teamHubMigrationDirectory(t), "00879_reimport_outlook_mail_by_sent_folder.sql"))+ if err != nil {+ t.Fatal(err)+ }+ if _, err = pool.Exec(ctx, string(migration)); err != nil {+ t.Fatal(err)+ }+ for id, wantImport := range map[string]bool{"reimport-outlook-active": false, "reimport-outlook-expired": false, "reimport-gmail-active": true} {+ var hasImport bool+ var documents int+ if err = pool.QueryRow(ctx, `SELECT mail_import_status IS NOT NULL AND mail_synced_until IS NOT NULL,(SELECT count(*) FROM external_mail_import_documents WHERE connection_id=$1) FROM external_connections WHERE id=$1`, id).Scan(&hasImport, &documents); err != nil {+ t.Fatal(err)+ }+ if hasImport != wantImport || (documents == 1) != wantImport {+ t.Fatalf("%s import=%v documents=%d", id, hasImport, documents)+ }+ }+ rows, err := pool.Query(ctx, `SELECT args->>'connection_id',args->>'tenant_id',queue,state='scheduled' AND scheduled_at>=now()+interval '29 minutes' AND scheduled_at<=now()+interval '31 minutes' FROM river_job WHERE kind='external.mail_connection' ORDER BY id`)+ if err != nil {+ t.Fatal(err)+ }+ defer rows.Close()+ var queued []string+ for rows.Next() {+ var connectionID, tenantID, queue string+ var delayed bool+ if err = rows.Scan(&connectionID, &tenantID, &queue, &delayed); err != nil {+ t.Fatal(err)+ }+ if tenantID != acmeTenant || queue != "external" || !delayed {+ t.Fatalf("job tenant=%s queue=%s delayed=%v", tenantID, queue, delayed)+ }+ queued = append(queued, connectionID)+ }+ if err = rows.Err(); err != nil {+ t.Fatal(err)+ }+ if len(queued) != 1 || queued[0] != "reimport-outlook-active" {+ t.Fatalf("queued=%v", queued)+ }+}