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.

fix(teamhub): key mail Wiki sources by mailbox, not Connection

muterC7d4e1f562e4a
diff --git a/apps/teamhub/internal/externalsource/jobs.go b/apps/teamhub/internal/externalsource/jobs.go
index 9958e462..bedb87e9 100644
--- a/apps/teamhub/internal/externalsource/jobs.go
+++ b/apps/teamhub/internal/externalsource/jobs.go
@@ -31,6 +31,9 @@ type TransientImportResult struct {
Status string
LastErrorCode string
Fetched int
+ // Mailbox is a mailbox import's mailbox identity, which with each
+ // document's RemoteID names its Wiki source (MailWikiSourceKey).
+ Mailbox string
}
// importRun is one connection import. Nothing about it is stored: its caller
@@ -45,7 +48,9 @@ type importRun struct {
CreatedAt time.Time
callsUsed atomic.Int64
mail bool
- result TransientImportResult
+ // mailbox keys a mail run's Wiki sources; see MailWikiSourceKey.
+ mailbox string
+ result TransientImportResult
}
// ImportSlack fetches the selected Slack conversations for its caller.
diff --git a/apps/teamhub/internal/externalsource/mail_import.go b/apps/teamhub/internal/externalsource/mail_import.go
index 57138d17..296263ec 100644
--- a/apps/teamhub/internal/externalsource/mail_import.go
+++ b/apps/teamhub/internal/externalsource/mail_import.go
@@ -23,6 +23,14 @@ type MailWikiSource struct {
Content []byte
}
+// MailWikiSourceKey names a message's Wiki source by its mailbox, the
+// Connection's remote principal key ("gmail:<address>" or "outlook:<user id>"),
+// not by the Connection, so reconnecting the same mailbox updates the sources
+// an earlier Connection wrote. The provider is the key's second segment.
+func MailWikiSourceKey(mailbox, remoteID string) string {
+ return "mail:" + mailbox + ":" + remoteID
+}
+
// MailImported names a mailbox snapshot that just completed.
type MailImported struct {
TenantID, OwnerActorID, ConnectionID string
@@ -224,9 +232,9 @@ func (s *Service) runMailImportPage(ctx context.Context, args MailImportArgs) er
job := &importRun{ConnectionID: args.ConnectionID, ConnectionRevision: args.Revision, ProviderCallBudget: mailImportBudget, CreatedAt: time.Now().UTC(), mail: true}
var progress mailImportProgress
var active bool
- err := s.pool.QueryRow(ctx, `SELECT account_id,mail_import_tenant_id,provider,upstream_connection_id,mail_import_cursor,mail_import_read,status='active' AND revision=$2
+ err := s.pool.QueryRow(ctx, `SELECT account_id,mail_import_tenant_id,provider,upstream_connection_id,coalesce(remote_principal_key,''),mail_import_cursor,mail_import_read,status='active' AND revision=$2
FROM external_connections WHERE id=$1 AND mail_import_revision=$2 AND mail_import_status='running'`, args.ConnectionID, args.Revision).Scan(
- &job.AccountID, &job.TenantID, &job.Provider, &job.UpstreamConnectionID, &progress.cursor, &progress.read, &active)
+ &job.AccountID, &job.TenantID, &job.Provider, &job.UpstreamConnectionID, &job.mailbox, &progress.cursor, &progress.read, &active)
if errors.Is(err, pgx.ErrNoRows) {
return nil
}
@@ -236,6 +244,11 @@ func (s *Service) runMailImportPage(ctx context.Context, args MailImportArgs) er
if !active {
return s.abandonMailImport(ctx, args.ConnectionID, args.Revision)
}
+ // An active mail Connection always has its mailbox identity; without one
+ // its messages could not be keyed apart from another mailbox's.
+ if job.mailbox == "" {
+ return s.failImport(ctx, job, "invalid_request")
+ }
if job.OwnerActorID, err = s.ownerActorID(ctx, job.AccountID, job.TenantID); errors.Is(err, ErrNotFound) {
return s.failImport(ctx, job, "owner_not_found")
} else if err != nil {
@@ -394,7 +407,7 @@ func (s *Service) publishMailPage(ctx context.Context, job *importRun, documents
}
if err := s.writeMailWikiSource(ctx, MailWikiSource{
TenantID: job.TenantID, OwnerActorID: job.OwnerActorID,
- SourceKey: "mail:" + job.ConnectionID + ":" + document.RemoteID,
+ SourceKey: MailWikiSourceKey(job.mailbox, document.RemoteID),
Filename: mailWikiFilename(document.Filename), Content: document.Markdown,
}); err != nil {
return err
@@ -426,15 +439,15 @@ func (s *Service) ReadMailImport(ctx context.Context, accountID, tenantID, conne
if err := s.EnsureMailImport(ctx, accountID, tenantID, connectionID); err != nil {
return TransientImportResult{}, err
}
- var status, code string
- err := s.pool.QueryRow(ctx, `SELECT CASE WHEN mail_import_revision=revision THEN coalesce(mail_import_status,'running') ELSE 'running' END,coalesce(mail_import_error_code,'') FROM external_connections WHERE id=$1 AND account_id=$2`, connectionID, accountID).Scan(&status, &code)
+ var status, code, mailbox string
+ err := s.pool.QueryRow(ctx, `SELECT CASE WHEN mail_import_revision=revision THEN coalesce(mail_import_status,'running') ELSE 'running' END,coalesce(mail_import_error_code,''),coalesce(remote_principal_key,'') FROM external_connections WHERE id=$1 AND account_id=$2`, connectionID, accountID).Scan(&status, &code, &mailbox)
if errors.Is(err, pgx.ErrNoRows) {
return TransientImportResult{}, ErrNotFound
}
if err != nil {
return TransientImportResult{}, err
}
- result := TransientImportResult{Status: status, LastErrorCode: code}
+ result := TransientImportResult{Status: status, LastErrorCode: code, Mailbox: mailbox}
if status != "completed" {
return result, nil
}
diff --git a/apps/teamhub/internal/externalsource/mail_sync.go b/apps/teamhub/internal/externalsource/mail_sync.go
index 0738d1e8..d099fd50 100644
--- a/apps/teamhub/internal/externalsource/mail_sync.go
+++ b/apps/teamhub/internal/externalsource/mail_sync.go
@@ -97,8 +97,8 @@ func (s *Service) EnqueueMailSyncs(ctx context.Context, now time.Time) error {
// syncMail reads, within one run, every page of the mail received since the
// Connection's sync position, and then moves the position to where it read
// to. A run that fails leaves the position, so River's retry or the next
-// night reads the window again. A Connection that changed meanwhile, or whose
-// owner left the Tenant, is left alone.
+// night reads the window again. A Connection that changed meanwhile, has no
+// mailbox identity, or whose owner left the Tenant, is left alone.
func (s *Service) syncMail(ctx context.Context, args MailSyncArgs) error {
queries := store.New(s.pool)
state, err := queries.GetMailSync(ctx, store.GetMailSyncParams{ID: args.ConnectionID, Revision: args.Revision})
@@ -108,10 +108,13 @@ func (s *Service) syncMail(ctx context.Context, args MailSyncArgs) error {
if err != nil {
return err
}
+ if state.Mailbox == "" {
+ return nil
+ }
job := &importRun{
ConnectionID: args.ConnectionID, ConnectionRevision: args.Revision, AccountID: state.AccountID,
TenantID: state.TenantID, Provider: state.Provider, UpstreamConnectionID: state.UpstreamConnectionID,
- ProviderCallBudget: mailImportBudget, CreatedAt: time.Now().UTC(),
+ ProviderCallBudget: mailImportBudget, CreatedAt: time.Now().UTC(), mailbox: state.Mailbox,
}
if job.OwnerActorID, err = s.ownerActorID(ctx, state.AccountID, state.TenantID); errors.Is(err, ErrNotFound) {
return nil
diff --git a/apps/teamhub/internal/personalprofile/admission.go b/apps/teamhub/internal/personalprofile/admission.go
index 948241b0..06c6b845 100644
--- a/apps/teamhub/internal/personalprofile/admission.go
+++ b/apps/teamhub/internal/personalprofile/admission.go
@@ -31,24 +31,24 @@ func (s *Service) fileAdmission(ctx context.Context, tenant, version string) (ad
return
}
-func (s *Service) connectionAdmission(ctx context.Context, claimed claimedGeneration, source storedSource, documents []composio.AppDocument) ([]bool, bool, error) {
+func (s *Service) connectionAdmission(ctx context.Context, claimed claimedGeneration, source storedSource, result externalsource.TransientImportResult) ([]bool, bool, error) {
if !externalsource.IsMailProvider(source.Provider) {
- allowed, err := s.transientAdmission(ctx, documents)
+ allowed, err := s.transientAdmission(ctx, result.Documents)
return allowed, false, err
}
- return s.mailAdmission(ctx, claimed, source.ConnectionID, documents)
+ return s.mailAdmission(ctx, claimed, result.Mailbox, result.Documents)
}
// mailAdmission matches the selected mailbox snapshot to its bound Wiki document,
// including the content hash: a newer message version cannot authorize older bytes.
-func (s *Service) mailAdmission(ctx context.Context, claimed claimedGeneration, connection string, documents []composio.AppDocument) ([]bool, bool, error) {
+func (s *Service) mailAdmission(ctx context.Context, claimed claimedGeneration, mailbox string, documents []composio.AppDocument) ([]bool, bool, error) {
keys := make([]string, 0, len(documents))
hashes := make([]string, 0, len(documents))
for _, d := range documents {
if len(d.ProfileMarkdown) == 0 {
continue
}
- keys = append(keys, "mail:"+connection+":"+d.RemoteID)
+ keys = append(keys, externalsource.MailWikiSourceKey(mailbox, d.RemoteID))
hash := sha256.Sum256(d.Markdown)
hashes = append(hashes, hex.EncodeToString(hash[:]))
}
@@ -79,7 +79,7 @@ func (s *Service) mailAdmission(ctx context.Context, claimed claimedGeneration,
admittedKeys[key] = ok
}
for i, d := range documents {
- admitted[i] = admittedKeys["mail:"+connection+":"+d.RemoteID]
+ admitted[i] = admittedKeys[externalsource.MailWikiSourceKey(mailbox, d.RemoteID)]
}
return admitted, false, rows.Err()
}
diff --git a/apps/teamhub/internal/personalprofile/worker.go b/apps/teamhub/internal/personalprofile/worker.go
index e96b1935..f1bd16ed 100644
--- a/apps/teamhub/internal/personalprofile/worker.go
+++ b/apps/teamhub/internal/personalprofile/worker.go
@@ -320,7 +320,7 @@ func (s *Service) collectGenerationDocuments(ctx context.Context, claimed claime
}
continue
}
- allowed, wait, err := s.connectionAdmission(ctx, claimed, source, result.Documents)
+ allowed, wait, err := s.connectionAdmission(ctx, claimed, source, result)
if err != nil || wait {
return collectedDocuments{}, wait, false, err
}
diff --git a/apps/teamhub/internal/store/external_mail_sync.sql.go b/apps/teamhub/internal/store/external_mail_sync.sql.go
index cb000a77..a287b0f2 100644
--- a/apps/teamhub/internal/store/external_mail_sync.sql.go
+++ b/apps/teamhub/internal/store/external_mail_sync.sql.go
@@ -43,6 +43,7 @@ func (q *Queries) AdvanceMailSync(ctx context.Context, arg AdvanceMailSyncParams
const getMailSync = `-- name: GetMailSync :one
SELECT account_id, mail_import_tenant_id::text AS tenant_id, provider, upstream_connection_id,
+ coalesce(remote_principal_key, '')::text AS mailbox,
mail_synced_until::timestamptz AS synced_until
FROM external_connections
WHERE id = $1::text AND revision = $2::bigint AND status = 'active'
@@ -60,6 +61,7 @@ type GetMailSyncRow struct {
TenantID string `json:"tenant_id"`
Provider string `json:"provider"`
UpstreamConnectionID string `json:"upstream_connection_id"`
+ Mailbox string `json:"mailbox"`
SyncedUntil pgtype.Timestamptz `json:"synced_until"`
}
@@ -73,6 +75,7 @@ func (q *Queries) GetMailSync(ctx context.Context, arg GetMailSyncParams) (GetMa
&i.TenantID,
&i.Provider,
&i.UpstreamConnectionID,
+ &i.Mailbox,
&i.SyncedUntil,
)
return i, err
diff --git a/apps/teamhub/internal/store/queries/external_mail_sync.sql b/apps/teamhub/internal/store/queries/external_mail_sync.sql
index 05ef4b89..68ab249d 100644
--- a/apps/teamhub/internal/store/queries/external_mail_sync.sql
+++ b/apps/teamhub/internal/store/queries/external_mail_sync.sql
@@ -12,6 +12,7 @@ ORDER BY id;
-- One Connection's sync position while it is still active at the revision
-- its sync was queued for.
SELECT account_id, mail_import_tenant_id::text AS tenant_id, provider, upstream_connection_id,
+ coalesce(remote_principal_key, '')::text AS mailbox,
mail_synced_until::timestamptz AS synced_until
FROM external_connections
WHERE id = sqlc.arg(id)::text AND revision = sqlc.arg(revision)::bigint AND status = 'active'
diff --git a/apps/teamhub/migrations/00875_key_mail_wiki_sources_by_mailbox.sql b/apps/teamhub/migrations/00875_key_mail_wiki_sources_by_mailbox.sql
new file mode 100644
index 00000000..cc030bc1
--- /dev/null
+++ b/apps/teamhub/migrations/00875_key_mail_wiki_sources_by_mailbox.sql
@@ -0,0 +1,154 @@
+-- +goose Up
+-- An imported message's Wiki source is keyed by its mailbox, the Connection's
+-- remote principal key ("gmail:<address>" or "outlook:<user id>"), instead of
+-- the Connection, so reconnecting the same mailbox updates the same Documents.
+--
+-- Sources that two Connections of one mailbox imported for the same message
+-- merge into one: the message keeps the source whose Document is active and
+-- bound to the Wiki, then the one written last. Every other source leaves the
+-- Wiki the way Trash removes a Document, since a Document is never deleted:
+-- its Document is trashed, its Bindings are suspended and its source row is
+-- deleted. A source whose Connection has no mailbox identity cannot be keyed
+-- and leaves the same way; mail is imported only after the Connection is
+-- identified, so none is expected.
+--
+-- A removed source's published row stays, so the next Wiki refresh sends it
+-- to LLM Wiki as a removed source and the pages citing it are rewritten
+-- instead of linking a trashed Document. A Wiki that loses more removed
+-- sources than one refresh accepts is refused until it is rebuilt. A frozen
+-- refresh keeps its rows; if it settles, its removed sources are published
+-- again and the next refresh removes them. Their unsettled try counts go with
+-- them. Memory's hourly reconciliation drops removed sources it indexed.
+CREATE TEMPORARY TABLE mail_wiki_source_merge AS
+WITH item AS (
+ SELECT item.tenant_id, item.owner_actor_id, item.source_key, item.document_id,
+ connection.remote_principal_key AS mailbox,
+ substr(item.source_key, length(split_part(item.source_key, ':', 2)) + 7) AS remote_id,
+ document.status = 'active' AND EXISTS (
+ SELECT 1 FROM document_context_bindings binding
+ WHERE binding.tenant_id = item.tenant_id AND binding.document_id = item.document_id
+ AND binding.binding_kind = 'wiki_source' AND binding.status = 'active') AS in_wiki,
+ item.updated_at, item.created_at
+ FROM wiki_source_items item
+ JOIN documents document ON document.id = item.document_id AND document.tenant_id = item.tenant_id
+ LEFT JOIN external_connections connection
+ ON connection.id = split_part(item.source_key, ':', 2) AND connection.remote_principal_key <> ''
+)
+SELECT item.tenant_id, item.owner_actor_id, item.source_key, item.document_id,
+ 'mail:' || item.mailbox || ':' || item.remote_id AS mailbox_key,
+ item.mailbox IS NOT NULL AND row_number() OVER (
+ PARTITION BY item.tenant_id, item.owner_actor_id, item.mailbox, item.remote_id
+ ORDER BY item.in_wiki DESC, item.updated_at DESC, item.created_at DESC, item.document_id) = 1 AS kept
+FROM item;
+
+DELETE FROM document_wiki_unsettled_sources unsettled
+USING mail_wiki_source_merge merged
+WHERE NOT merged.kept AND unsettled.tenant_id = merged.tenant_id AND unsettled.document_id = merged.document_id;
+
+DELETE FROM wiki_source_items item
+USING mail_wiki_source_merge merged
+WHERE NOT merged.kept AND item.tenant_id = merged.tenant_id
+ AND item.owner_actor_id = merged.owner_actor_id AND item.source_key = merged.source_key;
+
+UPDATE wiki_source_items item
+SET source_key = merged.mailbox_key
+FROM mail_wiki_source_merge merged
+WHERE merged.kept AND item.tenant_id = merged.tenant_id
+ AND item.owner_actor_id = merged.owner_actor_id AND item.source_key = merged.source_key;
+
+-- Each removed Document is trashed as one lifecycle operation, in Trash's
+-- order: the status, the access invalidation, then its suspended Bindings.
+WITH trashed AS (
+ UPDATE documents document
+ SET status = 'trashed',
+ trashed_at = GREATEST(document.updated_at, clock_timestamp()),
+ updated_at = GREATEST(document.updated_at, clock_timestamp())
+ FROM mail_wiki_source_merge merged
+ WHERE NOT merged.kept AND document.id = merged.document_id
+ AND document.tenant_id = merged.tenant_id AND document.status = 'active'
+ RETURNING document.id, document.tenant_id, document.owner_actor_id, document.updated_at
+), counted AS (
+ UPDATE document_permission_counts permission
+ SET permission_count = permission.permission_count + 1
+ FROM trashed
+ WHERE permission.document_id = trashed.id
+)
+INSERT INTO document_events(
+ id, tenant_id, document_id, event_type, actor_id, resource_kind, resource_id, projection_version, occurred_at
+)
+SELECT 'document_event_' || md5('merge_mail_wiki_source:' || trashed.id || ':' || event.type),
+ trashed.tenant_id, trashed.id, event.type, trashed.owner_actor_id, 'lifecycle_operation',
+ 'document_lifecycle_' || md5('merge_mail_wiki_source:' || trashed.id), 1,
+ GREATEST(clock_timestamp(), trashed.updated_at)
+FROM trashed
+CROSS JOIN (VALUES (1, 'document.access_invalidated'), (2, 'document.trashed')) event(position, type)
+ORDER BY trashed.id, event.position;
+
+WITH suspended AS (
+ UPDATE document_context_bindings binding
+ SET status = 'suspended', access_epoch = binding.access_epoch + 1, updated_at = clock_timestamp()
+ FROM mail_wiki_source_merge merged
+ WHERE NOT merged.kept AND binding.tenant_id = merged.tenant_id
+ AND binding.document_id = merged.document_id AND binding.status = 'active'
+ RETURNING binding.tenant_id, binding.document_id
+)
+INSERT INTO document_events(
+ id, tenant_id, document_id, event_type, actor_id, resource_kind, resource_id, projection_version, occurred_at
+)
+SELECT 'document_event_' || md5('merge_mail_wiki_source:' || document.id || ':document.binding_updated'),
+ document.tenant_id, document.id, 'document.binding_updated', document.owner_actor_id, 'binding_context',
+ 'document_lifecycle_' || md5('merge_mail_wiki_source:' || document.id), 1,
+ GREATEST(clock_timestamp(), document.updated_at)
+FROM documents document
+WHERE (document.tenant_id, document.id) IN (SELECT tenant_id, document_id FROM suspended)
+ORDER BY document.id;
+
+DROP TABLE mail_wiki_source_merge;
+
+-- The provider is the mailbox key's second segment.
+CREATE OR REPLACE VIEW public.wiki_document_verdicts AS
+ SELECT binding.wiki_id,
+ binding.tenant_id,
+ document.id AS document_id,
+ COALESCE(version.filename, document.title) AS filename,
+ CASE
+ WHEN (item.document_id IS NULL) THEN 'my_pages'::text
+ ELSE split_part(item.source_key, ':'::text, 2)
+ END AS source,
+ public.document_text_version_id(document.id, text.source_kind, text.source_id) AS version_id,
+ (octet_length(text.markdown))::bigint AS size_bytes,
+ text.updated_at AS decided_at,
+ public.source_rejection_reason(document.native_import_status, version.filename, version.representation_format, text.source_kind, version.media_type, text.status, (octet_length(text.markdown))::bigint, text.longest_line_bytes) AS reason
+ FROM ((((public.document_context_bindings binding
+ JOIN public.documents document ON (((document.id = binding.document_id) AND (document.tenant_id = binding.tenant_id) AND (document.status = 'active'::text))))
+ JOIN public.document_texts text ON ((text.document_id = document.id)))
+ LEFT JOIN public.document_versions version ON (((text.source_kind = 'file_version'::text) AND (version.id = text.source_id) AND (version.document_id = document.id))))
+ LEFT JOIN public.wiki_source_items item ON (((item.tenant_id = document.tenant_id) AND (item.document_id = document.id))))
+ WHERE ((binding.binding_kind = 'wiki_source'::text) AND (binding.status = 'active'::text) AND (COALESCE(document.native_import_status, 'completed'::text) = ANY (ARRAY['completed'::text, 'failed'::text])) AND (NOT (EXISTS ( SELECT 1
+ FROM public.document_context_bindings page
+ WHERE ((page.document_id = document.id) AND (page.tenant_id = document.tenant_id) AND (page.binding_kind = 'wiki_page'::text))))));
+
+-- +goose Down
+-- Merged sources stay merged and keyed by mailbox; only the view goes back.
+CREATE OR REPLACE VIEW public.wiki_document_verdicts AS
+ SELECT binding.wiki_id,
+ binding.tenant_id,
+ document.id AS document_id,
+ COALESCE(version.filename, document.title) AS filename,
+ CASE
+ WHEN (item.document_id IS NULL) THEN 'my_pages'::text
+ ELSE COALESCE(connection.provider, 'mail'::text)
+ END AS source,
+ public.document_text_version_id(document.id, text.source_kind, text.source_id) AS version_id,
+ (octet_length(text.markdown))::bigint AS size_bytes,
+ text.updated_at AS decided_at,
+ public.source_rejection_reason(document.native_import_status, version.filename, version.representation_format, text.source_kind, version.media_type, text.status, (octet_length(text.markdown))::bigint, text.longest_line_bytes) AS reason
+ FROM (((((public.document_context_bindings binding
+ JOIN public.documents document ON (((document.id = binding.document_id) AND (document.tenant_id = binding.tenant_id) AND (document.status = 'active'::text))))
+ JOIN public.document_texts text ON ((text.document_id = document.id)))
+ LEFT JOIN public.document_versions version ON (((text.source_kind = 'file_version'::text) AND (version.id = text.source_id) AND (version.document_id = document.id))))
+ LEFT JOIN public.wiki_source_items item ON (((item.tenant_id = document.tenant_id) AND (item.document_id = document.id))))
+ LEFT JOIN public.external_connections connection ON ((connection.id = split_part(item.source_key, ':'::text, 2))))
+ WHERE ((binding.binding_kind = 'wiki_source'::text) AND (binding.status = 'active'::text) AND (COALESCE(document.native_import_status, 'completed'::text) = ANY (ARRAY['completed'::text, 'failed'::text])) AND (NOT (EXISTS ( SELECT 1
+ FROM public.document_context_bindings page
+ WHERE ((page.document_id = document.id) AND (page.tenant_id = document.tenant_id) AND (page.binding_kind = 'wiki_page'::text))))));
diff --git a/apps/teamhub/tests/integration/external_source_fakes_test.go b/apps/teamhub/tests/integration/external_source_fakes_test.go
index 455076b6..4f1de099 100644
--- a/apps/teamhub/tests/integration/external_source_fakes_test.go
+++ b/apps/teamhub/tests/integration/external_source_fakes_test.go
@@ -257,7 +257,7 @@ func aliceAccountID(t *testing.T, ctx context.Context, pool *pgxpool.Pool) strin
func seedExternalConnection(t *testing.T, ctx context.Context, pool *pgxpool.Pool, id, accountID, provider, connectionStatus string) {
t.Helper()
- if _, err := pool.Exec(ctx, `INSERT INTO external_connections(id,account_id,provider,upstream_connection_id,status,identity_label,remote_principal_key) VALUES($1,$2,$3,$1||'-upstream',$4,$1,$1||'-principal')`, id, accountID, provider, connectionStatus); err != nil {
+ if _, err := pool.Exec(ctx, `INSERT INTO external_connections(id,account_id,provider,upstream_connection_id,status,identity_label,remote_principal_key) VALUES($1,$2,$3,$1||'-upstream',$4,$1,$3||':'||$1)`, id, accountID, provider, connectionStatus); err != nil {
t.Fatal(err)
}
}
diff --git a/apps/teamhub/tests/integration/key_mail_wiki_sources_by_mailbox_migration_test.go b/apps/teamhub/tests/integration/key_mail_wiki_sources_by_mailbox_migration_test.go
new file mode 100644
index 00000000..a0b63f26
--- /dev/null
+++ b/apps/teamhub/tests/integration/key_mail_wiki_sources_by_mailbox_migration_test.go
@@ -0,0 +1,119 @@
+//go:build integration_migration_history
+
+package integration_test
+
+import (
+ "context"
+ "os"
+ "testing"
+
+ "github.com/jackc/pgx/v5/pgxpool"
+ "github.com/pressly/goose/v3"
+)
+
+// Mail sources two Connections of one mailbox imported merge into one source
+// per message keyed by the mailbox. The source that stays is the one in the
+// Wiki, then the one written last; the others leave like trashed Documents
+// but keep their published rows, so the next refresh removes them.
+func TestKeyMailWikiSourcesByMailboxMergesReconnectedMailbox(t *testing.T) {
+ ctx := context.Background()
+ databaseURL := newEmptyDatabase(t, "mail_mailbox_key")
+ db := openMigrationTestDatabase(t, databaseURL)
+ provider, err := goose.NewProvider(goose.DialectPostgres, db, os.DirFS(teamHubMigrationDirectory(t)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := provider.UpTo(ctx, 874); err != nil {
+ t.Fatal(err)
+ }
+ insertUnifiedDocumentIdentityFixture(t, ctx, db)
+ pool, err := pgxpool.New(ctx, databaseURL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(pool.Close)
+ // m1 and m3 were imported by both Connections; m2 only by the first. The
+ // later copy of m3 left the Wiki, so the earlier one stays. orphan's
+ // Connection never learned its mailbox.
+ if _, err := pool.Exec(ctx, `
+ INSERT INTO external_connections(id,account_id,provider,upstream_connection_id,status,identity_label,remote_principal_key) VALUES
+ ('connection_before','account_document_a','gmail','upstream_before','revoked','[email protected]','gmail:[email protected]'),
+ ('connection_after','account_document_a','gmail','upstream_after','active','[email protected]','gmail:[email protected]'),
+ ('connection_unknown','account_document_a','gmail','upstream_unknown','failed',NULL,NULL);
+ INSERT INTO personal_wikis(id,tenant_id,owner_actor_id) VALUES('wiki_mail','tenant_document_a','actor_human_a');
+ CREATE TEMPORARY TABLE fixture(id text, connection_id text, message text, binding text, written timestamptz);
+ INSERT INTO fixture VALUES
+ ('m1_before','connection_before','message:1','active','2026-11-11 03:47'),
+ ('m1_after','connection_after','message:1','active','2026-11-11 03:59'),
+ ('m2_before','connection_before','message:2','active','2026-11-11 03:47'),
+ ('m3_before','connection_before','message:3','active','2026-11-11 03:47'),
+ ('m3_after','connection_after','message:3','suspended','2026-11-11 03:59'),
+ ('orphan','connection_unknown','message:9','active','2026-11-11 03:40');
+ INSERT INTO documents(id,tenant_id,title,format,owner_actor_id,owner_actor_kind,creator_actor_id,creator_actor_kind,status)
+ SELECT id,'tenant_document_a',id || '.md','markdown','actor_human_a','human','actor_human_a','human','active' FROM fixture;
+ INSERT INTO document_versions(id,tenant_id,document_id,version_number,filename,representation_format,media_type,
+ size_bytes,sha256,content_object_id,source,created_by_actor_id)
+ SELECT 'version_' || id,'tenant_document_a',id,1,id || '.md','markdown','text/markdown',5,repeat('a',64),
+ 'object_' || id,'ordinary_upload','actor_human_a' FROM fixture;
+ UPDATE documents SET current_version_id='version_' || id WHERE id IN (SELECT id FROM fixture);
+ INSERT INTO document_texts(document_id,tenant_id,source_kind,source_id,status,markdown,markdown_sha256,search_text)
+ SELECT id,'tenant_document_a','file_version','version_' || id,'ready','Hello',repeat('b',64),'Hello' FROM fixture
+ ON CONFLICT (document_id) DO UPDATE SET source_kind=EXCLUDED.source_kind,source_id=EXCLUDED.source_id,
+ status=EXCLUDED.status,markdown=EXCLUDED.markdown,markdown_sha256=EXCLUDED.markdown_sha256,search_text=EXCLUDED.search_text;
+ INSERT INTO document_context_bindings(id,tenant_id,document_id,binding_kind,wiki_id,status)
+ SELECT 'binding_' || id,'tenant_document_a',id,'wiki_source','wiki_mail',binding FROM fixture;
+ INSERT INTO wiki_source_items(tenant_id,owner_actor_id,source_key,content_sha256,document_id,document_version_id,created_at,updated_at)
+ SELECT 'tenant_document_a','actor_human_a','mail:' || connection_id || ':' || message,repeat('a',64),id,'version_' || id,written,written
+ FROM fixture;
+ INSERT INTO document_wiki_published_sources(wiki_id,tenant_id,document_id,document_version_id)
+ SELECT 'wiki_mail','tenant_document_a',id,'version_' || id FROM fixture WHERE id IN ('m1_before','m1_after');
+ INSERT INTO document_wiki_unsettled_sources(wiki_id,tenant_id,document_id,document_version_id,tries)
+ SELECT 'wiki_mail','tenant_document_a',id,'version_' || id,1 FROM fixture WHERE id IN ('m1_before','m1_after');
+ `); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := provider.Up(ctx); err != nil {
+ t.Fatal(err)
+ }
+
+ assertMemorySourceRows(t, pool, `SELECT source_key,document_id FROM wiki_source_items ORDER BY source_key`,
+ [][]any{
+ {"mail:gmail:[email protected]:message:1", "m1_after"},
+ {"mail:gmail:[email protected]:message:2", "m2_before"},
+ {"mail:gmail:[email protected]:message:3", "m3_before"},
+ })
+ assertMemorySourceRows(t, pool, `SELECT document.id,document.status,binding.status,binding.access_epoch,count.permission_count
+ FROM documents document
+ JOIN document_context_bindings binding ON binding.document_id=document.id
+ JOIN document_permission_counts count ON count.document_id=document.id
+ WHERE document.id IN ('m1_after','m1_before','m2_before','m3_after','m3_before','orphan') ORDER BY document.id`,
+ [][]any{
+ {"m1_after", "active", "active", int64(1), int64(0)},
+ {"m1_before", "trashed", "suspended", int64(2), int64(1)},
+ {"m2_before", "active", "active", int64(1), int64(0)},
+ {"m3_after", "trashed", "suspended", int64(1), int64(1)},
+ {"m3_before", "active", "active", int64(1), int64(0)},
+ {"orphan", "trashed", "suspended", int64(2), int64(1)},
+ })
+ assertMemorySourceRows(t, pool, `SELECT document_id,event_type,actor_id FROM document_events
+ WHERE document_id IN ('m1_after','m1_before','m2_before','m3_after','m3_before','orphan') ORDER BY document_id,sequence`,
+ [][]any{
+ {"m1_before", "document.access_invalidated", "actor_human_a"},
+ {"m1_before", "document.trashed", "actor_human_a"},
+ {"m1_before", "document.binding_updated", "actor_human_a"},
+ {"m3_after", "document.access_invalidated", "actor_human_a"},
+ {"m3_after", "document.trashed", "actor_human_a"},
+ {"orphan", "document.access_invalidated", "actor_human_a"},
+ {"orphan", "document.trashed", "actor_human_a"},
+ {"orphan", "document.binding_updated", "actor_human_a"},
+ })
+ // The removed copy stays published until a refresh removes it; its
+ // unsettled try count goes.
+ assertMemorySourceRows(t, pool, `SELECT document_id FROM document_wiki_published_sources ORDER BY document_id`,
+ [][]any{{"m1_after"}, {"m1_before"}})
+ assertMemorySourceRows(t, pool, `SELECT document_id FROM document_wiki_unsettled_sources ORDER BY document_id`,
+ [][]any{{"m1_after"}})
+ assertMemorySourceRows(t, pool, `SELECT source_id FROM wiki_current_sources ORDER BY source_id`,
+ [][]any{{"m1_after"}, {"m2_before"}, {"m3_before"}})
+ assertMemorySourceRows(t, pool, `SELECT DISTINCT source FROM wiki_document_verdicts`, [][]any{{"gmail"}})
+}
diff --git a/apps/teamhub/tests/integration/mail_connection_import_test.go b/apps/teamhub/tests/integration/mail_connection_import_test.go
index 4d176064..86f49fb3 100644
--- a/apps/teamhub/tests/integration/mail_connection_import_test.go
+++ b/apps/teamhub/tests/integration/mail_connection_import_test.go
@@ -104,6 +104,7 @@ func TestMailConnectionAutomaticallyImportsWikiWithoutProfile(t *testing.T) {
// Authorization goes through managed Composio; start from the job it queues.
connectionID := providerName + "_auto"
seedExternalConnection(t, ctx, pool, connectionID, "account_alice", providerName, "active")
+ mailbox := providerName + ":" + connectionID
tx, err := pool.Begin(ctx)
if err != nil {
t.Fatal(err)
@@ -120,7 +121,7 @@ func TestMailConnectionAutomaticallyImportsWikiWithoutProfile(t *testing.T) {
for time.Now().Before(deadline) {
var completed bool
var docs int
- _ = pool.QueryRow(ctx, `SELECT coalesce((SELECT mail_import_status='completed' FROM external_connections WHERE id=$1),false), (SELECT count(*) FROM wiki_source_items WHERE source_key LIKE 'mail:'||$1||':%')`, connectionID).Scan(&completed, &docs)
+ _ = pool.QueryRow(ctx, `SELECT coalesce((SELECT mail_import_status='completed' FROM external_connections WHERE id=$1),false), (SELECT count(*) FROM wiki_source_items WHERE source_key LIKE 'mail:'||$2||':%')`, connectionID, mailbox).Scan(&completed, &docs)
if completed && docs == 3000 {
finished = true
break
@@ -134,7 +135,7 @@ func TestMailConnectionAutomaticallyImportsWikiWithoutProfile(t *testing.T) {
}
var docs, snapshots int
var snapshot string
- if err = pool.QueryRow(ctx, `SELECT (SELECT count(*) FROM wiki_source_items WHERE source_key LIKE 'mail:'||$1||':%'), (SELECT count(*) FROM external_mail_import_documents WHERE connection_id=$1), (SELECT mail_import_status FROM external_connections WHERE id=$1)`, connectionID).Scan(&docs, &snapshots, &snapshot); err != nil {
+ if err = pool.QueryRow(ctx, `SELECT (SELECT count(*) FROM wiki_source_items WHERE source_key LIKE 'mail:'||$2||':%'), (SELECT count(*) FROM external_mail_import_documents WHERE connection_id=$1), (SELECT mail_import_status FROM external_connections WHERE id=$1)`, connectionID, mailbox).Scan(&docs, &snapshots, &snapshot); err != nil {
t.Fatal(err)
}
if docs != 3000 || snapshots != 3000 || snapshot != "completed" {
@@ -152,7 +153,7 @@ func TestMailConnectionAutomaticallyImportsWikiWithoutProfile(t *testing.T) {
}
// Automated mail reaches the Wiki.
var automatedWiki int
- if err = pool.QueryRow(ctx, `SELECT count(*) FROM wiki_source_items WHERE source_key=$1`, "mail:"+connectionID+":message:0").Scan(&automatedWiki); err != nil || automatedWiki != 1 {
+ if err = pool.QueryRow(ctx, `SELECT count(*) FROM wiki_source_items WHERE source_key=$1`, externalsource.MailWikiSourceKey(mailbox, "message:0")).Scan(&automatedWiki); err != nil || automatedWiki != 1 {
t.Fatalf("automated mail Wiki sources=%d err=%v", automatedWiki, err)
}
generator.mu.Lock()
diff --git a/apps/teamhub/tests/integration/mail_wiki_whitelist_test.go b/apps/teamhub/tests/integration/mail_wiki_whitelist_test.go
index fd1a742a..fc4aa135 100644
--- a/apps/teamhub/tests/integration/mail_wiki_whitelist_test.go
+++ b/apps/teamhub/tests/integration/mail_wiki_whitelist_test.go
@@ -124,13 +124,13 @@ func TestMailWhitelistAdmitsMailAndSyncsNightly(t *testing.T) {
t.Helper()
var sources int
if err := pool.QueryRow(ctx, `SELECT count(*) FROM wiki_source_items WHERE source_key=$1`,
- fmt.Sprintf("mail:%s:message:human-%d", connectionID, window)).Scan(&sources); err != nil || sources != 1 {
+ externalsource.MailWikiSourceKey("gmail:"+connectionID, fmt.Sprintf("message:human-%d", window))).Scan(&sources); err != nil || sources != 1 {
t.Fatalf("window %d admitted Wiki sources=%d err=%v", window, sources, err)
}
}
assertMail(1)
var firstVersion string
- const versionQuery = `SELECT document_version_id FROM wiki_source_items WHERE source_key='mail:gmail_whitelist:message:human-1'`
+ const versionQuery = `SELECT document_version_id FROM wiki_source_items WHERE source_key='mail:gmail:gmail_whitelist:message:human-1'`
if err = pool.QueryRow(ctx, versionQuery).Scan(&firstVersion); err != nil {
t.Fatal(err)
}
@@ -171,6 +171,107 @@ func TestMailWhitelistAdmitsMailAndSyncsNightly(t *testing.T) {
}
}
+// Reconnecting a mailbox reads it again under a new Connection; its messages
+// keep the Wiki sources the earlier Connection wrote instead of gaining a
+// second Document each.
+func TestReconnectedMailboxKeepsItsWikiSources(t *testing.T) {
+ allowParallelIntegrationTest(t)
+ ctx := t.Context()
+ databaseURL := newIntegrationDatabase(t)
+ pool, err := pgxpool.New(ctx, databaseURL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(pool.Close)
+ provider := &windowedMailProvider{fakeGmailProvider: &fakeGmailProvider{status: composio.ConnectionActive}}
+ cfg := config.ForTest(func(c *config.Config) {
+ c.DatabaseURL = databaseURL
+ c.SessionTTL = time.Hour
+ c.CookieName = "teamhub_session"
+ c.ArtifactStorageRoot = t.TempDir()
+ c.ArtifactMaxBytes = 2 << 20
+ })
+ newFakeComposio(t).configure(&cfg)
+ application, err := newIntegrationApp(ctx, cfg, withComposio(provider), starting(app.JobQueue))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(application.Close)
+
+ const mailbox = "gmail:[email protected]"
+ importMailbox := func(connectionID string) {
+ t.Helper()
+ if _, err := pool.Exec(ctx, `INSERT INTO external_connections(id,account_id,provider,upstream_connection_id,status,identity_label,remote_principal_key)
+ VALUES($1,'account_alice','gmail',$1||'-upstream','active','[email protected]',$2)`, connectionID, mailbox); err != nil {
+ t.Fatal(err)
+ }
+ tx, err := pool.Begin(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer tx.Rollback(ctx)
+ if err = jobs.InsertTx(ctx, tx, externalsource.MailConnectionArgs{AccountID: "account_alice", TenantID: acmeTenant, ConnectionID: connectionID}, nil); err != nil {
+ t.Fatal(err)
+ }
+ if err = tx.Commit(ctx); err != nil {
+ t.Fatal(err)
+ }
+ deadline := time.Now().Add(30 * time.Second)
+ for {
+ var completed bool
+ if err := pool.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM external_connections WHERE id=$1 AND mail_import_status='completed')`, connectionID).Scan(&completed); err != nil {
+ t.Fatal(err)
+ }
+ if completed {
+ return
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("the snapshot of %s did not complete", connectionID)
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+ }
+ sources := func() map[string][2]string {
+ t.Helper()
+ rows, err := pool.Query(ctx, `SELECT source_key,document_id,document_version_id FROM wiki_source_items WHERE tenant_id=$1`, acmeTenant)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer rows.Close()
+ found := make(map[string][2]string)
+ for rows.Next() {
+ var key, documentID, versionID string
+ if err := rows.Scan(&key, &documentID, &versionID); err != nil {
+ t.Fatal(err)
+ }
+ found[key] = [2]string{documentID, versionID}
+ }
+ if err := rows.Err(); err != nil {
+ t.Fatal(err)
+ }
+ return found
+ }
+ first := externalsource.MailWikiSourceKey(mailbox, "message:human-1")
+ importMailbox("gmail_before_reconnect")
+ before := sources()
+ if len(before) != 1 || before[first][0] == "" {
+ t.Fatalf("first Connection wrote Wiki sources %v, want only %s", before, first)
+ }
+ if _, err := pool.Exec(ctx, `UPDATE external_connections SET status='revoked' WHERE id='gmail_before_reconnect'`); err != nil {
+ t.Fatal(err)
+ }
+ // The second snapshot reads the first message again, unchanged, and a new one.
+ importMailbox("gmail_after_reconnect")
+ after := sources()
+ if len(after) != 2 || after[first] != before[first] || after[externalsource.MailWikiSourceKey(mailbox, "message:human-2")][0] == "" {
+ t.Fatalf("reconnected mailbox Wiki sources=%v, want %s kept at %v and message:human-2 added", after, first, before[first])
+ }
+ var documents int
+ if err := pool.QueryRow(ctx, `SELECT count(*) FROM documents WHERE tenant_id=$1 AND id LIKE 'document_onboarding_wiki_%'`, acmeTenant).Scan(&documents); err != nil || documents != 2 {
+ t.Fatalf("reconnected mailbox has %d mail Documents, want 2: %v", documents, err)
+ }
+}
+
// An overlap may read a published message twice without creating a nightly delta.
func TestNightlyWikiSkipsPublishedMailUntilItsVersionChanges(t *testing.T) {
allowParallelIntegrationTest(t)