Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(whatsapp): list members in the side panel, wait quietly to import (#8853)

Wolf Mermelsteind213e066e223
diff --git a/.sqlx/query-0a22c921baaa9749abad7122bcd254508e8b18eaf1fa6779e03160005a6e7302.json b/.sqlx/query-0a22c921baaa9749abad7122bcd254508e8b18eaf1fa6779e03160005a6e7302.json
new file mode 100644
index 0000000000..78a2ed6736
--- /dev/null
+++ b/.sqlx/query-0a22c921baaa9749abad7122bcd254508e8b18eaf1fa6779e03160005a6e7302.json
@@ -0,0 +1,108 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "WITH sources AS MATERIALIZED (\n SELECT array_append(ARRAY(SELECT team_id::text FROM team_user WHERE user_id = $1)\n || ARRAY(SELECT channel_id::text FROM comms_channel_participants WHERE user_id = $1 AND left_at IS NULL), $1) AS ids),\n candidates AS MATERIALIZED (\n SELECT $2::uuid AS id WHERE $2::uuid IS NOT NULL\n UNION\n SELECT ea.entity_id FROM entity_access ea, sources s\n WHERE $2::uuid IS NULL AND ea.entity_type = 'whatsapp_group' AND ea.source_id = ANY(s.ids)\n UNION\n SELECT rs.group_id FROM whatsapp_group_read_state rs WHERE $2::uuid IS NULL AND rs.user_id = $1)\n SELECT g.id,g.name,g.kind,g.user_id,g.group_jid,g.state,g.adopted_at,g.backfill_state,g.backfill_imported,\n (SELECT count(*) FROM (SELECT 1 FROM whatsapp_group_message m WHERE m.binding_id=g.id AND m.message_id IS NOT NULL\n AND m.deleted_at IS NULL AND m.origin<>'history' AND m.kind<>'system'\n AND NOT EXISTS(SELECT 1 FROM whatsapp_external_person p WHERE p.id=m.person_id AND p.user_id=$1)\n AND (r.message_id IS NULL OR (m.source_at,m.id)>(r.read_at,r.message_id)) LIMIT $3) unread) AS \"unread_count!\",\n (SELECT max(source_at) FROM whatsapp_group_message WHERE binding_id=g.id AND message_id IS NOT NULL) AS last_message_at,\n roster.metadata AS \"metadata?\",\n seen.community_jid AS \"community_jid?\",seen.community_announcements AS \"community_announcements?\",parent.name AS \"community_name?\"\n FROM candidates c JOIN whatsapp_group g ON g.id=c.id\n LEFT JOIN whatsapp_group_read_state r ON r.group_id=g.id AND r.user_id=$1\n LEFT JOIN whatsapp_linked_account a ON a.user_id=$1\n LEFT JOIN whatsapp_group_roster roster ON roster.account_id=a.id AND roster.group_jid=g.group_jid\n LEFT JOIN LATERAL (SELECT r.metadata->>'communityJid' AS community_jid,COALESCE((r.metadata->>'communityAnnouncements')::boolean,false) AS community_announcements\n FROM whatsapp_group_roster r JOIN whatsapp_group_membership m ON m.account_id=r.account_id\n WHERE m.binding_id=g.id AND m.consent_ended_at IS NULL AND r.group_jid=g.group_jid\n ORDER BY r.observed_at DESC LIMIT 1) seen ON true\n LEFT JOIN LATERAL (SELECT r.metadata->>'name' AS name\n FROM whatsapp_group_roster r JOIN whatsapp_group_membership m ON m.account_id=r.account_id\n WHERE m.binding_id=g.id AND m.consent_ended_at IS NULL AND r.group_jid=seen.community_jid\n ORDER BY r.observed_at DESC LIMIT 1) parent ON true\n -- On the candidate, not the chat: Postgres would otherwise check every chat.\n WHERE ($2::uuid IS NOT NULL OR whatsapp_group_can_view(c.id,$1))\n ORDER BY g.adopted_at DESC LIMIT 2000",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "kind",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "group_jid",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "state",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "adopted_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "backfill_state",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 8,
+ "name": "backfill_imported",
+ "type_info": "Int4"
+ },
+ {
+ "ordinal": 9,
+ "name": "unread_count!",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 10,
+ "name": "last_message_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 11,
+ "name": "metadata?",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 12,
+ "name": "community_jid?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 13,
+ "name": "community_announcements?",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 14,
+ "name": "community_name?",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Uuid",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ true,
+ false,
+ null,
+ null,
+ false,
+ null,
+ null,
+ null
+ ]
+ },
+ "hash": "0a22c921baaa9749abad7122bcd254508e8b18eaf1fa6779e03160005a6e7302"
+}
diff --git a/.sqlx/query-13a34fe816487cb7ec13b5988b6d4ca4d3280e12aaeba9f19063430bfa5155de.json b/.sqlx/query-13a34fe816487cb7ec13b5988b6d4ca4d3280e12aaeba9f19063430bfa5155de.json
new file mode 100644
index 0000000000..cf15ab7293
--- /dev/null
+++ b/.sqlx/query-13a34fe816487cb7ec13b5988b6d4ca4d3280e12aaeba9f19063430bfa5155de.json
@@ -0,0 +1,21 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "WITH input AS (\n SELECT * FROM UNNEST($2::text[], $3::text[], $4::text[], $5::timestamptz[], $6::bool[], $7::bool[], $8::jsonb[])\n AS i(chat_jid, kind, name, last_activity_at, archived, pinned, anchor))\n INSERT INTO whatsapp_chat AS c (account_id, chat_jid, kind, name, last_activity_at, archived, pinned, anchor)\n SELECT $1, i.chat_jid, i.kind, i.name, i.last_activity_at, COALESCE(i.archived, false), COALESCE(i.pinned, false), i.anchor\n FROM input i\n ON CONFLICT (account_id, chat_jid) DO UPDATE SET\n name = COALESCE(excluded.name, c.name),\n last_activity_at = GREATEST(c.last_activity_at, excluded.last_activity_at),\n archived = COALESCE((SELECT i.archived FROM input i WHERE i.chat_jid = excluded.chat_jid), c.archived),\n pinned = COALESCE((SELECT i.pinned FROM input i WHERE i.chat_jid = excluded.chat_jid), c.pinned),\n anchor = CASE WHEN excluded.anchor IS NOT NULL AND (c.anchor IS NULL\n OR (excluded.anchor->>'at')::timestamptz >= (c.anchor->>'at')::timestamptz)\n THEN excluded.anchor ELSE c.anchor END,\n updated_at = now()\n WHERE c.name IS DISTINCT FROM COALESCE(excluded.name, c.name)\n OR c.last_activity_at IS DISTINCT FROM GREATEST(c.last_activity_at, excluded.last_activity_at)\n OR c.archived IS DISTINCT FROM COALESCE((SELECT i.archived FROM input i WHERE i.chat_jid = excluded.chat_jid), c.archived)\n OR c.pinned IS DISTINCT FROM COALESCE((SELECT i.pinned FROM input i WHERE i.chat_jid = excluded.chat_jid), c.pinned)\n OR (excluded.anchor IS NOT NULL AND c.anchor IS DISTINCT FROM excluded.anchor AND (c.anchor IS NULL\n OR (excluded.anchor->>'at')::timestamptz >= (c.anchor->>'at')::timestamptz))",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "TextArray",
+ "TextArray",
+ "TextArray",
+ "TimestamptzArray",
+ "BoolArray",
+ "BoolArray",
+ "JsonbArray"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "13a34fe816487cb7ec13b5988b6d4ca4d3280e12aaeba9f19063430bfa5155de"
+}
diff --git a/.sqlx/query-b9164c293cd744ebcef950126e50e6a67f2fa87c5c2c296432dbe57e95655e0c.json b/.sqlx/query-2123bcd331ed8eef32d42179398b1b8a19abf2243e793918bbb89dbc6ae0433d.json
similarity index 67%
rename from .sqlx/query-b9164c293cd744ebcef950126e50e6a67f2fa87c5c2c296432dbe57e95655e0c.json
rename to .sqlx/query-2123bcd331ed8eef32d42179398b1b8a19abf2243e793918bbb89dbc6ae0433d.json
index 07e87327ea..ff2046113d 100644
--- a/.sqlx/query-b9164c293cd744ebcef950126e50e6a67f2fa87c5c2c296432dbe57e95655e0c.json
+++ b/.sqlx/query-2123bcd331ed8eef32d42179398b1b8a19abf2243e793918bbb89dbc6ae0433d.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "SELECT b.mime, b.filename, b.sha256, b.bytes FROM whatsapp_send s\n JOIN whatsapp_media_blob b ON b.document_id = (s.payload->'message'->>'upload_id')::uuid\n AND b.user_id = s.user_id AND b.group_id = s.group_id\n WHERE s.id = $1 AND s.account_id = $2 AND s.claimed_epoch = $3 AND s.state = 'sending'\n AND s.payload->'message'->>'type' = 'media'",
+ "query": "SELECT b.mime, b.filename, b.sha256, b.bytes FROM whatsapp_send s\n JOIN whatsapp_media_blob b ON b.document_id = (s.payload->'message'->>'uploadId')::uuid\n AND b.user_id = s.user_id AND b.group_id = s.group_id\n WHERE s.id = $1 AND s.account_id = $2 AND s.claimed_epoch = $3 AND s.state = 'sending'\n AND s.payload->'message'->>'type' = 'media'",
"describe": {
"columns": [
{
@@ -38,5 +38,5 @@
false
]
},
- "hash": "b9164c293cd744ebcef950126e50e6a67f2fa87c5c2c296432dbe57e95655e0c"
+ "hash": "2123bcd331ed8eef32d42179398b1b8a19abf2243e793918bbb89dbc6ae0433d"
}
diff --git a/.sqlx/query-29fc7af288a6b66d3d66897020882ffba0944cede06789d6d5d3f0f60d706b39.json b/.sqlx/query-29fc7af288a6b66d3d66897020882ffba0944cede06789d6d5d3f0f60d706b39.json
new file mode 100644
index 0000000000..0900ad3d0c
--- /dev/null
+++ b/.sqlx/query-29fc7af288a6b66d3d66897020882ffba0944cede06789d6d5d3f0f60d706b39.json
@@ -0,0 +1,19 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE whatsapp_chat c SET\n name = COALESCE(i.name, c.name),\n last_activity_at = GREATEST(c.last_activity_at, i.last_activity_at),\n archived = COALESCE(i.archived, c.archived),\n pinned = COALESCE(i.pinned, c.pinned),\n updated_at = now()\n FROM UNNEST($2::text[], $3::text[], $4::timestamptz[], $5::bool[], $6::bool[])\n AS i(chat_jid, name, last_activity_at, archived, pinned)\n WHERE c.account_id = $1 AND c.chat_jid = i.chat_jid\n AND (c.name IS DISTINCT FROM COALESCE(i.name, c.name)\n OR c.last_activity_at IS DISTINCT FROM GREATEST(c.last_activity_at, i.last_activity_at)\n OR c.archived IS DISTINCT FROM COALESCE(i.archived, c.archived)\n OR c.pinned IS DISTINCT FROM COALESCE(i.pinned, c.pinned))",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "TextArray",
+ "TextArray",
+ "TimestamptzArray",
+ "BoolArray",
+ "BoolArray"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "29fc7af288a6b66d3d66897020882ffba0944cede06789d6d5d3f0f60d706b39"
+}
diff --git a/.sqlx/query-24e02b9f9df426d070d8f52a6a167e94f381ab8457c515c42287830741b73c7c.json b/.sqlx/query-2e1a6ae6a9d83b22abf9c8814ba71b454fe3d218b9229c5da4c74794b7c04e45.json
similarity index 82%
rename from .sqlx/query-24e02b9f9df426d070d8f52a6a167e94f381ab8457c515c42287830741b73c7c.json
rename to .sqlx/query-2e1a6ae6a9d83b22abf9c8814ba71b454fe3d218b9229c5da4c74794b7c04e45.json
index 8078d0dd53..1cda427e73 100644
--- a/.sqlx/query-24e02b9f9df426d070d8f52a6a167e94f381ab8457c515c42287830741b73c7c.json
+++ b/.sqlx/query-2e1a6ae6a9d83b22abf9c8814ba71b454fe3d218b9229c5da4c74794b7c04e45.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "SELECT id, backfill_imported, backfill_cursor, adopted_at FROM whatsapp_group\n WHERE user_id = $1 AND group_jid = $2 AND state = 'active'\n AND backfill_state IN ('pending', 'running', 'waiting_for_phone')\n ORDER BY id FOR UPDATE",
+ "query": "SELECT id, backfill_imported, backfill_cursor, adopted_at FROM whatsapp_group\n WHERE user_id = $1 AND group_jid = $2 AND state = 'active'\n AND backfill_state IN ('waiting_for_message', 'pending', 'running', 'waiting_for_phone')\n ORDER BY id FOR UPDATE",
"describe": {
"columns": [
{
@@ -37,5 +37,5 @@
false
]
},
- "hash": "24e02b9f9df426d070d8f52a6a167e94f381ab8457c515c42287830741b73c7c"
+ "hash": "2e1a6ae6a9d83b22abf9c8814ba71b454fe3d218b9229c5da4c74794b7c04e45"
}
diff --git a/.sqlx/query-4432b2af358f8226cb247012f4a4b4064d3d386c1f9d0b5509bad9272e1821e3.json b/.sqlx/query-3645301ee2ac07d6aa7aa2ecdc6b7f7c907e47bdea7cdce704331ad543ef03f1.json
similarity index 78%
rename from .sqlx/query-4432b2af358f8226cb247012f4a4b4064d3d386c1f9d0b5509bad9272e1821e3.json
rename to .sqlx/query-3645301ee2ac07d6aa7aa2ecdc6b7f7c907e47bdea7cdce704331ad543ef03f1.json
index 659039d712..e9cd98c805 100644
--- a/.sqlx/query-4432b2af358f8226cb247012f4a4b4064d3d386c1f9d0b5509bad9272e1821e3.json
+++ b/.sqlx/query-3645301ee2ac07d6aa7aa2ecdc6b7f7c907e47bdea7cdce704331ad543ef03f1.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "UPDATE whatsapp_send s SET state = 'sending', claimed_epoch = $2, updated_at = now()\n FROM whatsapp_group b\n WHERE s.id IN (\n SELECT id FROM whatsapp_send WHERE account_id = $1 AND generation = $3 AND state = 'pending'\n ORDER BY group_id, group_sequence LIMIT $4 FOR UPDATE SKIP LOCKED)\n AND b.id = s.group_id\n RETURNING s.id, s.group_id AS binding_id, s.group_sequence, s.payload, s.traceparent, b.group_jid,\n (SELECT r.metadata FROM whatsapp_group_roster r WHERE r.account_id = s.account_id AND r.group_jid = b.group_jid) AS roster",
+ "query": "UPDATE whatsapp_send s SET state = 'sending', claimed_epoch = $2, updated_at = now()\n FROM whatsapp_group b\n WHERE s.id IN (\n SELECT id FROM whatsapp_send WHERE account_id = $1 AND generation = $3 AND state = 'pending'\n ORDER BY group_id, group_sequence LIMIT $4 FOR UPDATE SKIP LOCKED)\n AND b.id = s.group_id\n RETURNING s.id, s.group_id, s.group_sequence, s.payload, s.traceparent, b.group_jid,\n (SELECT r.metadata FROM whatsapp_group_roster r WHERE r.account_id = s.account_id AND r.group_jid = b.group_jid) AS roster",
"describe": {
"columns": [
{
@@ -10,7 +10,7 @@
},
{
"ordinal": 1,
- "name": "binding_id",
+ "name": "group_id",
"type_info": "Uuid"
},
{
@@ -57,5 +57,5 @@
null
]
},
- "hash": "4432b2af358f8226cb247012f4a4b4064d3d386c1f9d0b5509bad9272e1821e3"
+ "hash": "3645301ee2ac07d6aa7aa2ecdc6b7f7c907e47bdea7cdce704331ad543ef03f1"
}
diff --git a/.sqlx/query-42e4e3d706b23957b8996fb0202749784b8066b2ce206607e43344cf725743ef.json b/.sqlx/query-42e4e3d706b23957b8996fb0202749784b8066b2ce206607e43344cf725743ef.json
deleted file mode 100644
index 515007b198..0000000000
--- a/.sqlx/query-42e4e3d706b23957b8996fb0202749784b8066b2ce206607e43344cf725743ef.json
+++ /dev/null
@@ -1,88 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "SELECT g.id,g.name,g.kind,g.user_id,g.group_jid,g.state,g.adopted_at,g.backfill_state,g.backfill_imported,\n (SELECT count(*) FROM whatsapp_group_message m WHERE m.binding_id=g.id AND m.message_id IS NOT NULL\n AND m.deleted_at IS NULL AND m.origin<>'history' AND m.kind<>'system'\n AND NOT EXISTS(SELECT 1 FROM whatsapp_external_person p WHERE p.id=m.person_id AND p.user_id=$1)\n AND (r.message_id IS NULL OR (m.source_at,m.id)>(r.read_at,r.message_id))) AS \"unread_count!\",\n (SELECT max(source_at) FROM whatsapp_group_message WHERE binding_id=g.id AND message_id IS NOT NULL) AS last_message_at,\n roster.metadata AS \"metadata?\"\n FROM whatsapp_group g\n LEFT JOIN whatsapp_group_read_state r ON r.group_id=g.id AND r.user_id=$1\n LEFT JOIN whatsapp_linked_account a ON a.user_id=$1\n LEFT JOIN whatsapp_group_roster roster ON roster.account_id=a.id AND roster.group_jid=g.group_jid\n WHERE whatsapp_group_can_view(g.id,$1)\n AND (r.user_id IS NOT NULL OR EXISTS (SELECT 1 FROM entity_access ea\n WHERE ea.entity_id=g.id AND ea.entity_type='whatsapp_group'\n AND (ea.source_id=$1 OR ea.source_id IN (SELECT team_id::text FROM team_user WHERE user_id=$1)\n OR ea.source_id IN (SELECT channel_id::text FROM comms_channel_participants WHERE user_id=$1 AND left_at IS NULL))))\n ORDER BY g.adopted_at DESC LIMIT 2000",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "id",
- "type_info": "Uuid"
- },
- {
- "ordinal": 1,
- "name": "name",
- "type_info": "Text"
- },
- {
- "ordinal": 2,
- "name": "kind",
- "type_info": "Text"
- },
- {
- "ordinal": 3,
- "name": "user_id",
- "type_info": "Text"
- },
- {
- "ordinal": 4,
- "name": "group_jid",
- "type_info": "Text"
- },
- {
- "ordinal": 5,
- "name": "state",
- "type_info": "Text"
- },
- {
- "ordinal": 6,
- "name": "adopted_at",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 7,
- "name": "backfill_state",
- "type_info": "Text"
- },
- {
- "ordinal": 8,
- "name": "backfill_imported",
- "type_info": "Int4"
- },
- {
- "ordinal": 9,
- "name": "unread_count!",
- "type_info": "Int8"
- },
- {
- "ordinal": 10,
- "name": "last_message_at",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 11,
- "name": "metadata?",
- "type_info": "Jsonb"
- }
- ],
- "parameters": {
- "Left": [
- "Text"
- ]
- },
- "nullable": [
- false,
- false,
- false,
- false,
- false,
- false,
- false,
- true,
- false,
- null,
- null,
- false
- ]
- },
- "hash": "42e4e3d706b23957b8996fb0202749784b8066b2ce206607e43344cf725743ef"
-}
diff --git a/.sqlx/query-4ba49775a375313a3abb8b5d80f056cac0ef170e2dd3ba20b47c4adb746b6d13.json b/.sqlx/query-4ba49775a375313a3abb8b5d80f056cac0ef170e2dd3ba20b47c4adb746b6d13.json
new file mode 100644
index 0000000000..4e85baa0de
--- /dev/null
+++ b/.sqlx/query-4ba49775a375313a3abb8b5d80f056cac0ef170e2dd3ba20b47c4adb746b6d13.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "DELETE FROM whatsapp_group_roster WHERE account_id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "4ba49775a375313a3abb8b5d80f056cac0ef170e2dd3ba20b47c4adb746b6d13"
+}
diff --git a/.sqlx/query-8df4815d5f9c954b46e8fd51674eb0b1ec04c6aff4fff1e24ef92713fdba9147.json b/.sqlx/query-4f38f67e58b2a59dd551ecca8d2b932dbce732e7ff74c33170c7cc771781b095.json
similarity index 89%
rename from .sqlx/query-8df4815d5f9c954b46e8fd51674eb0b1ec04c6aff4fff1e24ef92713fdba9147.json
rename to .sqlx/query-4f38f67e58b2a59dd551ecca8d2b932dbce732e7ff74c33170c7cc771781b095.json
index 5fc3cbdbdb..7ff02f07af 100644
--- a/.sqlx/query-8df4815d5f9c954b46e8fd51674eb0b1ec04c6aff4fff1e24ef92713fdba9147.json
+++ b/.sqlx/query-4f38f67e58b2a59dd551ecca8d2b932dbce732e7ff74c33170c7cc771781b095.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "UPDATE whatsapp_group_attachment a SET retry_at = now() + interval '5 minutes'\n FROM whatsapp_media_blob blob\n WHERE (a.binding_id, a.person_id, a.source_id, a.ordinal) IN (\n SELECT binding_id, person_id, source_id, ordinal FROM whatsapp_group_attachment\n WHERE state = 'downloaded' AND retry_at <= now()\n ORDER BY retry_at LIMIT $1 FOR UPDATE SKIP LOCKED)\n AND blob.document_id = a.document_id\n RETURNING a.binding_id, a.person_id, a.source_id, a.ordinal, a.document_id, a.attempts,\n blob.group_id, blob.user_id, blob.filename, blob.mime, blob.sha256, blob.bytes",
+ "query": "UPDATE whatsapp_group_attachment a SET retry_at = now() + interval '5 minutes'\n FROM whatsapp_media_blob blob\n WHERE (a.binding_id, a.person_id, a.source_id, a.ordinal) IN (\n SELECT binding_id, person_id, source_id, ordinal FROM whatsapp_group_attachment\n WHERE state = 'downloaded' AND retry_at <= now()\n ORDER BY retry_at LIMIT $1 FOR UPDATE SKIP LOCKED)\n AND blob.document_id = a.document_id\n RETURNING a.binding_id, a.person_id, a.source_id, a.ordinal, a.document_id, a.attempts,\n blob.group_id, blob.user_id, blob.filename, blob.mime, blob.sha256",
"describe": {
"columns": [
{
@@ -57,11 +57,6 @@
"ordinal": 10,
"name": "sha256",
"type_info": "Bytea"
- },
- {
- "ordinal": 11,
- "name": "bytes",
- "type_info": "Bytea"
}
],
"parameters": {
@@ -80,9 +75,8 @@
false,
false,
false,
- false,
false
]
},
- "hash": "8df4815d5f9c954b46e8fd51674eb0b1ec04c6aff4fff1e24ef92713fdba9147"
+ "hash": "4f38f67e58b2a59dd551ecca8d2b932dbce732e7ff74c33170c7cc771781b095"
}
diff --git a/.sqlx/query-535bd0ee91b3d610a7efc2b237706dceaba35c74297979f9c628d02c7f6ec7f6.json b/.sqlx/query-535bd0ee91b3d610a7efc2b237706dceaba35c74297979f9c628d02c7f6ec7f6.json
new file mode 100644
index 0000000000..6aeda3396a
--- /dev/null
+++ b/.sqlx/query-535bd0ee91b3d610a7efc2b237706dceaba35c74297979f9c628d02c7f6ec7f6.json
@@ -0,0 +1,66 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT g.id, g.group_jid, g.backfill_state AS \"state!\", g.backfill_imported, g.backfill_cursor,\n g.adopted_at, g.backfill_requested_at, COALESCE(c.anchor, stored.anchor) AS \"anchor?\"\n FROM whatsapp_group g\n LEFT JOIN whatsapp_chat c ON c.account_id = $1 AND c.chat_jid = g.group_jid\n LEFT JOIN LATERAL (\n SELECT jsonb_build_object(\n 'id', m.source_id,\n 'at', m.source_at,\n 'fromMe', EXISTS (SELECT 1 FROM whatsapp_identity_alias a\n WHERE a.binding_id = m.binding_id AND a.person_id = m.person_id AND a.jid = $3),\n 'senderJid', (SELECT a.jid FROM whatsapp_identity_alias a\n WHERE a.binding_id = m.binding_id AND a.person_id = m.person_id\n ORDER BY a.jid LIKE '%@lid' DESC, a.jid LIMIT 1)) AS anchor\n FROM whatsapp_group_message m JOIN whatsapp_group other ON other.id = m.binding_id\n WHERE c.anchor IS NULL AND other.group_jid = g.group_jid\n AND m.kind = 'message' AND m.message_id IS NOT NULL\n AND (m.binding_id = g.id OR EXISTS (SELECT 1 FROM whatsapp_message_observation o\n WHERE o.binding_id = m.binding_id AND o.person_id = m.person_id\n AND o.source_id = m.source_id AND o.account_id = $1))\n ORDER BY m.source_at DESC, m.id DESC LIMIT 1\n ) stored ON true\n WHERE g.user_id = $2 AND g.state = 'active'\n AND g.backfill_state IN ('waiting_for_message', 'pending', 'running', 'waiting_for_phone')\n ORDER BY g.adopted_at, g.id LIMIT 20",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "group_jid",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "state!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "backfill_imported",
+ "type_info": "Int4"
+ },
+ {
+ "ordinal": 4,
+ "name": "backfill_cursor",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 5,
+ "name": "adopted_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "backfill_requested_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "anchor?",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ true,
+ false,
+ true,
+ false,
+ true,
+ null
+ ]
+ },
+ "hash": "535bd0ee91b3d610a7efc2b237706dceaba35c74297979f9c628d02c7f6ec7f6"
+}
diff --git a/.sqlx/query-586fcb55e4185e14b8d01253cc46500600aaca8ca180e274eb639c5feee19229.json b/.sqlx/query-586fcb55e4185e14b8d01253cc46500600aaca8ca180e274eb639c5feee19229.json
deleted file mode 100644
index 9bb1ef4eb4..0000000000
--- a/.sqlx/query-586fcb55e4185e14b8d01253cc46500600aaca8ca180e274eb639c5feee19229.json
+++ /dev/null
@@ -1,30 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "SELECT mime, filename FROM whatsapp_media_blob b\n WHERE document_id = $1 AND group_id = $2 AND user_id = $3\n AND NOT EXISTS (SELECT 1 FROM whatsapp_group_attachment a WHERE a.document_id = b.document_id)",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "mime",
- "type_info": "Text"
- },
- {
- "ordinal": 1,
- "name": "filename",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "Uuid",
- "Text"
- ]
- },
- "nullable": [
- false,
- false
- ]
- },
- "hash": "586fcb55e4185e14b8d01253cc46500600aaca8ca180e274eb639c5feee19229"
-}
diff --git a/.sqlx/query-58ee195b55c5eacea7a439824ec28e3abfc96865e166e7944fa4cc62665bf1d8.json b/.sqlx/query-58ee195b55c5eacea7a439824ec28e3abfc96865e166e7944fa4cc62665bf1d8.json
new file mode 100644
index 0000000000..dc9632a6d1
--- /dev/null
+++ b/.sqlx/query-58ee195b55c5eacea7a439824ec28e3abfc96865e166e7944fa4cc62665bf1d8.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE whatsapp_pairing SET state = $2, consumed_at = clock_timestamp(), qr_code = NULL, pair_code = NULL, passkey_challenge = NULL, passkey_response = NULL, updated_at = now() WHERE id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "58ee195b55c5eacea7a439824ec28e3abfc96865e166e7944fa4cc62665bf1d8"
+}
diff --git a/.sqlx/query-6346d7b868ab315c5c1c2a2bb0c5b344671608e00001e465f56cf37be096cc8d.json b/.sqlx/query-6346d7b868ab315c5c1c2a2bb0c5b344671608e00001e465f56cf37be096cc8d.json
deleted file mode 100644
index 41d3aa4f40..0000000000
--- a/.sqlx/query-6346d7b868ab315c5c1c2a2bb0c5b344671608e00001e465f56cf37be096cc8d.json
+++ /dev/null
@@ -1,65 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "SELECT g.id,g.name,g.kind,g.user_id,g.backfill_state,g.backfill_imported,\n (SELECT count(*) FROM whatsapp_group_message m WHERE m.binding_id = g.id AND m.message_id IS NOT NULL\n AND m.deleted_at IS NULL AND m.origin <> 'history' AND m.kind <> 'system'\n AND NOT EXISTS (SELECT 1 FROM whatsapp_external_person p WHERE p.id = m.person_id AND p.user_id = $2)\n AND (r.message_id IS NULL OR (m.source_at,m.id) > (r.read_at,r.message_id))) AS \"unread_count!\",\n (SELECT max(source_at) FROM whatsapp_group_message WHERE binding_id = g.id AND message_id IS NOT NULL) AS last_message_at\n FROM whatsapp_group g LEFT JOIN whatsapp_group_read_state r ON r.group_id = g.id AND r.user_id = $2\n WHERE g.id = $1",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "id",
- "type_info": "Uuid"
- },
- {
- "ordinal": 1,
- "name": "name",
- "type_info": "Text"
- },
- {
- "ordinal": 2,
- "name": "kind",
- "type_info": "Text"
- },
- {
- "ordinal": 3,
- "name": "user_id",
- "type_info": "Text"
- },
- {
- "ordinal": 4,
- "name": "backfill_state",
- "type_info": "Text"
- },
- {
- "ordinal": 5,
- "name": "backfill_imported",
- "type_info": "Int4"
- },
- {
- "ordinal": 6,
- "name": "unread_count!",
- "type_info": "Int8"
- },
- {
- "ordinal": 7,
- "name": "last_message_at",
- "type_info": "Timestamptz"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "Text"
- ]
- },
- "nullable": [
- false,
- false,
- false,
- false,
- true,
- false,
- null,
- null
- ]
- },
- "hash": "6346d7b868ab315c5c1c2a2bb0c5b344671608e00001e465f56cf37be096cc8d"
-}
diff --git a/.sqlx/query-6e30f2660e2a2532a2fca9782b10e0a4695062e13992545fb920cdb6d7520e74.json b/.sqlx/query-6e30f2660e2a2532a2fca9782b10e0a4695062e13992545fb920cdb6d7520e74.json
new file mode 100644
index 0000000000..594f9c4715
--- /dev/null
+++ b/.sqlx/query-6e30f2660e2a2532a2fca9782b10e0a4695062e13992545fb920cdb6d7520e74.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT bytes FROM whatsapp_media_blob WHERE document_id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "bytes",
+ "type_info": "Bytea"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "6e30f2660e2a2532a2fca9782b10e0a4695062e13992545fb920cdb6d7520e74"
+}
diff --git a/.sqlx/query-7b0ddfbdc46a5fcac81157960c25470b8b5e69f69f8461e89fa40332dde9e0e5.json b/.sqlx/query-7b0ddfbdc46a5fcac81157960c25470b8b5e69f69f8461e89fa40332dde9e0e5.json
new file mode 100644
index 0000000000..ea7836b682
--- /dev/null
+++ b/.sqlx/query-7b0ddfbdc46a5fcac81157960c25470b8b5e69f69f8461e89fa40332dde9e0e5.json
@@ -0,0 +1,12 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "DELETE FROM whatsapp_pairing WHERE consumed_at < now() - interval '1 day'",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": []
+ },
+ "hash": "7b0ddfbdc46a5fcac81157960c25470b8b5e69f69f8461e89fa40332dde9e0e5"
+}
diff --git a/.sqlx/query-826decd9d2670f80a8521605dd231456cfa914d36a64de15ce9b11d1961a7c4f.json b/.sqlx/query-826decd9d2670f80a8521605dd231456cfa914d36a64de15ce9b11d1961a7c4f.json
deleted file mode 100644
index e649f850ce..0000000000
--- a/.sqlx/query-826decd9d2670f80a8521605dd231456cfa914d36a64de15ce9b11d1961a7c4f.json
+++ /dev/null
@@ -1,57 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "INSERT INTO whatsapp_group (id, group_jid, kind, name, user_id, state, share_permission_id, backfill_state) VALUES ($1,$2,$3,$4,$5,'active',$6,'pending') RETURNING id, group_jid, kind, user_id, state, adopted_at",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "id",
- "type_info": "Uuid"
- },
- {
- "ordinal": 1,
- "name": "group_jid",
- "type_info": "Text"
- },
- {
- "ordinal": 2,
- "name": "kind",
- "type_info": "Text"
- },
- {
- "ordinal": 3,
- "name": "user_id",
- "type_info": "Text"
- },
- {
- "ordinal": 4,
- "name": "state",
- "type_info": "Text"
- },
- {
- "ordinal": 5,
- "name": "adopted_at",
- "type_info": "Timestamptz"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "Text",
- "Text",
- "Text",
- "Text",
- "Text"
- ]
- },
- "nullable": [
- false,
- false,
- false,
- false,
- false,
- false
- ]
- },
- "hash": "826decd9d2670f80a8521605dd231456cfa914d36a64de15ce9b11d1961a7c4f"
-}
diff --git a/.sqlx/query-8bb6d85211c1d34d611ec5df4d83b3958e149be1323dc623a1a795014e6b29ce.json b/.sqlx/query-8bb6d85211c1d34d611ec5df4d83b3958e149be1323dc623a1a795014e6b29ce.json
new file mode 100644
index 0000000000..7cd69afe34
--- /dev/null
+++ b/.sqlx/query-8bb6d85211c1d34d611ec5df4d83b3958e149be1323dc623a1a795014e6b29ce.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "DELETE FROM whatsapp_chat WHERE account_id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "8bb6d85211c1d34d611ec5df4d83b3958e149be1323dc623a1a795014e6b29ce"
+}
diff --git a/.sqlx/query-979407c035898747bf4b3962791f0aae875d2c708fe650d1f60df0c9e6c4b0d4.json b/.sqlx/query-979407c035898747bf4b3962791f0aae875d2c708fe650d1f60df0c9e6c4b0d4.json
new file mode 100644
index 0000000000..e6cdb8727d
--- /dev/null
+++ b/.sqlx/query-979407c035898747bf4b3962791f0aae875d2c708fe650d1f60df0c9e6c4b0d4.json
@@ -0,0 +1,24 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT mime FROM whatsapp_media_blob b\n WHERE document_id = $1 AND group_id = $2 AND user_id = $3\n AND NOT EXISTS (SELECT 1 FROM whatsapp_group_attachment a WHERE a.document_id = b.document_id)",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "mime",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "979407c035898747bf4b3962791f0aae875d2c708fe650d1f60df0c9e6c4b0d4"
+}
diff --git a/.sqlx/query-979a7bc09d7f983885860213022cbd0050f8901ea7c9542943fd8ae87521d7ec.json b/.sqlx/query-979a7bc09d7f983885860213022cbd0050f8901ea7c9542943fd8ae87521d7ec.json
new file mode 100644
index 0000000000..d1e9ca985a
--- /dev/null
+++ b/.sqlx/query-979a7bc09d7f983885860213022cbd0050f8901ea7c9542943fd8ae87521d7ec.json
@@ -0,0 +1,25 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE whatsapp_group b SET next_sequence = next_sequence + 1\n WHERE b.id = $1 AND b.state = 'active'\n AND EXISTS (\n SELECT 1 FROM whatsapp_linked_account a JOIN whatsapp_group_membership m ON m.account_id = a.id\n WHERE a.id = $2 AND a.user_id = $3 AND a.state = 'connected' AND a.generation = $4\n AND m.binding_id = b.id AND m.generation = a.generation AND m.consent_ended_at IS NULL\n AND m.remote_member AND m.can_post AND m.reconciled)\n AND whatsapp_group_can_view(b.id, $3)\n RETURNING next_sequence",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "next_sequence",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Text",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "979a7bc09d7f983885860213022cbd0050f8901ea7c9542943fd8ae87521d7ec"
+}
diff --git a/.sqlx/query-af68a9210da158ba404123454b2d00898b4e5794fc60d092522943c47b6fb6dd.json b/.sqlx/query-a7e25f75e554f8bab386b3484e722ecc0dffbf16fe1376a187aed763e83b8f9a.json
similarity index 68%
rename from .sqlx/query-af68a9210da158ba404123454b2d00898b4e5794fc60d092522943c47b6fb6dd.json
rename to .sqlx/query-a7e25f75e554f8bab386b3484e722ecc0dffbf16fe1376a187aed763e83b8f9a.json
index e6bfff6ddb..f19cd034a1 100644
--- a/.sqlx/query-af68a9210da158ba404123454b2d00898b4e5794fc60d092522943c47b6fb6dd.json
+++ b/.sqlx/query-a7e25f75e554f8bab386b3484e722ecc0dffbf16fe1376a187aed763e83b8f9a.json
@@ -1,11 +1,11 @@
{
"db_name": "PostgreSQL",
- "query": "SELECT s.group_id AS binding_id, s.payload, s.allocated_source_id, s.state, s.created_at\n FROM whatsapp_send s WHERE s.id = $1 AND s.account_id = $2 AND s.dispatch_started_at IS NOT NULL FOR UPDATE",
+ "query": "SELECT s.group_id, s.payload, s.allocated_source_id, s.state, s.created_at\n FROM whatsapp_send s WHERE s.id = $1 AND s.account_id = $2 AND s.dispatch_started_at IS NOT NULL FOR UPDATE",
"describe": {
"columns": [
{
"ordinal": 0,
- "name": "binding_id",
+ "name": "group_id",
"type_info": "Uuid"
},
{
@@ -43,5 +43,5 @@
false
]
},
- "hash": "af68a9210da158ba404123454b2d00898b4e5794fc60d092522943c47b6fb6dd"
+ "hash": "a7e25f75e554f8bab386b3484e722ecc0dffbf16fe1376a187aed763e83b8f9a"
}
diff --git a/.sqlx/query-b786cd62597579e1a8d765131145b54e10ba43192282c30371864597614ba9aa.json b/.sqlx/query-b786cd62597579e1a8d765131145b54e10ba43192282c30371864597614ba9aa.json
deleted file mode 100644
index 3ca9eb494e..0000000000
--- a/.sqlx/query-b786cd62597579e1a8d765131145b54e10ba43192282c30371864597614ba9aa.json
+++ /dev/null
@@ -1,24 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "UPDATE whatsapp_group SET name = $3\n WHERE user_id = $1 AND group_jid = $2 AND kind = 'direct' AND state = 'active' AND name <> $3\n RETURNING id",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "id",
- "type_info": "Uuid"
- }
- ],
- "parameters": {
- "Left": [
- "Text",
- "Text",
- "Text"
- ]
- },
- "nullable": [
- false
- ]
- },
- "hash": "b786cd62597579e1a8d765131145b54e10ba43192282c30371864597614ba9aa"
-}
diff --git a/.sqlx/query-c412870d6e6e8be6878bfe1bd793ce3292bc74417b2f18890c481265f4f2a1d6.json b/.sqlx/query-c412870d6e6e8be6878bfe1bd793ce3292bc74417b2f18890c481265f4f2a1d6.json
deleted file mode 100644
index 872480ff79..0000000000
--- a/.sqlx/query-c412870d6e6e8be6878bfe1bd793ce3292bc74417b2f18890c481265f4f2a1d6.json
+++ /dev/null
@@ -1,65 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "SELECT g.id, g.group_jid, g.backfill_state AS \"state!\", g.backfill_imported, g.backfill_cursor,\n g.adopted_at, g.backfill_requested_at, c.anchor AS \"anchor?\"\n FROM whatsapp_group g\n LEFT JOIN whatsapp_chat c ON c.account_id = $1 AND c.chat_jid = g.group_jid\n WHERE g.user_id = $2 AND g.state = 'active'\n AND g.backfill_state IN ('pending', 'running', 'waiting_for_phone')\n ORDER BY g.adopted_at, g.id LIMIT 20",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "id",
- "type_info": "Uuid"
- },
- {
- "ordinal": 1,
- "name": "group_jid",
- "type_info": "Text"
- },
- {
- "ordinal": 2,
- "name": "state!",
- "type_info": "Text"
- },
- {
- "ordinal": 3,
- "name": "backfill_imported",
- "type_info": "Int4"
- },
- {
- "ordinal": 4,
- "name": "backfill_cursor",
- "type_info": "Jsonb"
- },
- {
- "ordinal": 5,
- "name": "adopted_at",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 6,
- "name": "backfill_requested_at",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 7,
- "name": "anchor?",
- "type_info": "Jsonb"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "Text"
- ]
- },
- "nullable": [
- false,
- false,
- true,
- false,
- true,
- false,
- true,
- true
- ]
- },
- "hash": "c412870d6e6e8be6878bfe1bd793ce3292bc74417b2f18890c481265f4f2a1d6"
-}
diff --git a/.sqlx/query-ca90bf3789dc312e956c7153adab75c8a048dc949b0a59baf4e002f97b36643a.json b/.sqlx/query-ca90bf3789dc312e956c7153adab75c8a048dc949b0a59baf4e002f97b36643a.json
deleted file mode 100644
index 52690b2f2a..0000000000
--- a/.sqlx/query-ca90bf3789dc312e956c7153adab75c8a048dc949b0a59baf4e002f97b36643a.json
+++ /dev/null
@@ -1,21 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "INSERT INTO whatsapp_chat AS c (account_id, chat_jid, kind, name, last_activity_at, archived, pinned, anchor)\n VALUES ($1, $2, $3, $4, $5, COALESCE($6, false), COALESCE($7, false), $8)\n ON CONFLICT (account_id, chat_jid) DO UPDATE SET\n name = COALESCE(excluded.name, c.name),\n last_activity_at = GREATEST(c.last_activity_at, excluded.last_activity_at),\n archived = COALESCE($6, c.archived),\n pinned = COALESCE($7, c.pinned),\n anchor = CASE WHEN excluded.anchor IS NOT NULL AND (c.anchor IS NULL\n OR (excluded.anchor->>'at')::timestamptz >= (c.anchor->>'at')::timestamptz)\n THEN excluded.anchor ELSE c.anchor END,\n updated_at = now()\n WHERE c.name IS DISTINCT FROM COALESCE(excluded.name, c.name)\n OR c.last_activity_at IS DISTINCT FROM GREATEST(c.last_activity_at, excluded.last_activity_at)\n OR c.archived IS DISTINCT FROM COALESCE($6, c.archived)\n OR c.pinned IS DISTINCT FROM COALESCE($7, c.pinned)\n OR (excluded.anchor IS NOT NULL AND c.anchor IS DISTINCT FROM excluded.anchor AND (c.anchor IS NULL\n OR (excluded.anchor->>'at')::timestamptz >= (c.anchor->>'at')::timestamptz))",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Text",
- "Text",
- "Text",
- "Timestamptz",
- "Bool",
- "Bool",
- "Jsonb"
- ]
- },
- "nullable": []
- },
- "hash": "ca90bf3789dc312e956c7153adab75c8a048dc949b0a59baf4e002f97b36643a"
-}
diff --git a/.sqlx/query-cb8ba5c8966bcadfe5c89637ea9d4f7c1e098f2f7296c84ec8a6555114877ff0.json b/.sqlx/query-cb8ba5c8966bcadfe5c89637ea9d4f7c1e098f2f7296c84ec8a6555114877ff0.json
new file mode 100644
index 0000000000..d3fd8d9107
--- /dev/null
+++ b/.sqlx/query-cb8ba5c8966bcadfe5c89637ea9d4f7c1e098f2f7296c84ec8a6555114877ff0.json
@@ -0,0 +1,58 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO whatsapp_group (id, group_jid, kind, name, user_id, state, share_permission_id, backfill_state)\n VALUES ($1,$2,$3,$4,$5,'active',$6,\n CASE WHEN EXISTS (SELECT 1 FROM whatsapp_chat WHERE account_id = $7 AND chat_jid = $2 AND anchor IS NOT NULL)\n OR EXISTS (SELECT 1 FROM whatsapp_group_message m JOIN whatsapp_group g ON g.id = m.binding_id\n WHERE g.group_jid = $2 AND m.kind = 'message' AND m.message_id IS NOT NULL\n AND EXISTS (SELECT 1 FROM whatsapp_message_observation o WHERE o.binding_id = m.binding_id\n AND o.person_id = m.person_id AND o.source_id = m.source_id AND o.account_id = $7))\n THEN 'pending' ELSE 'waiting_for_message' END)\n RETURNING id, group_jid, kind, user_id, state, adopted_at",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "group_jid",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "kind",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "state",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "adopted_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text",
+ "Text",
+ "Text",
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "cb8ba5c8966bcadfe5c89637ea9d4f7c1e098f2f7296c84ec8a6555114877ff0"
+}
diff --git a/.sqlx/query-e55c16693e50ef596a84285d816a513f20f480b1c15be658fc894fdab1dfaf3a.json b/.sqlx/query-d044c7fd6d10b08dbf317d73beb9f14f8247544befbb6bab882e9c636056e19b.json
similarity index 91%
rename from .sqlx/query-e55c16693e50ef596a84285d816a513f20f480b1c15be658fc894fdab1dfaf3a.json
rename to .sqlx/query-d044c7fd6d10b08dbf317d73beb9f14f8247544befbb6bab882e9c636056e19b.json
index 7324b607c3..7ee64a5d2b 100644
--- a/.sqlx/query-e55c16693e50ef596a84285d816a513f20f480b1c15be658fc894fdab1dfaf3a.json
+++ b/.sqlx/query-d044c7fd6d10b08dbf317d73beb9f14f8247544befbb6bab882e9c636056e19b.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "SELECT m.id,m.person_id,p.user_id,COALESCE(p.display_name,'WhatsApp participant') AS \"name!\",\n m.body,m.reply_to,m.source_at,m.ingested_at,m.revised_at,m.deleted_at,m.kind,m.rich,m.mentions,m.forwarded,m.view_once,\n (SELECT state FROM whatsapp_send s WHERE s.message_id = m.id AND s.user_id = $2 ORDER BY s.created_at DESC LIMIT 1) AS delivery\n FROM whatsapp_group_message m JOIN whatsapp_external_person p ON p.id = m.person_id\n WHERE m.binding_id = $1 AND m.message_id IS NOT NULL\n AND ($3::uuid IS NULL OR (m.source_at,m.id) < (SELECT source_at,id FROM whatsapp_group_message WHERE id = $3 AND binding_id = $1 AND message_id IS NOT NULL))\n ORDER BY m.source_at DESC,m.id DESC LIMIT $4",
+ "query": "SELECT m.id,m.person_id,p.user_id,COALESCE(p.display_name,'WhatsApp participant') AS \"name!\",\n m.body,m.reply_to,m.source_at,m.ingested_at,m.revised_at,m.deleted_at,m.kind,m.rich,m.mentions,m.forwarded,m.view_once,\n (SELECT state FROM whatsapp_send s WHERE s.message_id = m.id AND s.user_id = $2 ORDER BY s.created_at DESC LIMIT 1) AS delivery\n FROM whatsapp_group_message m JOIN whatsapp_external_person p ON p.id = m.person_id\n WHERE m.binding_id = $1 AND m.message_id IS NOT NULL\n AND ($3::uuid IS NULL OR (m.source_at,m.id) < (SELECT source_at,id FROM whatsapp_group_message WHERE id = $3 AND binding_id = $1 AND message_id IS NOT NULL))\n AND ($5::uuid IS NULL OR m.id = $5)\n ORDER BY m.source_at DESC,m.id DESC LIMIT $4",
"describe": {
"columns": [
{
@@ -89,7 +89,8 @@
"Uuid",
"Text",
"Uuid",
- "Int8"
+ "Int8",
+ "Uuid"
]
},
"nullable": [
@@ -111,5 +112,5 @@
null
]
},
- "hash": "e55c16693e50ef596a84285d816a513f20f480b1c15be658fc894fdab1dfaf3a"
+ "hash": "d044c7fd6d10b08dbf317d73beb9f14f8247544befbb6bab882e9c636056e19b"
}
diff --git a/.sqlx/query-d97f6d326a00dc82c793bee806800fbe5fb9b11e7269931ce956fda4f2f03bec.json b/.sqlx/query-d97f6d326a00dc82c793bee806800fbe5fb9b11e7269931ce956fda4f2f03bec.json
deleted file mode 100644
index 4b3f0c991e..0000000000
--- a/.sqlx/query-d97f6d326a00dc82c793bee806800fbe5fb9b11e7269931ce956fda4f2f03bec.json
+++ /dev/null
@@ -1,19 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "UPDATE whatsapp_chat c SET\n name = COALESCE($3, c.name),\n last_activity_at = GREATEST(c.last_activity_at, $4),\n archived = COALESCE($5, c.archived),\n pinned = COALESCE($6, c.pinned),\n updated_at = now()\n WHERE c.account_id = $1 AND c.chat_jid = $2\n AND (c.name IS DISTINCT FROM COALESCE($3, c.name)\n OR c.last_activity_at IS DISTINCT FROM GREATEST(c.last_activity_at, $4)\n OR c.archived IS DISTINCT FROM COALESCE($5, c.archived)\n OR c.pinned IS DISTINCT FROM COALESCE($6, c.pinned))",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Text",
- "Text",
- "Timestamptz",
- "Bool",
- "Bool"
- ]
- },
- "nullable": []
- },
- "hash": "d97f6d326a00dc82c793bee806800fbe5fb9b11e7269931ce956fda4f2f03bec"
-}
diff --git a/.sqlx/query-df51b865a6ce141efd8914b20be2ffb38b2bd05871c7c415915409e27c16dea2.json b/.sqlx/query-df51b865a6ce141efd8914b20be2ffb38b2bd05871c7c415915409e27c16dea2.json
deleted file mode 100644
index 2b819bea7c..0000000000
--- a/.sqlx/query-df51b865a6ce141efd8914b20be2ffb38b2bd05871c7c415915409e27c16dea2.json
+++ /dev/null
@@ -1,26 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "UPDATE whatsapp_group b SET next_sequence = next_sequence + 1\n WHERE b.id = $1 AND b.id = $2 AND b.state = 'active'\n AND EXISTS (\n SELECT 1 FROM whatsapp_linked_account a JOIN whatsapp_group_membership m ON m.account_id = a.id\n WHERE a.id = $3 AND a.user_id = $4 AND a.state = 'connected' AND a.generation = $5\n AND m.binding_id = b.id AND m.generation = a.generation AND m.consent_ended_at IS NULL\n AND m.remote_member AND m.can_post AND m.reconciled)\n AND whatsapp_group_can_view(b.id, $4)\n RETURNING next_sequence",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "next_sequence",
- "type_info": "Int8"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "Uuid",
- "Uuid",
- "Text",
- "Int8"
- ]
- },
- "nullable": [
- false
- ]
- },
- "hash": "df51b865a6ce141efd8914b20be2ffb38b2bd05871c7c415915409e27c16dea2"
-}
diff --git a/.sqlx/query-e017c5c5684296df49cae20a2859ae72b0bd9b023b030aced9ffebda6e2c7c55.json b/.sqlx/query-e017c5c5684296df49cae20a2859ae72b0bd9b023b030aced9ffebda6e2c7c55.json
new file mode 100644
index 0000000000..019d2079cb
--- /dev/null
+++ b/.sqlx/query-e017c5c5684296df49cae20a2859ae72b0bd9b023b030aced9ffebda6e2c7c55.json
@@ -0,0 +1,24 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE whatsapp_group g SET name = i.name\n FROM UNNEST($2::text[], $3::text[]) AS i(group_jid, name)\n WHERE g.user_id = $1 AND g.group_jid = i.group_jid AND g.kind = 'direct' AND g.state = 'active'\n AND g.name <> i.name\n RETURNING g.id",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "TextArray",
+ "TextArray"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "e017c5c5684296df49cae20a2859ae72b0bd9b023b030aced9ffebda6e2c7c55"
+}
diff --git a/.sqlx/query-e1e4a113f30db292e22884add48dbf43b8f06bcb3043862fc75961973ed9f562.json b/.sqlx/query-e1e4a113f30db292e22884add48dbf43b8f06bcb3043862fc75961973ed9f562.json
new file mode 100644
index 0000000000..70f5d9e060
--- /dev/null
+++ b/.sqlx/query-e1e4a113f30db292e22884add48dbf43b8f06bcb3043862fc75961973ed9f562.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE whatsapp_group SET backfill_state = 'pending'\n WHERE user_id = $1 AND group_jid = ANY($2) AND state = 'active'\n AND backfill_state = 'waiting_for_message'\n RETURNING id",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "TextArray"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "e1e4a113f30db292e22884add48dbf43b8f06bcb3043862fc75961973ed9f562"
+}
diff --git a/.sqlx/query-25a3546a1d143befc191768ce7ca378bf2817eeec4629ae8b7b30aea1bcfe06c.json b/.sqlx/query-e6bf5a5973ceb5d020d0dc38c589387872b6826f3c80042437209e60ff4a683e.json
similarity index 75%
rename from .sqlx/query-25a3546a1d143befc191768ce7ca378bf2817eeec4629ae8b7b30aea1bcfe06c.json
rename to .sqlx/query-e6bf5a5973ceb5d020d0dc38c589387872b6826f3c80042437209e60ff4a683e.json
index d8fd852beb..cc99696a19 100644
--- a/.sqlx/query-25a3546a1d143befc191768ce7ca378bf2817eeec4629ae8b7b30aea1bcfe06c.json
+++ b/.sqlx/query-e6bf5a5973ceb5d020d0dc38c589387872b6826f3c80042437209e60ff4a683e.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "UPDATE whatsapp_group g SET backfill_state = $3,\n backfill_requested_at = CASE WHEN $4 THEN now() ELSE g.backfill_requested_at END\n FROM (SELECT id, backfill_state FROM whatsapp_group WHERE id = $1 FOR UPDATE) old\n WHERE g.id = old.id AND g.user_id = $2\n AND g.backfill_state IN ('pending', 'running', 'waiting_for_phone')\n RETURNING old.backfill_state AS \"previous!\"",
+ "query": "UPDATE whatsapp_group g SET backfill_state = $3,\n backfill_requested_at = CASE WHEN $4 THEN now() ELSE g.backfill_requested_at END\n FROM (SELECT id, backfill_state FROM whatsapp_group WHERE id = $1 FOR UPDATE) old\n WHERE g.id = old.id AND g.user_id = $2\n AND g.backfill_state IN ('waiting_for_message', 'pending', 'running', 'waiting_for_phone')\n RETURNING old.backfill_state AS \"previous!\"",
"describe": {
"columns": [
{
@@ -21,5 +21,5 @@
true
]
},
- "hash": "25a3546a1d143befc191768ce7ca378bf2817eeec4629ae8b7b30aea1bcfe06c"
+ "hash": "e6bf5a5973ceb5d020d0dc38c589387872b6826f3c80042437209e60ff4a683e"
}
diff --git a/.sqlx/query-ea5adae63196aa6243b6dca31577d9e75b3669fe70b0eece9257c3dcfc70dcea.json b/.sqlx/query-ea5adae63196aa6243b6dca31577d9e75b3669fe70b0eece9257c3dcfc70dcea.json
deleted file mode 100644
index 62f653a5dd..0000000000
--- a/.sqlx/query-ea5adae63196aa6243b6dca31577d9e75b3669fe70b0eece9257c3dcfc70dcea.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "UPDATE whatsapp_pairing SET state = 'failed', consumed_at = clock_timestamp(), qr_code = NULL, pair_code = NULL, passkey_challenge = NULL, passkey_response = NULL, updated_at = now() WHERE id = $1",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid"
- ]
- },
- "nullable": []
- },
- "hash": "ea5adae63196aa6243b6dca31577d9e75b3669fe70b0eece9257c3dcfc70dcea"
-}
diff --git a/Cargo.lock b/Cargo.lock
index 9cc39cf8dc..83bc1691a2 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -21599,6 +21599,7 @@ dependencies = [
"entity_access",
"entity_access_db_utils",
"macro_db_migrator",
+ "macro_user_id",
"sqlx",
"tokio",
"tokio-util",
@@ -21709,6 +21710,7 @@ dependencies = [
"tokio",
"tokio-util",
"tracing",
+ "tracing-subscriber",
"uuid",
"whatsapp_fake_server",
"whatsapp_linked",
diff --git a/apps/web/src/components/app/side-panel/SidePanel.tsx b/apps/web/src/components/app/side-panel/SidePanel.tsx
index 06e211bf29..486038079f 100644
--- a/apps/web/src/components/app/side-panel/SidePanel.tsx
+++ b/apps/web/src/components/app/side-panel/SidePanel.tsx
@@ -48,6 +48,14 @@ const NARROW_THRESHOLD_PX = 1224;
const SIDE_MIN_PX = 320;
const SIDE_MAX_PX = 380;
const MAIN_MIN_PX = 320;
+// The floating card's width, and its inset from the pane's top and right.
+const FLOATING_WIDTH_PX = 320;
+const FLOATING_INSET_PX = 12;
+/**
+ * Room to leave on the right so an open floating card covers nothing, for
+ * content that makes room for it where the pane is wide enough.
+ */
+const FLOATING_CLEARANCE_PX = FLOATING_WIDTH_PX + 2 * FLOATING_INSET_PX;
/**
* Wide-mode open state for a side panel.
@@ -384,7 +392,13 @@ function SidePanelLayoutInner(
<aside
aria-label="Block details"
inert={!showFloating()}
- class="absolute right-3 top-3 flex max-h-[calc(100%-1.5rem)] w-[min(320px,calc(100%-1.5rem))] max-w-full flex-col overflow-hidden rounded-xl border border-edge-frame bg-surface shadow-xl pointer-events-auto"
+ class="absolute flex max-w-full flex-col overflow-hidden rounded-xl border border-edge-frame bg-surface shadow-xl pointer-events-auto"
+ style={{
+ top: `${FLOATING_INSET_PX}px`,
+ right: `${FLOATING_INSET_PX}px`,
+ width: `min(${FLOATING_WIDTH_PX}px, calc(100% - ${2 * FLOATING_INSET_PX}px))`,
+ 'max-height': `calc(100% - ${2 * FLOATING_INSET_PX}px)`,
+ }}
onClick={(event) => event.stopPropagation()}
>
<SidePanelOutlet
@@ -832,5 +846,6 @@ export const SidePanel = {
Loading,
CountTitle,
Card,
+ FLOATING_CLEARANCE_PX,
};
export { useSidePanel };
diff --git a/apps/web/src/features/channel/Media/MediaGrid.tsx b/apps/web/src/features/channel/Media/MediaGrid.tsx
index 6c70eee01a..e6cd03a720 100644
--- a/apps/web/src/features/channel/Media/MediaGrid.tsx
+++ b/apps/web/src/features/channel/Media/MediaGrid.tsx
@@ -20,6 +20,7 @@ function MessageImageTile(props: {
item: MediaItem;
large: boolean;
onOpen: () => void;
+ onError?: () => void;
}) {
const dimensions = () =>
constrainImageDimensions(
@@ -47,6 +48,7 @@ function MessageImageTile(props: {
width={dimensions()?.width ?? props.item.width ?? undefined}
height={dimensions()?.height ?? props.item.height ?? undefined}
fallback={<MediaImage.Fallback fill={!!dimensions()} />}
+ onError={props.onError}
style={{
...(dimensions()
? {
@@ -84,7 +86,11 @@ function AttachmentImageTile(props: { item: MediaItem; onOpen?: () => void }) {
);
}
-function MessageVideoTile(props: { item: MediaItem; onOpen: () => void }) {
+function MessageVideoTile(props: {
+ item: MediaItem;
+ onOpen: () => void;
+ onError?: () => void;
+}) {
const download = createFileDownload(() => mediaDownloadSource(props.item));
const [isInlinePlaying, setIsInlinePlaying] = createSignal(false);
const src = () => props.item.src;
@@ -109,6 +115,7 @@ function MessageVideoTile(props: { item: MediaItem; onOpen: () => void }) {
class="block max-h-120 max-w-full"
width={videoWidth()}
height={videoHeight()}
+ onError={props.onError}
/>
<MediaVideo.PlayOverlay class="[&_svg]:size-6" />
</button>
@@ -133,6 +140,7 @@ function MessageVideoTile(props: { item: MediaItem; onOpen: () => void }) {
src={src()}
width={videoWidth()}
height={videoHeight()}
+ onError={() => props.onError?.()}
/>
</Show>
<div
@@ -176,6 +184,8 @@ export function MediaGrid(props: {
items: MediaItem[];
variant: 'message' | 'attachments';
onOpen: (index: number) => void;
+ /** An item whose file failed to load (message tiles only). */
+ onError?: (id: string) => void;
class?: string;
}) {
const hasSingleLargeImage = createMemo(
@@ -199,6 +209,7 @@ export function MediaGrid(props: {
item={item}
large={hasSingleLargeImage()}
onOpen={() => props.onOpen(index())}
+ onError={() => props.onError?.(item.id)}
/>
</Match>
<Match
@@ -213,6 +224,7 @@ export function MediaGrid(props: {
<MessageVideoTile
item={item}
onOpen={() => props.onOpen(index())}
+ onError={() => props.onError?.(item.id)}
/>
</Match>
<Match when={true}>
diff --git a/apps/web/src/features/channel/Media/MediaImage.tsx b/apps/web/src/features/channel/Media/MediaImage.tsx
index e6b946e9ca..9d3209cad0 100644
--- a/apps/web/src/features/channel/Media/MediaImage.tsx
+++ b/apps/web/src/features/channel/Media/MediaImage.tsx
@@ -82,6 +82,8 @@ function Image(props: {
style?: JSX.CSSProperties;
loading?: 'eager' | 'lazy';
fallback?: JSX.Element;
+ /** The file couldn't be loaded; the fallback otherwise stays up. */
+ onError?: () => void;
}) {
const [loaded, setLoaded] = createSignal(false);
const hasDimensions = () => (props.width ?? 0) > 0 && (props.height ?? 0) > 0;
@@ -133,6 +135,7 @@ function Image(props: {
loading={props.loading}
onClick={() => props.onOpen?.()}
onLoad={() => setLoaded(true)}
+ onError={() => props.onError?.()}
use:internalDrag={true}
/>
</>
diff --git a/apps/web/src/features/channel/Media/MediaVideo.tsx b/apps/web/src/features/channel/Media/MediaVideo.tsx
index fc562cd4d1..f5446c1a28 100644
--- a/apps/web/src/features/channel/Media/MediaVideo.tsx
+++ b/apps/web/src/features/channel/Media/MediaVideo.tsx
@@ -16,6 +16,7 @@ function Preview(props: {
onOpen?: () => void;
width?: number;
height?: number;
+ onError?: () => void;
}) {
return (
<video
@@ -27,6 +28,7 @@ function Preview(props: {
width={props.width}
height={props.height}
onClick={() => props.onOpen?.()}
+ onError={() => props.onError?.()}
onLoadedMetadata={(e) => {
// iOS Safari doesn't paint the first frame with preload="metadata".
// Seeking to a tiny positive time forces it to decode and display the frame.
diff --git a/apps/web/src/features/channel/Message/ChannelMessage.tsx b/apps/web/src/features/channel/Message/ChannelMessage.tsx
index 8e802ceab7..803e159940 100644
--- a/apps/web/src/features/channel/Message/ChannelMessage.tsx
+++ b/apps/web/src/features/channel/Message/ChannelMessage.tsx
@@ -12,21 +12,15 @@ import type { ChannelMessageListMeta } from './list-meta';
import { Message } from './Message';
import { MaybeSwipeToReplyRow } from './SwipeToReplyRow';
-/**
- * Where a message lives. A WhatsApp group renders through these rows but keeps
- * its own storage, so it never reaches the stored-message editor.
- */
-export type ChannelMessageParent =
- | MessageParent
- | { type: 'whatsapp_group'; id: string };
-
-function storedParent(parent: ChannelMessageParent): MessageParent | undefined {
- return parent.type === 'whatsapp_group' ? undefined : parent;
-}
-
type ChannelMessageProps = {
renderContent?: (content: JSX.Element) => JSX.Element;
- parent: ChannelMessageParent;
+ /**
+ * The stored conversation the message belongs to; inline editing needs
+ * it. Rows of messages stored elsewhere leave it out.
+ */
+ parent?: MessageParent;
+ /** Header time; defaults to the time alone in a channel. */
+ timestampFormat?: 'time' | 'dateAndTime';
inputMode?: 'inline' | 'unified';
message: MessageData;
actions?: MessageActions;
@@ -55,7 +49,7 @@ function isEditingMessage(
function MessageContentSlot(props: {
renderContent?: (content: JSX.Element) => JSX.Element;
- parent: ChannelMessageParent;
+ parent?: MessageParent;
inputMode?: 'inline' | 'unified';
messageEditor?: MessageEditor;
class?: string;
@@ -63,7 +57,7 @@ function MessageContentSlot(props: {
const message = useMessage();
const isEditing = () => isEditingMessage(props.messageEditor, message().id);
const inlineEditing = () => {
- const parent = storedParent(props.parent);
+ const parent = props.parent;
const messageEditor = props.messageEditor;
if (!isEditing() || props.inputMode === 'unified') return;
return parent && messageEditor ? { parent, messageEditor } : undefined;
@@ -133,7 +127,8 @@ function DeletedMessageLayout() {
function RegularMessageLayout(props: {
renderContent?: (content: JSX.Element) => JSX.Element;
- parent: ChannelMessageParent;
+ parent?: MessageParent;
+ timestampFormat?: 'time' | 'dateAndTime';
inputMode?: 'inline' | 'unified';
messageEditor?: MessageEditor;
hideTriggeredBy?: boolean;
@@ -150,10 +145,8 @@ function RegularMessageLayout(props: {
<Message.Timestamp
class="shrink-0"
format={
- props.parent.type === 'channel' ||
- props.parent.type === 'whatsapp_group'
- ? 'time'
- : 'dateAndTime'
+ props.timestampFormat ??
+ (props.parent?.type === 'channel' ? 'time' : 'dateAndTime')
}
/>
<Message.EditedIndicator class="shrink-0" />
@@ -184,7 +177,7 @@ function RegularMessageLayout(props: {
function GroupedMessageLayout(props: {
renderContent?: (content: JSX.Element) => JSX.Element;
- parent: ChannelMessageParent;
+ parent?: MessageParent;
inputMode?: 'inline' | 'unified';
messageEditor?: MessageEditor;
}) {
@@ -263,6 +256,7 @@ export function ChannelMessage(props: ChannelMessageProps) {
<RegularMessageLayout
renderContent={props.renderContent}
parent={props.parent}
+ timestampFormat={props.timestampFormat}
inputMode={props.inputMode}
messageEditor={props.messageEditor}
hideTriggeredBy={props.hideTriggeredBy}
diff --git a/apps/web/src/features/channel/Message/MediaPreview.tsx b/apps/web/src/features/channel/Message/MediaPreview.tsx
index 681b20c8d9..c91de2b74c 100644
--- a/apps/web/src/features/channel/Message/MediaPreview.tsx
+++ b/apps/web/src/features/channel/Message/MediaPreview.tsx
@@ -6,6 +6,8 @@ import { createSignal } from 'solid-js';
type MediaPreviewProps = {
items: MediaItem[];
class?: string;
+ /** An item whose file failed to load. */
+ onError?: (id: string) => void;
};
export function MediaPreview(props: MediaPreviewProps) {
@@ -18,6 +20,7 @@ export function MediaPreview(props: MediaPreviewProps) {
items={props.items}
variant="message"
class={props.class}
+ onError={props.onError}
onOpen={(index) => {
setSelectedIndex(index);
setViewerOpen(true);
diff --git a/apps/web/src/features/external-view/components/in-macro-section.test.tsx b/apps/web/src/features/external-view/components/in-macro-section.test.tsx
index dec8a95f71..394b6040c4 100644
--- a/apps/web/src/features/external-view/components/in-macro-section.test.tsx
+++ b/apps/web/src/features/external-view/components/in-macro-section.test.tsx
@@ -5,7 +5,9 @@ import {
screen,
within,
} from '@solidjs/testing-library';
+import { createRoot } from 'solid-js';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { createOpenSections } from '../../whatsapp-linked/primitives/open-sections';
import { InMacroGroups } from './in-macro-section';
beforeEach(() => {
@@ -32,6 +34,7 @@ it('lists readable groups with unread counts and marks read-only ones', () => {
id: 'group-design',
kind: 'group',
name: 'Design Crit',
+ ownerId: 'macro|[email protected]',
unreadCount: 3,
canSend: true,
},
@@ -39,6 +42,7 @@ it('lists readable groups with unread counts and marks read-only ones', () => {
id: 'group-family',
kind: 'group',
name: 'Ana, Ben, +2',
+ ownerId: 'macro|[email protected]',
unreadCount: 0,
canSend: false,
},
@@ -46,6 +50,7 @@ it('lists readable groups with unread counts and marks read-only ones', () => {
id: 'chat-ana',
kind: 'direct',
name: 'Ana Ruiz',
+ ownerId: 'macro|[email protected]',
unreadCount: 1,
canSend: false,
},
@@ -53,6 +58,8 @@ it('lists readable groups with unread counts and marks read-only ones', () => {
isPending={false}
isError={false}
activeGroupId="group-family"
+ isOpen={() => true}
+ onOpenChange={vi.fn()}
onOpenGroup={onOpenGroup}
onRetry={vi.fn()}
/>
@@ -68,10 +75,84 @@ it('lists readable groups with unread counts and marks read-only ones', () => {
expect(within(family).getByText('Read-only')).toBeTruthy();
// A shared direct chat: only its owner replies.
const direct = nav.getByRole('button', { name: /Ana Ruiz/ });
- expect(within(direct).getByText('Read-only').getAttribute('title')).toBe(
- 'You can read this chat. Only its owner can reply.'
- );
+ expect(
+ within(direct).getByText(
+ ': You can read this chat. Only its owner can reply.'
+ )
+ ).toBeTruthy();
fireEvent.click(design);
expect(onOpenGroup).toHaveBeenCalledWith('group-design');
});
+
+it('sorts chats into direct messages, groups and one section per community, like Chat', () => {
+ const sections = createRoot(() =>
+ createOpenSections('test:sidebar-sections', () => undefined)
+ );
+ const launch = { id: '[email protected]', name: 'Launch' };
+ render(() => (
+ <InMacroGroups
+ groups={[
+ {
+ id: 'chat-ana',
+ kind: 'direct',
+ name: 'Ana Ruiz',
+ ownerId: 'macro|[email protected]',
+ unreadCount: 0,
+ canSend: true,
+ },
+ {
+ id: 'group-notices',
+ kind: 'group',
+ name: 'Launch',
+ ownerId: 'macro|[email protected]',
+ unreadCount: 4,
+ canSend: false,
+ community: { ...launch, announcements: true },
+ },
+ {
+ id: 'group-design',
+ kind: 'group',
+ name: 'Design Crit',
+ ownerId: 'macro|[email protected]',
+ unreadCount: 2,
+ canSend: true,
+ },
+ {
+ id: 'group-launch-design',
+ kind: 'group',
+ name: 'Design',
+ ownerId: 'macro|[email protected]',
+ unreadCount: 1,
+ canSend: true,
+ community: { ...launch, announcements: false },
+ },
+ ]}
+ isPending={false}
+ isError={false}
+ activeGroupId={undefined}
+ isOpen={sections.isOpen}
+ onOpenChange={sections.setOpen}
+ onOpenGroup={vi.fn()}
+ onRetry={vi.fn()}
+ />
+ ));
+ const rows = (label: string) =>
+ within(screen.getByRole('navigation', { name: label }))
+ .getAllByRole('button')
+ .map((row) => row.getAttribute('title'));
+ expect(rows('Direct messages')).toEqual(['Ana Ruiz']);
+ expect(rows('Groups')).toEqual(['Design Crit']);
+ // Under its community, a group goes by its own name, in recent order.
+ expect(rows('Launch')).toEqual(['Announcements', 'Design']);
+ expect(
+ screen
+ .getAllByRole('button', { expanded: true })
+ .map((trigger) => trigger.textContent)
+ ).toEqual(['Direct messages', 'Groups', 'Communities', 'Launch']);
+
+ // A folded section keeps its unread count in sight.
+ fireEvent.click(screen.getByRole('button', { name: 'Communities' }));
+ expect(sections.isOpen('communities')).toBe(false);
+ expect(screen.getByLabelText('5 unread messages')).toBeTruthy();
+});
diff --git a/apps/web/src/features/external-view/components/in-macro-section.tsx b/apps/web/src/features/external-view/components/in-macro-section.tsx
index 05e345f4b1..c5a4033cfc 100644
--- a/apps/web/src/features/external-view/components/in-macro-section.tsx
+++ b/apps/web/src/features/external-view/components/in-macro-section.tsx
@@ -1,10 +1,21 @@
import { ViewSidebar } from '@app/components/view-shell';
import { ViewSkeleton } from '@app/components/view-shell/ViewSkeleton';
-import type { GroupSummary } from '@app/features/whatsapp-group/core/group';
import UserIcon from '@phosphor/user.svg';
import UsersThreeIcon from '@phosphor/users-three.svg';
-import { Button } from '@ui';
+import { Button, Tooltip } from '@ui';
import { For, Match, Show, Switch } from 'solid-js';
+import type { GroupSummary } from '../../whatsapp-group/core/group';
+import { ConversationSectionList } from '../../whatsapp-linked/components/conversation-sections';
+import {
+ conversationSections,
+ nameInCommunity,
+} from '../../whatsapp-linked/core/chat';
+
+function readOnlyReason(group: GroupSummary): string {
+ return group.kind === 'direct'
+ ? 'You can read this chat. Only its owner can reply.'
+ : "You can read this group. Your WhatsApp isn't in it, so you can't send.";
+}
export function UnreadCount(props: { count: number }) {
return (
@@ -24,10 +35,12 @@ function GroupRow(props: {
active: boolean;
onOpen: () => void;
}) {
+ const name = () =>
+ props.group.community ? nameInCommunity(props.group) : props.group.name;
return (
<ViewSidebar.Item
active={props.active}
- title={props.group.name}
+ title={name()}
onClick={props.onOpen}
>
<ViewSidebar.Icon>
@@ -42,19 +55,15 @@ function GroupRow(props: {
class="min-w-0 flex-1 truncate"
classList={{ 'font-medium text-ink': props.group.unreadCount > 0 }}
>
- {props.group.name}
+ {name()}
</span>
<Show when={!props.group.canSend}>
- <span
- class="shrink-0 text-xs text-ink-extra-muted"
- title={
- props.group.kind === 'direct'
- ? 'You can read this chat. Only its owner can reply.'
- : "You can read this group. Your WhatsApp isn't in it, so you can't send."
- }
- >
- Read-only
- </span>
+ <Tooltip label={readOnlyReason(props.group)} as="span" class="shrink-0">
+ <span class="text-xs text-ink-extra-muted">
+ Read-only
+ <span class="sr-only">: {readOnlyReason(props.group)}</span>
+ </span>
+ </Tooltip>
</Show>
<UnreadCount count={props.group.unreadCount} />
</ViewSidebar.Item>
@@ -62,14 +71,18 @@ function GroupRow(props: {
}
/**
- * WhatsApp groups this viewer can read in Macro, their own and shared ones,
- * as rows nested under WhatsApp in External's sidebar.
+ * WhatsApp chats this viewer can read in Macro, their own and shared ones,
+ * nested under WhatsApp in External's sidebar: direct messages, groups, then
+ * each community's groups, like Chat's rail. Folded sections show their
+ * unread count.
*/
export function InMacroGroups(props: {
groups: GroupSummary[] | undefined;
isPending: boolean;
isError: boolean;
activeGroupId: string | undefined;
+ isOpen: (sectionId: string) => boolean;
+ onOpenChange: (sectionId: string, open: boolean) => void;
onOpenGroup: (groupId: string) => void;
onRetry: () => void;
}) {
@@ -77,24 +90,47 @@ export function InMacroGroups(props: {
<Switch>
<Match when={props.groups}>
{(groups) => (
- <ViewSidebar.Nav aria-label="WhatsApp chats in Macro">
- <For
- each={groups()}
- fallback={
- <p class="px-(--sidebar-item-inset) py-1.5 text-sm text-ink-extra-muted">
- No chats added yet
- </p>
- }
+ <Show
+ when={groups().length}
+ fallback={
+ <p class="px-(--sidebar-item-inset) py-1.5 text-sm text-ink-extra-muted">
+ No chats added yet
+ </p>
+ }
+ >
+ <div
+ role="navigation"
+ aria-label="WhatsApp chats in Macro"
+ class="flex flex-col"
>
- {(group) => (
- <GroupRow
- group={group}
- active={group.id === props.activeGroupId}
- onOpen={() => props.onOpenGroup(group.id)}
- />
- )}
- </For>
- </ViewSidebar.Nav>
+ <ConversationSectionList
+ sections={conversationSections(groups())}
+ isOpen={props.isOpen}
+ onOpenChange={props.onOpenChange}
+ folded={(items) => (
+ <UnreadCount
+ count={items.reduce(
+ (sum, group) => sum + group.unreadCount,
+ 0
+ )}
+ />
+ )}
+ list={(items, label) => (
+ <ViewSidebar.Nav aria-label={label}>
+ <For each={items}>
+ {(group) => (
+ <GroupRow
+ group={group}
+ active={group.id === props.activeGroupId}
+ onOpen={() => props.onOpenGroup(group.id)}
+ />
+ )}
+ </For>
+ </ViewSidebar.Nav>
+ )}
+ />
+ </div>
+ </Show>
)}
</Match>
<Match when={props.isPending}>
diff --git a/apps/web/src/features/external-view/external-view.tsx b/apps/web/src/features/external-view/external-view.tsx
index 66894ee0f4..caba2e7384 100644
--- a/apps/web/src/features/external-view/external-view.tsx
+++ b/apps/web/src/features/external-view/external-view.tsx
@@ -15,6 +15,7 @@ import { useSearchParams } from '@solidjs/router';
import { createSignal, Show } from 'solid-js';
import { z } from 'zod';
import { whatsappGroupApi } from '../whatsapp-group/queries/production-api';
+import { createOpenSections } from '../whatsapp-linked/primitives/open-sections';
import { WhatsAppLinked } from '../whatsapp-linked/whatsapp-linked';
import { InMacroGroups, UnreadCount } from './components/in-macro-section';
@@ -62,12 +63,18 @@ export function ExternalView() {
'external-view'
);
const [groupsOpen, setGroupsOpen] = createSignal(true);
+ const sections = createOpenSections(
+ 'macro:whatsapp:sidebar-sections:v2',
+ userId
+ );
const inMacroGroups = () => (
<InMacroGroups
groups={inMacro()}
isPending={groups.isPending}
isError={groups.isError}
activeGroupId={params.groupId}
+ isOpen={sections.isOpen}
+ onOpenChange={sections.setOpen}
onOpenGroup={openGroup}
onRetry={() => fireAndForget(groups.refetch(), 'external-view')}
/>
@@ -94,7 +101,7 @@ export function ExternalView() {
id="external-whatsapp-groups"
class="px-2 pt-4 pb-1 text-xs font-semibold tracking-tight text-ink-extra-muted"
>
- Groups
+ In Macro
</h2>
{inMacroGroups()}
</section>
diff --git a/apps/web/src/features/whatsapp-group/AGENTS.md b/apps/web/src/features/whatsapp-group/AGENTS.md
index 089d10bb73..cfe371fd34 100644
--- a/apps/web/src/features/whatsapp-group/AGENTS.md
+++ b/apps/web/src/features/whatsapp-group/AGENTS.md
@@ -32,6 +32,16 @@ lists belong to `features/whatsapp-linked` and `features/external-view`.
its owner sends; shared viewers see "Only <owner> can reply in this chat".
User-facing copy says "chat"; code, routes and the entity type keep "group".
- Viewing follows ordinary entity sharing. WhatsApp membership controls sending.
+- Members, sharing and Stop syncing live in the generic `SidePanel`
+ (`components/chat-details.tsx`), floating and closed by default like an
+ in-view email thread. The header is `ViewShell.TopBar` (kept visible on
+ touch, under the safe area) with Share in a `HeaderActionGroup` and
+ `SidePanel.Toggle`. The host
+ (`whatsapp-group.tsx`, the functional fixture, tests) supplies
+ `SidePanel.Root`; the view renders the `SidePanel.Layout`. While it is
+ open on a pane at least 900px wide, the timeline and composer pad
+ `SidePanel.FLOATING_CLEARANCE_PX` on the right so the card never covers
+ them.
- Every write uses the viewer's own connected WhatsApp account.
- A draft keeps one idempotency key until DSS records it; unknown outcomes
retry quietly with that key, so a resend can never arrive twice.
@@ -43,13 +53,17 @@ lists belong to `features/whatsapp-linked` and `features/external-view`.
- History imported after adding (`backfill` on the detail) lands older than
the rows shown; the view keeps its distance from the bottom when rows appear
above, and says "Importing history…" / "Waiting for … phone" until DSS
- reports `done` or `partial`.
+ reports `done` or `partial`. `waiting_for_message` (no message to import
+ from yet) shows nothing.
- Images, video and audio play inline: `fileUrl` resolves the imported
document's presigned URL and `InboundMedia` hands it to Chat's
`MediaPreview` (or an audio player); `groupMessageData` keeps them out of
the document chips. DSS's declared width/height reserve the space (keeps
the open-at-bottom scroll right); stickers, GIFs and voice notes follow the
- attachment's `presentation`.
+ attachment's `presentation`. A file whose URL can't be resolved, or whose
+ image, video or audio fails to load (expired or missing), shows
+ "Attachment unavailable" instead of loading forever (Chat's media tiles
+ report it through `MediaPreview`'s `onError`).
- The timeline and composer use Chat's layout (`macro-message-width` column,
`CustomScrollbar`, `ChannelInputContainer` → centered column). The view
follows the bottom (a `ResizeObserver` on the content) until the reader
diff --git a/apps/web/src/features/whatsapp-group/components/chat-details.tsx b/apps/web/src/features/whatsapp-group/components/chat-details.tsx
new file mode 100644
index 0000000000..86628be359
--- /dev/null
+++ b/apps/web/src/features/whatsapp-group/components/chat-details.tsx
@@ -0,0 +1,226 @@
+import { SidePanel } from '@components/app/side-panel';
+import { EntityMetadata } from '@components/app/side-panel/EntityMetadata';
+import MagnifyingGlassIcon from '@phosphor/magnifying-glass.svg';
+import { Badge, Button, ConfirmDialog, InputGroup } from '@ui';
+import { createMemo, createSignal, For, Show } from 'solid-js';
+import { phoneFromJid } from '../../whatsapp-linked/core/account';
+import type { GroupDetail } from '../core/group';
+
+/** Rosters longer than this get a filter above the list. */
+const FILTER_FROM = 12;
+
+type Member = GroupDetail['members'][number];
+
+function initials(name: string): string {
+ const letters = name
+ .replace(/^\+/, '')
+ .split(/\s+/)
+ .map((word) => word[0])
+ .filter((letter) => !!letter && /\p{L}/u.test(letter));
+ return (letters.slice(0, 2).join('') || '#').toUpperCase();
+}
+
+function MemberRow(props: { member: Member; own: boolean }) {
+ const phone = () => phoneFromJid(props.member.id);
+ return (
+ <li class="flex min-h-9 items-center gap-2 px-1" data-whatsapp-member>
+ <span
+ aria-hidden="true"
+ class="flex size-6 shrink-0 items-center justify-center rounded-full bg-hover text-[10px] font-medium text-ink-muted"
+ >
+ {initials(props.member.name)}
+ </span>
+ <div class="flex min-w-0 flex-1 flex-col">
+ <span class="ph-no-capture truncate text-sm text-ink">
+ {props.member.name}
+ <Show when={props.own}>
+ <span class="text-ink-extra-muted"> (you)</span>
+ </Show>
+ </span>
+ <Show when={phone() !== props.member.name && phone()}>
+ {(number) => (
+ <span class="ph-no-capture truncate text-xs text-ink-extra-muted">
+ {number()}
+ </span>
+ )}
+ </Show>
+ </div>
+ <Show when={props.member.admin}>
+ <Badge variant="outline" size="xs">
+ Admin
+ </Badge>
+ </Show>
+ </li>
+ );
+}
+
+/** The WhatsApp group's participants: name, number, admin. */
+function Members(props: { group: GroupDetail }) {
+ const [filter, setFilter] = createSignal('');
+ const ownDigits = () => props.group.phone?.replace(/\D/g, '');
+ const isOwn = (member: Member) =>
+ !!ownDigits() &&
+ phoneFromJid(member.id)?.replace(/\D/g, '') === ownDigits();
+ const sorted = createMemo(() =>
+ [...props.group.members].sort(
+ (a, b) =>
+ Number(isOwn(b)) - Number(isOwn(a)) ||
+ Number(b.admin) - Number(a.admin) ||
+ a.name.localeCompare(b.name)
+ )
+ );
+ const shown = createMemo(() => {
+ const query = filter().trim().toLowerCase();
+ if (!query) return sorted();
+ const digits = query.replace(/\D/g, '');
+ return sorted().filter(
+ (member) =>
+ member.name.toLowerCase().includes(query) ||
+ (!!digits && (phoneFromJid(member.id) ?? '').includes(digits))
+ );
+ });
+ return (
+ <div class="flex flex-col gap-2">
+ <p class="px-1 text-xs text-ink-muted">
+ Members of the WhatsApp group can send from Macro with their own
+ WhatsApp.
+ </p>
+ <Show when={props.group.members.length > FILTER_FROM}>
+ <InputGroup size="md" variant="outline" class="rounded-full">
+ <InputGroup.Addon>
+ <MagnifyingGlassIcon />
+ </InputGroup.Addon>
+ <InputGroup.Input
+ type="search"
+ value={filter()}
+ onInput={(event) => setFilter(event.currentTarget.value)}
+ placeholder="Search members"
+ aria-label="Search members"
+ />
+ </InputGroup>
+ </Show>
+ <ul aria-label="WhatsApp members" class="flex flex-col">
+ <For
+ each={shown()}
+ fallback={
+ <li class="px-1 py-2 text-xs text-ink-muted">
+ No matching members
+ </li>
+ }
+ >
+ {(member) => <MemberRow member={member} own={isOwn(member)} />}
+ </For>
+ </ul>
+ </div>
+ );
+}
+
+/**
+ * The chat's side panel sections: its WhatsApp members, Macro sharing and,
+ * for the owner, syncing. Registers with the nearest `SidePanel.Root`.
+ */
+export function ChatDetails(props: {
+ group: GroupDetail;
+ stopped: boolean;
+ onShare: () => void;
+ /** Stops syncing; false when it failed (the caller reported why). */
+ onStopSync: () => Promise<boolean>;
+}) {
+ const [confirming, setConfirming] = createSignal(false);
+ const [stopping, setStopping] = createSignal(false);
+ const stop = async () => {
+ setStopping(true);
+ const stopped = await props.onStopSync();
+ setStopping(false);
+ if (stopped) setConfirming(false);
+ };
+ return (
+ <>
+ <Show when={props.group.kind !== 'direct'}>
+ <SidePanel.Section
+ id="whatsapp-members"
+ title={
+ <SidePanel.CountTitle
+ label="Members"
+ count={props.group.members.length}
+ />
+ }
+ defaultOpen
+ order={10}
+ >
+ <Members group={props.group} />
+ </SidePanel.Section>
+ </Show>
+ <SidePanel.Section
+ id="whatsapp-sharing"
+ title="Sharing"
+ defaultOpen
+ order={20}
+ >
+ <div class="flex flex-col items-start gap-2 px-1">
+ <p class="text-xs text-ink-muted">
+ People you share this chat with read it in Macro.{' '}
+ {props.group.kind === 'direct'
+ ? 'Only its owner can reply.'
+ : 'Only WhatsApp members can send.'}
+ </p>
+ <Button variant="outline" size="sm" onClick={() => props.onShare()}>
+ Share…
+ </Button>
+ </div>
+ </SidePanel.Section>
+ <Show when={props.group.accessLevel === 'owner'}>
+ <SidePanel.Section
+ id="whatsapp-sync"
+ title="Syncing"
+ defaultOpen
+ order={30}
+ >
+ <div class="flex flex-col items-start gap-2 px-1">
+ <p class="text-xs text-ink-muted" role="status">
+ <Show
+ when={!props.stopped}
+ fallback="Syncing stopped. Its history stays in Macro."
+ >
+ <Show
+ when={props.group.phone}
+ fallback="New messages sync from your WhatsApp."
+ >
+ {(phone) => (
+ <>
+ New messages sync from your WhatsApp,{' '}
+ <span class="ph-no-capture">{phone()}</span>.
+ </>
+ )}
+ </Show>
+ </Show>
+ </p>
+ <Show when={!props.stopped}>
+ <Button
+ variant="danger"
+ size="sm"
+ onClick={() => setConfirming(true)}
+ >
+ Stop syncing
+ </Button>
+ </Show>
+ {/* Inside the panel, so on touch it stacks on the details sheet. */}
+ <ConfirmDialog
+ open={confirming()}
+ onOpenChange={setConfirming}
+ title="Stop syncing this chat?"
+ body="Its history stays in Macro. New messages will stop syncing."
+ confirmLabel="Stop syncing"
+ tone="danger"
+ pending={stopping()}
+ onConfirm={stop}
+ />
+ </div>
+ </SidePanel.Section>
+ </Show>
+ <SidePanel.Footer>
+ <EntityMetadata ownerId={props.group.ownerId} />
+ </SidePanel.Footer>
+ </>
+ );
+}
diff --git a/apps/web/src/features/whatsapp-group/components/inbound-attachment.tsx b/apps/web/src/features/whatsapp-group/components/inbound-attachment.tsx
index ce168b9a70..ac9c6858c8 100644
--- a/apps/web/src/features/whatsapp-group/components/inbound-attachment.tsx
+++ b/apps/web/src/features/whatsapp-group/components/inbound-attachment.tsx
@@ -1,41 +1,41 @@
import SpinnerIcon from '@phosphor/spinner.svg';
import WarningIcon from '@phosphor/warning-circle.svg';
import { Match, Switch } from 'solid-js';
-import type { InboundAttachment } from '../core/attachments';
/**
- * A WhatsApp file that isn't a Macro document yet: still importing, failed,
- * or of a kind Macro can't keep. Every state is the same height, so the
+ * A WhatsApp file that isn't a Macro document yet (still importing, failed,
+ * or of a kind Macro can't keep), or one whose file can't be fetched. Every state is the same height, so the
* channel doesn't jump when it resolves.
*/
export function InboundAttachmentPlaceholder(props: {
- attachment: InboundAttachment;
+ state: 'loading' | 'unavailable' | 'unsupported';
+ fileName: string;
}) {
return (
<div
class="flex h-12 max-w-sm items-center gap-2 rounded-lg border border-edge-muted px-3 text-sm text-ink-muted"
- data-linked-inbound-attachment={props.attachment.state}
+ data-linked-inbound-attachment={props.state}
>
<Switch>
- <Match when={props.attachment.state === 'loading'}>
+ <Match when={props.state === 'loading'}>
<SpinnerIcon
class="size-4 shrink-0 animate-spin"
aria-hidden="true"
/>
<span role="status" class="min-w-0 truncate">
- Loading {props.attachment.fileName}…
+ Loading {props.fileName}…
</span>
</Match>
- <Match when={props.attachment.state === 'unavailable'}>
+ <Match when={props.state === 'unavailable'}>
<WarningIcon class="size-4 shrink-0" aria-hidden="true" />
<span class="min-w-0 truncate">
- Attachment unavailable: {props.attachment.fileName}
+ Attachment unavailable: {props.fileName}
</span>
</Match>
- <Match when={props.attachment.state === 'unsupported'}>
+ <Match when={props.state === 'unsupported'}>
<WarningIcon class="size-4 shrink-0" aria-hidden="true" />
<span class="min-w-0 truncate">
- {props.attachment.fileName} can't be shown in Macro
+ {props.fileName} can't be shown in Macro
</span>
</Match>
</Switch>
diff --git a/apps/web/src/features/whatsapp-group/components/inbound-media.test.tsx b/apps/web/src/features/whatsapp-group/components/inbound-media.test.tsx
new file mode 100644
index 0000000000..772a2892f5
--- /dev/null
+++ b/apps/web/src/features/whatsapp-group/components/inbound-media.test.tsx
@@ -0,0 +1,56 @@
+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
+import { afterEach, expect, it } from 'vitest';
+import { InboundMedia } from './inbound-media';
+
+afterEach(cleanup);
+
+it('shows a file that fails to load as unavailable instead of loading forever', () => {
+ const { container } = render(() => (
+ <InboundMedia
+ files={[
+ {
+ id: 'photo',
+ kind: 'image',
+ fileName: 'photo.jpg',
+ url: 'https://files.example.test/expired-photo',
+ width: 800,
+ height: 600,
+ },
+ {
+ id: 'voice',
+ kind: 'audio',
+ fileName: 'voice.ogg',
+ url: 'https://files.example.test/expired-voice',
+ presentation: 'voice_note',
+ },
+ {
+ id: 'sticker',
+ kind: 'image',
+ fileName: 'sticker.webp',
+ url: undefined,
+ unavailable: true,
+ presentation: 'sticker',
+ },
+ ]}
+ />
+ ));
+ expect(screen.getByText('Attachment unavailable: sticker.webp')).toBeTruthy();
+ expect(screen.queryByLabelText('Loading sticker.webp')).toBeNull();
+
+ const photo = container.querySelector(
+ 'img[src="https://files.example.test/expired-photo"]'
+ );
+ const voice = container.querySelector('audio');
+ if (!photo || !voice) throw new Error('media not rendered');
+ fireEvent.error(photo);
+ fireEvent.error(voice);
+
+ expect(screen.getByText('Attachment unavailable: photo.jpg')).toBeTruthy();
+ expect(screen.getByText('Attachment unavailable: voice.ogg')).toBeTruthy();
+ expect(
+ container.querySelector(
+ 'img[src="https://files.example.test/expired-photo"]'
+ )
+ ).toBeNull();
+ expect(container.querySelector('audio')).toBeNull();
+});
diff --git a/apps/web/src/features/whatsapp-group/components/inbound-media.tsx b/apps/web/src/features/whatsapp-group/components/inbound-media.tsx
index c1d9c49d72..14dbc9d9b2 100644
--- a/apps/web/src/features/whatsapp-group/components/inbound-media.tsx
+++ b/apps/web/src/features/whatsapp-group/components/inbound-media.tsx
@@ -2,8 +2,9 @@ import type { MediaItem } from '@channel/Media/media-items';
import { MediaPreview } from '@channel/Message/MediaPreview';
import { constrainImageDimensions } from '@macro-inc/lexical-core/utils/media';
import MicrophoneIcon from '@phosphor/microphone.svg';
-import { createMemo, For, Match, Show, Switch } from 'solid-js';
+import { createMemo, createSignal, For, Match, Show, Switch } from 'solid-js';
import { formatDuration } from '../core/rich';
+import { InboundAttachmentPlaceholder } from './inbound-attachment';
/** An imported image, video or voice note with its resolved file URL. */
export type InboundMediaFile = {
@@ -12,6 +13,8 @@ export type InboundMediaFile = {
fileName: string;
/** Undefined while the URL resolves. */
url: string | undefined;
+ /** The URL couldn't be resolved (the file is gone or not readable). */
+ unavailable?: boolean;
/** A local preview shown until `url` loads (files this page sent). */
previewUrl?: string;
/** Declared by WhatsApp; reserves the space before the file loads. */
@@ -50,7 +53,7 @@ function Reserved(props: { file: InboundMediaFile; max: number }) {
}
/** Sticker size, no frame, like WhatsApp. */
-function Sticker(props: { file: InboundMediaFile }) {
+function Sticker(props: { file: InboundMediaFile; onError: () => void }) {
return (
<Show
when={props.file.url}
@@ -65,6 +68,7 @@ function Sticker(props: { file: InboundMediaFile }) {
height={boxFor(props.file, STICKER_MAX).height}
class="max-w-full object-contain select-none"
loading="lazy"
+ onError={() => props.onError()}
/>
)}
</Show>
@@ -72,7 +76,7 @@ function Sticker(props: { file: InboundMediaFile }) {
}
/** A GIF loops silently in place, like Chat's inline GIFs. */
-function Gif(props: { file: InboundMediaFile }) {
+function Gif(props: { file: InboundMediaFile; onError: () => void }) {
return (
<Show
when={props.file.url}
@@ -95,13 +99,14 @@ function Gif(props: { file: InboundMediaFile }) {
width={boxFor(props.file, MEDIA_MAX).width}
height={boxFor(props.file, MEDIA_MAX).height}
class="block h-auto max-w-full rounded-2xl border border-edge bg-surface"
+ onError={() => props.onError()}
/>
)}
</Show>
);
}
-function Audio(props: { file: InboundMediaFile }) {
+function Audio(props: { file: InboundMediaFile; onError: () => void }) {
const voice = () => props.file.presentation === 'voice_note';
const label = () =>
[
@@ -139,6 +144,7 @@ function Audio(props: { file: InboundMediaFile }) {
src={url()}
aria-label={label()}
class="h-10 w-full"
+ onError={() => props.onError()}
/>
)}
</Show>
@@ -149,12 +155,18 @@ function Audio(props: { file: InboundMediaFile }) {
/**
* WhatsApp media inline, like Chat: images and video in Chat's media grid
* (click opens the viewer), GIFs looping, stickers small and unframed,
- * audio and voice notes in a player with their length.
+ * audio and voice notes in a player with their length. A file that can't be
+ * fetched shows as unavailable instead of loading forever.
*/
export function InboundMedia(props: { files: InboundMediaFile[] }) {
+ const [failed, setFailed] = createSignal<ReadonlySet<string>>(new Set());
+ const fail = (id: string) => setFailed((ids) => new Set(ids).add(id));
+ const usable = (file: InboundMediaFile) =>
+ !file.unavailable && !failed().has(file.id);
const grid = () =>
props.files.filter(
(file) =>
+ usable(file) &&
file.kind !== 'audio' &&
file.presentation !== 'sticker' &&
file.presentation !== 'gif'
@@ -189,7 +201,7 @@ export function InboundMedia(props: { files: InboundMediaFile[] }) {
return (
<div class="mt-1 flex flex-col gap-2" data-whatsapp-inline-media>
<Show when={visual().length > 0}>
- <MediaPreview items={visual()} />
+ <MediaPreview items={visual()} onError={fail} />
</Show>
<For each={grid().filter((file) => !file.url)}>
{(file) => <Reserved file={file} max={MEDIA_MAX} />}
@@ -197,14 +209,20 @@ export function InboundMedia(props: { files: InboundMediaFile[] }) {
<For each={props.files}>
{(file) => (
<Switch>
+ <Match when={!usable(file)}>
+ <InboundAttachmentPlaceholder
+ state="unavailable"
+ fileName={file.fileName}
+ />
+ </Match>
<Match when={file.kind === 'audio'}>
- <Audio file={file} />
+ <Audio file={file} onError={() => fail(file.id)} />
</Match>
<Match when={file.presentation === 'sticker'}>
- <Sticker file={file} />
+ <Sticker file={file} onError={() => fail(file.id)} />
</Match>
<Match when={file.presentation === 'gif'}>
- <Gif file={file} />
+ <Gif file={file} onError={() => fail(file.id)} />
</Match>
</Switch>
)}
diff --git a/apps/web/src/features/whatsapp-group/components/system-line.tsx b/apps/web/src/features/whatsapp-group/components/system-line.tsx
index b4fb60753a..c7add31151 100644
--- a/apps/web/src/features/whatsapp-group/components/system-line.tsx
+++ b/apps/web/src/features/whatsapp-group/components/system-line.tsx
@@ -27,9 +27,10 @@ const ICONS = {
export function WhatsAppSystemLine(props: {
id: string;
line: SystemLine;
+ chat: 'group' | 'direct';
occurredAt: string;
}) {
- const text = () => describeSystemLine(props.line);
+ const text = () => describeSystemLine(props.line, props.chat);
return (
<SystemActivityLine
id={props.id}
diff --git a/apps/web/src/features/whatsapp-group/core/group.ts b/apps/web/src/features/whatsapp-group/core/group.ts
index 2f0063b372..4c5b6d1dc3 100644
--- a/apps/web/src/features/whatsapp-group/core/group.ts
+++ b/apps/web/src/features/whatsapp-group/core/group.ts
@@ -8,16 +8,27 @@ export type GroupSummary = {
/** A group, or a one-to-one chat (named after the other person). */
kind: 'group' | 'direct';
name: string;
+ /** The Macro user who added it; only they share it on. */
+ ownerId: string;
unreadCount: number;
/** False for viewers who can only read. */
canSend: boolean;
+ /** The WhatsApp community the group belongs to. */
+ community?: { id: string; name: string; announcements: boolean };
};
/**
* Importing the chat's earlier messages from the owner's phone after it was
* added. Absent for groups added before imports existed.
*/
export type GroupBackfill = {
- state: 'pending' | 'running' | 'waiting_for_phone' | 'done' | 'partial';
+ /** `waiting_for_message`: nobody has posted since adding; nothing to import from yet. */
+ state:
+ | 'waiting_for_message'
+ | 'pending'
+ | 'running'
+ | 'waiting_for_phone'
+ | 'done'
+ | 'partial';
/** Messages the phone sent, including ones already shown. */
imported: number;
};
@@ -80,15 +91,7 @@ export type GroupSend =
/** A recorded send, as DSS reports its progress. */
export type SendProgress = {
id: string;
- state:
- | 'pending'
- | 'sending'
- | 'unknown'
- | 'accepted'
- | 'sent'
- | 'delivered'
- | 'read'
- | 'failed';
+ state: 'pending' | 'sending' | 'unknown' | 'accepted' | 'failed';
messageId?: string;
errorCode?: string;
};
@@ -169,10 +172,7 @@ export function recordedOutcome(
): 'waiting' | 'accepted' | { failed: string } {
return match(progress.state)
.with(P.union('pending', 'sending'), () => 'waiting' as const)
- .with(
- P.union('accepted', 'sent', 'delivered', 'read'),
- () => 'accepted' as const
- )
+ .with('accepted', () => 'accepted' as const)
.with(P.union('failed', 'unknown'), () => ({
failed: deliveryFailure(progress),
}))
@@ -219,7 +219,7 @@ export function backfillStatus(
? 'Waiting for your phone to import history'
: "Waiting for the owner's phone to import history"
)
- .with(P.union('done', 'partial'), () => undefined)
+ .with(P.union('waiting_for_message', 'done', 'partial'), () => undefined)
.exhaustive();
}
diff --git a/apps/web/src/features/whatsapp-group/core/rich.test.ts b/apps/web/src/features/whatsapp-group/core/rich.test.ts
index 56473cc761..b4d91d98dd 100644
--- a/apps/web/src/features/whatsapp-group/core/rich.test.ts
+++ b/apps/web/src/features/whatsapp-group/core/rich.test.ts
@@ -17,7 +17,7 @@ const line = (partial: Partial<SystemLine>): SystemLine => ({
...partial,
});
const sentence = (partial: Partial<SystemLine>) =>
- systemLineSentence(describeSystemLine(line(partial)));
+ systemLineSentence(describeSystemLine(line(partial), 'group'));
describe('system lines', () => {
it('words every group event like WhatsApp', () => {
@@ -83,6 +83,14 @@ describe('system lines', () => {
call: { video: false, outcome: 'answered', durationSeconds: 125 },
})
).toBe('Group voice call · 2:05');
+ expect(
+ systemLineSentence(
+ describeSystemLine(
+ line({ action: 'call', call: { video: false, outcome: 'missed' } }),
+ 'direct'
+ )
+ )
+ ).toBe('Missed voice call');
});
it('starts with the verb when WhatsApp did not say who', () => {
diff --git a/apps/web/src/features/whatsapp-group/core/rich.ts b/apps/web/src/features/whatsapp-group/core/rich.ts
index d6e185a9f4..24b01ff917 100644
--- a/apps/web/src/features/whatsapp-group/core/rich.ts
+++ b/apps/web/src/features/whatsapp-group/core/rich.ts
@@ -179,8 +179,12 @@ export type SystemLineText = {
icon: 'added' | 'removed' | 'edit' | 'picture' | 'pin' | 'call' | 'timer';
};
-export function describeSystemLine(line: SystemLine): SystemLineText {
- const text = systemLineParts(line);
+/** `chat` decides whether a call reads as a group call. */
+export function describeSystemLine(
+ line: SystemLine,
+ chat: 'group' | 'direct'
+): SystemLineText {
+ const text = systemLineParts(line, chat);
// WhatsApp didn't say who: the verb starts the sentence.
return text.actor
? text
@@ -190,7 +194,10 @@ export function describeSystemLine(line: SystemLine): SystemLineText {
};
}
-function systemLineParts(line: SystemLine): SystemLineText {
+function systemLineParts(
+ line: SystemLine,
+ chat: 'group' | 'direct'
+): SystemLineText {
const actor = line.actor?.name;
const people = namesList(line.participants);
return match(line)
@@ -283,23 +290,27 @@ function systemLineParts(line: SystemLine): SystemLineText {
icon: 'pin',
}))
.with({ action: 'call' }, ({ call }) => ({
- verb: callLine(call),
+ verb: callLine(call, chat),
icon: 'call',
}))
.exhaustive();
}
-function callLine(call: CallSummary | undefined): string {
- const kind = call?.video ? 'video call' : 'voice call';
+function callLine(
+ call: CallSummary | undefined,
+ chat: 'group' | 'direct'
+): string {
+ const kind = `${chat === 'group' ? 'group ' : ''}${call?.video ? 'video call' : 'voice call'}`;
+ const plain = `${kind.charAt(0).toUpperCase()}${kind.slice(1)}`;
return match(call?.outcome)
- .with('missed', () => `Missed group ${kind}`)
- .with('rejected', () => `Declined group ${kind}`)
+ .with('missed', () => `Missed ${kind}`)
+ .with('rejected', () => `Declined ${kind}`)
.with('answered', () =>
call?.durationSeconds
- ? `Group ${kind} · ${formatDuration(call.durationSeconds)}`
- : `Group ${kind}`
+ ? `${plain} · ${formatDuration(call.durationSeconds)}`
+ : plain
)
- .with(P.union('other', undefined), () => `Group ${kind}`)
+ .with(P.union('other', undefined), () => plain)
.exhaustive();
}
diff --git a/apps/web/src/features/whatsapp-group/queries/production-api.test.ts b/apps/web/src/features/whatsapp-group/queries/production-api.test.ts
index 481eeb06a9..d62a025b3c 100644
--- a/apps/web/src/features/whatsapp-group/queries/production-api.test.ts
+++ b/apps/web/src/features/whatsapp-group/queries/production-api.test.ts
@@ -27,26 +27,26 @@ it('decodes shared viewing separately from the callers own sending account and h
id: '019a061e-0000-7000-8000-000000000001',
kind: 'group',
name: 'Shared group',
- user_id: 'macro|[email protected]',
- unread_count: 3,
- last_message_at: null,
- can_send: false,
- send_reason: 'no_account',
- access_level: 'view',
- sending_identity: null,
+ userId: 'macro|[email protected]',
+ unreadCount: 3,
+ lastMessageAt: null,
+ canSend: false,
+ sendReason: 'no_account',
+ accessLevel: 'view',
+ sendingIdentity: null,
roster: null,
- share_permission: {
+ sharePermission: {
id: 'share-1',
owner: 'macro|[email protected]',
channelSharePermissions: [],
},
limits: {
- text_limit_bytes: 65536,
- attachment_limit_bytes: 33554432,
- max_attachments: 1,
+ textLimitBytes: 65536,
+ attachmentLimitBytes: 33554432,
+ maxAttachments: 1,
mutations: ['reaction', 'edit', 'delete'],
- mutation_window_seconds: 900,
- attachment_types: ['image/png', 'application/pdf'],
+ mutationWindowSeconds: 900,
+ attachmentTypes: ['image/png', 'application/pdf'],
},
} satisfies WhatsAppGroupDetail;
client.detail.mockResolvedValue(ok(detail));
@@ -64,41 +64,41 @@ it('decodes shared viewing separately from the callers own sending account and h
it('decodes pagination, deleted flags, reaction ownership and attachment states from the independent timeline', async () => {
const page = {
- next_cursor: '019a061e-0000-7000-8000-000000000002',
+ nextCursor: '019a061e-0000-7000-8000-000000000002',
messages: [
{
id: '019a061e-0000-7000-8000-000000000003',
kind: 'message',
- sender: { person_id: 'person-1', user_id: null, name: 'Ana Ruiz' },
+ sender: { personId: 'person-1', userId: null, name: 'Ana Ruiz' },
body: '',
mentions: [],
forwarded: false,
- view_once: false,
+ viewOnce: false,
rich: null,
- reply_to: null,
- sent_at: '2026-10-21T12:00:00Z',
- received_at: '2026-10-21T12:00:01Z',
- edited_at: null,
+ replyTo: null,
+ sentAt: '2026-10-21T12:00:00Z',
+ receivedAt: '2026-10-21T12:00:01Z',
+ editedAt: null,
deleted: true,
reactions: [{ emoji: '👍', count: 2, mine: true }],
attachments: [
{
ordinal: 0,
state: 'unsupported',
- file_name: 'drawing.psd',
+ fileName: 'drawing.psd',
mime: 'image/vnd.adobe.photoshop',
size: 1024,
- document_id: null,
+ documentId: null,
},
],
- delivery_state: null,
+ deliveryState: null,
},
],
} satisfies WhatsAppGroupMessages;
client.messages.mockResolvedValue(ok(page));
const result = await whatsappGroupApi.messages('group-id', 'before-id');
expect(client.messages).toHaveBeenCalledWith('group-id', 'before-id');
- expect(result.before).toBe(page.next_cursor);
+ expect(result.before).toBe(page.nextCursor);
expect(result.messages[0]).toMatchObject({
deleted: true,
sender: { name: 'Ana Ruiz' },
@@ -111,24 +111,24 @@ it('decodes pagination, deleted flags, reaction ownership and attachment states
it('decodes mentions, forwarding, media presentation and every rich type, keeping only http(s) links', async () => {
const base: Omit<WhatsAppGroupMessage, 'id'> = {
- sender: { person_id: 'person-1', user_id: null, name: 'Ana Ruiz' },
+ sender: { personId: 'person-1', userId: null, name: 'Ana Ruiz' },
body: '',
- reply_to: null,
- sent_at: '2026-10-21T12:00:00Z',
- received_at: '2026-10-21T12:00:01Z',
- edited_at: null,
+ replyTo: null,
+ sentAt: '2026-10-21T12:00:00Z',
+ receivedAt: '2026-10-21T12:00:01Z',
+ editedAt: null,
deleted: false,
reactions: [],
attachments: [],
- delivery_state: null,
+ deliveryState: null,
kind: 'message',
mentions: [],
forwarded: false,
- view_once: false,
+ viewOnce: false,
rich: null,
};
const page = {
- next_cursor: null,
+ nextCursor: null,
messages: [
{
...base,
@@ -147,13 +147,13 @@ it('decodes mentions, forwarding, media presentation and every rich type, keepin
{
ordinal: 0,
state: 'ready',
- file_name: 'sticker.webp',
+ fileName: 'sticker.webp',
mime: 'image/webp',
size: 2048,
- document_id: 'doc-1',
+ documentId: 'doc-1',
width: 512,
height: 512,
- duration_seconds: null,
+ durationSeconds: null,
presentation: 'sticker',
},
],
@@ -294,9 +294,9 @@ it('preserves the deliberate send key and maps quotes and reactions without a ch
'intent-key'
);
expect(client.send).toHaveBeenCalledWith('group-id', {
- idempotency_key: 'intent-key',
+ idempotencyKey: 'intent-key',
message: { type: 'text', text: 'Reply', mentions: [] },
- reply_to: 'quoted-id',
+ replyTo: 'quoted-id',
});
await whatsappGroupApi.send(
'group-id',
@@ -308,13 +308,13 @@ it('preserves the deliberate send key and maps quotes and reactions without a ch
'mention-key'
);
expect(client.send).toHaveBeenLastCalledWith('group-id', {
- idempotency_key: 'mention-key',
+ idempotencyKey: 'mention-key',
message: {
type: 'text',
text: 'Hi @15550001111',
mentions: ['[email protected]'],
},
- reply_to: null,
+ replyTo: null,
});
await whatsappGroupApi.send(
'group-id',
@@ -322,14 +322,14 @@ it('preserves the deliberate send key and maps quotes and reactions without a ch
'reaction-key'
);
expect(client.send).toHaveBeenLastCalledWith('group-id', {
- idempotency_key: 'reaction-key',
+ idempotencyKey: 'reaction-key',
message: {
type: 'mutation',
- message_id: 'message-id',
+ messageId: 'message-id',
operation: 'reaction',
text: '',
},
- reply_to: null,
+ replyTo: null,
});
});
@@ -394,13 +394,13 @@ it('reads recorded progress by send id', async () => {
ok([
{
id: 'send-1',
- group_id: 'group-id',
- user_id: 'macro|[email protected]',
- created_at: '2026-10-21T12:00:00Z',
+ groupId: 'group-id',
+ userId: 'macro|[email protected]',
+ createdAt: '2026-10-21T12:00:00Z',
state: 'accepted',
- message_id: 'message-9',
+ messageId: 'message-9',
payload: {
- idempotency_key: 'key-1',
+ idempotencyKey: 'key-1',
message: { type: 'text', text: 'x' },
},
},
diff --git a/apps/web/src/features/whatsapp-group/queries/production-api.ts b/apps/web/src/features/whatsapp-group/queries/production-api.ts
index b144d884cc..b01c57e22a 100644
--- a/apps/web/src/features/whatsapp-group/queries/production-api.ts
+++ b/apps/web/src/features/whatsapp-group/queries/production-api.ts
@@ -90,24 +90,24 @@ function content(request: GroupSend): LinkedReplyContent {
}))
.with({ kind: 'media' }, ({ uploadId, caption }) => ({
type: 'media' as const,
- upload_id: uploadId,
+ uploadId,
caption: caption ?? null,
}))
.with({ kind: 'reaction' }, ({ messageId, emoji }) => ({
type: 'mutation' as const,
- message_id: messageId,
+ messageId,
operation: 'reaction' as const,
text: emoji,
}))
.with({ kind: 'edit' }, ({ messageId, text }) => ({
type: 'mutation' as const,
- message_id: messageId,
+ messageId,
operation: 'edit' as const,
text,
}))
.with({ kind: 'delete' }, ({ messageId }) => ({
type: 'mutation' as const,
- message_id: messageId,
+ messageId,
operation: 'delete' as const,
text: null,
}))
@@ -141,6 +141,8 @@ function writeFailure(
'INVALID_JSON',
'UNKNOWN_ERROR',
'temporarily_unavailable',
+ 'backlogged',
+ 'internal_error',
'lease_fenced',
// Not recorded; DSS takes one write per second per person.
'rate_limited'
@@ -171,7 +173,19 @@ function writeFailure(
kind: 'refused',
reason: "WhatsApp wasn't reachable in time, so this wasn't sent.",
}))
- .with(P.union('conflict', 'CONFLICT', 'identity_conflict'), () => ({
+ .with(
+ P.union(
+ 'cannot_add_not_in_group',
+ 'cannot_add_community',
+ 'cannot_add_own_chat',
+ 'cannot_add_not_in_chat_list'
+ ),
+ () => ({
+ kind: 'refused',
+ reason: "This chat can't be in Macro, so nothing was sent.",
+ })
+ )
+ .with(P.union('conflict', 'CONFLICT'), () => ({
kind: 'refused',
reason: 'This conflicts with an earlier WhatsApp request.',
}))
@@ -184,8 +198,8 @@ function progress(send: LinkedSendProgress): SendProgress {
return {
id: send.id,
state: send.state,
- messageId: send.message_id ?? undefined,
- errorCode: send.error_code ?? undefined,
+ messageId: send.messageId ?? undefined,
+ errorCode: send.errorCode ?? undefined,
};
}
@@ -196,8 +210,16 @@ export const whatsappGroupApi: WhatsAppGroupApi = {
id: group.id,
kind: group.kind,
name: group.name,
- unreadCount: group.unread_count,
- canSend: group.can_send,
+ ownerId: group.userId,
+ unreadCount: group.unreadCount,
+ canSend: group.canSend,
+ community: group.community
+ ? {
+ id: group.community.id,
+ name: group.community.name,
+ announcements: group.community.announcements,
+ }
+ : undefined,
})),
detail: async (id) => {
const view = await throwOnErr(() => client.detail(id));
@@ -205,14 +227,14 @@ export const whatsappGroupApi: WhatsAppGroupApi = {
id,
kind: view.kind,
name: view.name,
- ownerId: view.user_id,
- accessLevel: view.access_level,
- canSend: view.can_send,
- sendReason: view.send_reason ?? undefined,
- phone: view.sending_identity
- ? phoneFromJid(view.sending_identity)
+ ownerId: view.userId,
+ accessLevel: view.accessLevel,
+ canSend: view.canSend,
+ sendReason: view.sendReason ?? undefined,
+ phone: view.sendingIdentity
+ ? phoneFromJid(view.sendingIdentity)
: undefined,
- unreadCount: view.unread_count,
+ unreadCount: view.unreadCount,
members: (view.roster?.participants ?? []).map((person) => ({
id: person.jid,
name:
@@ -224,7 +246,7 @@ export const whatsappGroupApi: WhatsAppGroupApi = {
backfill: view.backfill
? { state: view.backfill.state, imported: view.backfill.imported }
: undefined,
- disappearingSeconds: view.disappearing_seconds ?? undefined,
+ disappearingSeconds: view.disappearingSeconds ?? undefined,
community: view.community
? {
name: view.community.name,
@@ -232,10 +254,10 @@ export const whatsappGroupApi: WhatsAppGroupApi = {
}
: undefined,
limits: {
- textBytes: view.limits.text_limit_bytes,
- attachmentBytes: view.limits.attachment_limit_bytes,
- attachmentTypes: view.limits.attachment_types,
- editSeconds: view.limits.mutation_window_seconds,
+ textBytes: view.limits.textLimitBytes,
+ attachmentBytes: view.limits.attachmentLimitBytes,
+ attachmentTypes: view.limits.attachmentTypes,
+ editSeconds: view.limits.mutationWindowSeconds,
mutations: view.limits.mutations,
},
};
@@ -243,13 +265,13 @@ export const whatsappGroupApi: WhatsAppGroupApi = {
messages: async (id, before) => {
const page = await throwOnErr(() => client.messages(id, before));
return {
- before: page.next_cursor ?? undefined,
+ before: page.nextCursor ?? undefined,
messages: page.messages.map((message) => ({
id: message.id,
kind: message.kind,
sender: {
name: message.sender.name,
- userId: message.sender.user_id ?? undefined,
+ userId: message.sender.userId ?? undefined,
},
body: message.body,
mentions: message.mentions.map((mention) => ({
@@ -258,10 +280,10 @@ export const whatsappGroupApi: WhatsAppGroupApi = {
})),
forwarded: message.forwarded,
rich: message.rich ? richContent(message.rich) : undefined,
- sentAt: message.sent_at,
- edited: !!message.edited_at,
+ sentAt: message.sentAt,
+ edited: !!message.editedAt,
deleted: message.deleted,
- replyTo: message.reply_to ?? undefined,
+ replyTo: message.replyTo ?? undefined,
reactions: message.reactions.map((reaction) => ({
emoji: reaction.emoji,
count: reaction.count,
@@ -270,12 +292,12 @@ export const whatsappGroupApi: WhatsAppGroupApi = {
attachments: message.attachments.map((attachment) => ({
ordinal: attachment.ordinal,
state: attachment.state,
- fileName: attachment.file_name,
+ fileName: attachment.fileName,
mime: attachment.mime,
- documentId: attachment.document_id ?? undefined,
+ documentId: attachment.documentId ?? undefined,
width: attachment.width ?? undefined,
height: attachment.height ?? undefined,
- durationSeconds: attachment.duration_seconds ?? undefined,
+ durationSeconds: attachment.durationSeconds ?? undefined,
presentation: attachment.presentation ?? undefined,
})),
})),
@@ -283,9 +305,9 @@ export const whatsappGroupApi: WhatsAppGroupApi = {
},
send: async (id, request, idempotencyKey) => {
const result = await client.send(id, {
- idempotency_key: idempotencyKey,
+ idempotencyKey,
message: content(request),
- reply_to: 'replyTo' in request ? (request.replyTo ?? null) : null,
+ replyTo: 'replyTo' in request ? (request.replyTo ?? null) : null,
});
return result.isOk()
? ok(progress(result.value))
@@ -297,7 +319,7 @@ export const whatsappGroupApi: WhatsAppGroupApi = {
const result = await client.upload(id, file);
return result.isOk()
? ok({
- uploadId: result.value.upload_id,
+ uploadId: result.value.uploadId,
audio: result.value.kind === 'audio',
})
: err(writeFailure(result.error));
diff --git a/apps/web/src/features/whatsapp-group/views/whatsapp-group-view.test.tsx b/apps/web/src/features/whatsapp-group/views/whatsapp-group-view.test.tsx
index a7f06f1117..28181273ed 100644
--- a/apps/web/src/features/whatsapp-group/views/whatsapp-group-view.test.tsx
+++ b/apps/web/src/features/whatsapp-group/views/whatsapp-group-view.test.tsx
@@ -1,5 +1,6 @@
import type { ChannelInputProps } from '@channel/Input/ChannelInput';
import type { InputHandle, InputSnapshot } from '@channel/Input/types';
+import { SidePanel } from '@components/app/side-panel';
import {
cleanup,
fireEvent,
@@ -69,15 +70,18 @@ function mount(fake: ReturnType<typeof createFakeGroup>) {
render(() => (
<QueryClientProvider client={new QueryClient()}>
<WhatsAppGroupProvider value={fake.capabilities}>
- <WhatsAppGroupView
- userId={group.ownerId}
- share={
- <button type="button" onClick={share}>
- Share
- </button>
- }
- onConnect={connect}
- />
+ <SidePanel.Root floating defaultOpen={false}>
+ <WhatsAppGroupView
+ userId={group.ownerId}
+ share={
+ <button type="button" onClick={share}>
+ Share
+ </button>
+ }
+ onShare={share}
+ onConnect={connect}
+ />
+ </SidePanel.Root>
</WhatsAppGroupProvider>
</QueryClientProvider>
));
@@ -228,6 +232,23 @@ it('says while history imports and shows older messages as they land', () => {
expect(screen.getByText('Earlier messages stay in WhatsApp')).toBeTruthy();
});
+it('says nothing while the chat waits for its first message', () => {
+ const fake = createFakeGroup({
+ group: {
+ ...group,
+ backfill: { state: 'waiting_for_message', imported: 0 },
+ },
+ messages: [],
+ });
+ mount(fake);
+ expect(screen.queryByRole('status')).toBeNull();
+ expect(screen.queryByText(/Importing history|Waiting for/)).toBeNull();
+ expect(screen.getByText(/No messages yet/)).toBeTruthy();
+
+ fake.setGroup({ ...group, backfill: { state: 'pending', imported: 0 } });
+ expect(screen.getByRole('status').textContent).toBe('Importing history…');
+});
+
it('tells a shared viewer whose phone the import waits for', () => {
const fake = createFakeGroup({
group: {
@@ -652,3 +673,69 @@ it('shows a direct chat as the person, and who can reply when shared', () => {
);
expect(screen.queryByTestId('whatsapp-composer')).toBeNull();
});
+
+it('opens members, sharing and syncing in the side panel', async () => {
+ const fake = createFakeGroup({
+ group: {
+ ...group,
+ members: [
+ { id: '[email protected]', name: 'Ben Okafor', admin: false },
+ { id: '[email protected]', name: 'Ana Ruiz', admin: true },
+ { id: '[email protected]', name: 'Wolf', admin: false },
+ ],
+ },
+ });
+ const { share } = mount(fake);
+ expect(screen.queryByRole('list', { name: 'WhatsApp members' })).toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: /side panel/i }));
+
+ const members = await screen.findByRole('list', {
+ name: 'WhatsApp members',
+ });
+ // You first, then admins, then everyone else by name.
+ expect(
+ [...members.querySelectorAll('li')].map((row) => row.textContent)
+ ).toEqual([
+ 'WWolf (you)+14155550142',
+ 'ARAna Ruiz+14155550101Admin',
+ 'BOBen Okafor',
+ ]);
+ fireEvent.click(screen.getByRole('button', { name: 'Share…' }));
+ expect(share).toHaveBeenCalledOnce();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Stop syncing' }));
+ const confirm = await screen.findByRole('dialog');
+ fireEvent.click(
+ [...confirm.querySelectorAll('button')].find(
+ (button) => button.textContent === 'Stop syncing'
+ ) as HTMLButtonElement
+ );
+ await waitFor(() => expect(fake.capabilities.stopSync).toHaveBeenCalled());
+ expect(
+ await screen.findByText('Syncing stopped. Its history stays in Macro.')
+ ).toBeTruthy();
+ expect(screen.getByText('This chat is no longer syncing')).toBeTruthy();
+});
+
+it('lets the owner stop syncing a direct chat from its details', async () => {
+ const fake = createFakeGroup({
+ group: { ...group, kind: 'direct', name: 'Ana Ruiz', members: [] },
+ });
+ mount(fake);
+ fireEvent.click(screen.getByRole('button', { name: /side panel/i }));
+ expect(
+ await screen.findByRole('button', { name: 'Stop syncing' })
+ ).toBeTruthy();
+ expect(screen.queryByRole('list', { name: 'WhatsApp members' })).toBeNull();
+ expect(screen.getByText(/Only its owner can reply/)).toBeTruthy();
+});
+
+it('keeps syncing controls from a shared viewer', async () => {
+ const fake = createFakeGroup({
+ group: { ...group, accessLevel: 'view', canSend: false },
+ });
+ mount(fake);
+ fireEvent.click(screen.getByRole('button', { name: /side panel/i }));
+ expect(await screen.findByRole('button', { name: 'Share…' })).toBeTruthy();
+ expect(screen.queryByRole('button', { name: 'Stop syncing' })).toBeNull();
+});
diff --git a/apps/web/src/features/whatsapp-group/views/whatsapp-group-view.tsx b/apps/web/src/features/whatsapp-group/views/whatsapp-group-view.tsx
index c5f7f79dc5..2a773dd28b 100644
--- a/apps/web/src/features/whatsapp-group/views/whatsapp-group-view.tsx
+++ b/apps/web/src/features/whatsapp-group/views/whatsapp-group-view.tsx
@@ -1,3 +1,5 @@
+import { ViewShell } from '@app/components/view-shell';
+import { ChannelLoading } from '@channel/Channel/ChannelLoading';
import { buildChannelMessageListMeta } from '@channel/Channel/message-list-meta';
import { ChannelInput } from '@channel/Input/ChannelInput';
import { ChannelInputContainer } from '@channel/Input/ChannelInputContainer';
@@ -9,8 +11,9 @@ import { DateDivider } from '@channel/Message/DateDivider';
import { NewDivider } from '@channel/Message/NewDivider';
import { SenderName } from '@channel/Message/SenderName';
import { MaybeMessageActionDrawerManager } from '@channel/Mobile/MessageActionDrawerManager';
-import { HeaderActionButton } from '@components/app/HeaderActionButton';
+import { HeaderActionGroup } from '@components/app/HeaderActionGroup';
import { FloatRegionOrInline } from '@components/app/mobile/float-regions/FloatRegion';
+import { SidePanel, useSidePanel } from '@components/app/side-panel';
import { CustomScrollbar } from '@core/component/CustomScrollbar';
import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
import { toast } from '@core/component/Toast/Toast';
@@ -18,12 +21,12 @@ import type {
MessageActionContext,
MessageActions,
} from '@core/messages/types';
+import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { getDisplayName, tryMacroId } from '@core/user';
import type { IUser } from '@core/user/types';
import { fireAndForget } from '@core/util/fireAndForget';
import ShareFatIcon from '@phosphor/share-fat.svg';
import TimerIcon from '@phosphor/timer.svg';
-import UsersThreeIcon from '@phosphor/users-three.svg';
import WhatsappIcon from '@phosphor/whatsapp-logo.svg';
import { Button, ConfirmDialog, Tooltip } from '@ui';
import {
@@ -38,6 +41,7 @@ import {
Show,
} from 'solid-js';
import { match } from 'ts-pattern';
+import { ChatDetails } from '../components/chat-details';
import { InboundAttachmentPlaceholder } from '../components/inbound-attachment';
import {
InboundMedia,
@@ -179,6 +183,8 @@ function MessageMedia(props: {
kind: file.kind,
fileName: file.attachment.fileName,
url: url() ?? file.attachment.previewUrl,
+ unavailable:
+ !url() && !file.attachment.previewUrl && !!stored?.isError,
previewUrl: file.attachment.previewUrl,
width: file.attachment.width,
height: file.attachment.height,
@@ -204,6 +210,8 @@ export function WhatsAppGroupView(props: {
leading?: JSX.Element;
/** The Share control; the host owns the share dialog. */
share: JSX.Element;
+ /** Opens the host's share dialog from the details panel. */
+ onShare: () => void;
onConnect: () => void;
}) {
const source = useWhatsAppGroup();
@@ -223,11 +231,11 @@ export function WhatsAppGroupView(props: {
},
});
const [deleting, setDeleting] = createSignal<string>();
- const [roster, setRoster] = createSignal(false);
- const [stopping, setStopping] = createSignal(false);
+ const sidePanel = useSidePanel();
+ // The floating details card covers the right of the pane; where the pane
+ // is wide enough, the timeline and composer make room for it instead.
+ const detailsBeside = () => !isTouchDevice() && !!sidePanel?.isOpen();
const [stopped, setStopped] = createSignal(false);
- const [stopError, setStopError] = createSignal<string>();
- const [stopPending, setStopPending] = createSignal(false);
let scroller: HTMLDivElement | undefined;
let alive = true;
let newest: string | undefined;
@@ -372,11 +380,6 @@ export function WhatsAppGroupView(props: {
scroller.scrollTop =
scroller.scrollHeight - scroller.clientHeight - fromBottom;
});
- const memberLabel = () => {
- const count = source.group.data?.members.length;
- if (count === undefined) return 'Members';
- return count === 1 ? '1 member' : `${count} members`;
- };
const importing = () =>
backfillStatus(
source.group.data?.backfill,
@@ -487,8 +490,10 @@ export function WhatsAppGroupView(props: {
};
return (
- <div class="flex h-full min-h-0 min-w-0 flex-col bg-panel text-ink touch:pt-(--mobile-content-inset-top)">
- <header class="flex h-12 shrink-0 items-center gap-2 px-3 touch:px-(--mobile-chrome-gutter)">
+ <div class="flex h-full min-h-0 min-w-0 flex-col bg-panel text-ink">
+ {/* Desktop chrome is the view shell's top bar; touch keeps it as the
+ page header, below the safe area. */}
+ <ViewShell.TopBar class="touch:flex touch:h-auto touch:min-h-12 touch:px-(--mobile-chrome-gutter) touch:pt-[calc(var(--mobile-content-inset-top,var(--safe-top,0px))+0.75rem)]">
{props.leading}
<span
aria-hidden="true"
@@ -522,409 +527,444 @@ export function WhatsAppGroupView(props: {
<Show when={importing()}>{(status) => <> · {status()}</>}</Show>
</span>
</div>
- <div class="flex shrink-0 items-center gap-1">
- {/* A direct chat is the person in the title; it has no roster. */}
- <Show when={source.group.data?.kind !== 'direct'}>
- <HeaderActionButton
- label={memberLabel()}
- icon={<UsersThreeIcon />}
- tooltip="WhatsApp members"
- onClick={() => setRoster((value) => !value)}
- />
- </Show>
- {props.share}
+ <div class="ml-auto flex shrink-0 items-center gap-2 touch:gap-1">
+ <HeaderActionGroup label="Sharing">{props.share}</HeaderActionGroup>
+ <SidePanel.Toggle />
</div>
- </header>
- <Show when={roster() && source.group.data?.kind !== 'direct'}>
- <aside class="max-h-56 shrink-0 overflow-y-auto border-b border-edge-muted p-4">
- <h2 class="mb-2 text-sm font-medium">WhatsApp members</h2>
- <p class="mb-2 text-xs text-ink-muted">
- WhatsApp membership controls who can send. Share controls who can
- read in Macro.
- </p>
- <ul class="space-y-1 text-sm">
- <For each={source.group.data?.members}>
- {(member) => (
- <li>
- {member.name}
- {member.admin ? ' · Admin' : ''}
- </li>
- )}
- </For>
- </ul>
- <Show when={source.group.data?.accessLevel === 'owner'}>
- <Button
- class="mt-3"
- variant="outline"
- size="sm"
- disabled={stopped()}
- onClick={() => setStopping(true)}
- >
- {stopped() ? 'Syncing stopped' : 'Stop syncing'}
- </Button>
+ </ViewShell.TopBar>
+ {/* Members, sharing and syncing open in the generic floating side
+ panel over the timeline, like an email thread's details. */}
+ <div class="relative min-h-0 min-w-0 flex-1">
+ <SidePanel.Layout headerToggle={false} floating>
+ <Show when={source.group.data}>
+ {(group) => (
+ <ChatDetails
+ group={group()}
+ stopped={stopped()}
+ onShare={props.onShare}
+ onStopSync={async () => {
+ try {
+ await source.stopSync();
+ } catch {
+ toast.failure("Couldn't stop syncing. Try again.");
+ return false;
+ }
+ if (alive) setStopped(true);
+ return true;
+ }}
+ />
+ )}
</Show>
- </aside>
- </Show>
- <StaticMarkdownContext>
- <MaybeMessageActionDrawerManager>
- {/* Chat's thread list layout: a full-width scroller with Chat's
- custom scrollbar, rows in the centered message column. */}
- <div class="relative min-h-0 flex-1">
+ <div class="@container/whatsapp-chat size-full min-h-0 min-w-0">
<div
- ref={setScroller}
- class="scrollbar-hidden h-full overflow-y-auto overscroll-contain px-2 pb-4 [overflow-anchor:none] mobile:pb-(--mobile-content-inset-bottom)"
- role="log"
- aria-label="WhatsApp messages"
- onWheel={intent}
- onTouchMove={intent}
- onKeyDown={intent}
- onPointerDown={intent}
- onScroll={() => {
- if (!scroller) return;
- fromBottom =
- scroller.scrollHeight -
- scroller.scrollTop -
- scroller.clientHeight;
- if (Date.now() - intentAt < 1000) following = fromBottom < 80;
- if (fromBottom < 60) markRead();
+ style={{
+ '--details-clearance': `${detailsBeside() ? SidePanel.FLOATING_CLEARANCE_PX : 0}px`,
}}
+ class="flex size-full min-h-0 min-w-0 flex-col @min-[900px]/whatsapp-chat:pr-(--details-clearance)"
>
- <div class="flex w-full justify-center">
- <div
- ref={(content) => grown.observe(content)}
- class="macro-message-width relative"
- >
- <Show
- when={source.group.isPending || source.timeline.isPending}
- >
- <p role="status" class="p-6 text-sm text-ink-muted">
- Loading WhatsApp chat…
- </p>
- </Show>
- <Show when={source.group.isError || source.timeline.isError}>
- <div class="p-4 text-sm">
- <p role="alert">
- Couldn't load this chat. You may need access from its
- owner.
- </p>
- <Button
- variant="outline"
- size="sm"
- onClick={() => {
- source.group.refetch();
- source.timeline.refetch();
- }}
- >
- Try again
- </Button>
- </div>
- </Show>
- <Show when={source.hasOlder()}>
- <div class="flex justify-center p-3">
- <Button
- variant="ghost"
- size="sm"
- disabled={source.loadingOlder()}
- onClick={() =>
- fireAndForget(older(), 'whatsapp-group.older')
- }
- >
- {source.loadingOlder()
- ? 'Loading…'
- : 'Load earlier messages'}
- </Button>
- </div>
- </Show>
- <Show when={source.timeline.data && !source.hasOlder()}>
- <Show
- when={
- source.group.data && disappearingNote(source.group.data)
- }
+ <StaticMarkdownContext>
+ <MaybeMessageActionDrawerManager>
+ {/* Chat's thread list layout: a full-width scroller with Chat's
+ custom scrollbar, rows in the centered message column. */}
+ <div class="relative min-h-0 flex-1">
+ <div
+ ref={setScroller}
+ class="scrollbar-hidden h-full overflow-y-auto overscroll-contain px-2 pb-4 [overflow-anchor:none] mobile:pb-(--mobile-content-inset-bottom)"
+ role="log"
+ aria-label="WhatsApp messages"
+ onWheel={intent}
+ onTouchMove={intent}
+ onKeyDown={intent}
+ onPointerDown={intent}
+ onScroll={() => {
+ if (!scroller) return;
+ fromBottom =
+ scroller.scrollHeight -
+ scroller.scrollTop -
+ scroller.clientHeight;
+ if (Date.now() - intentAt < 1000)
+ following = fromBottom < 80;
+ if (fromBottom < 60) markRead();
+ }}
>
- {(note) => (
- <p class="p-3 text-center text-xs text-ink-muted">
- {note()}
- </p>
- )}
- </Show>
- <Show when={importing() ?? historyStart()}>
- {(note) => (
- <p
- role="status"
- class="p-3 text-center text-xs text-ink-muted"
- >
- {note()}
- </p>
- )}
- </Show>
- </Show>
- <Show
- when={
- source.timeline.data &&
- rows().length === 0 &&
- !importing()
- }
- >
- <p class="p-6 text-center text-sm text-ink-muted">
- No messages yet. New WhatsApp messages will appear here.
- </p>
- </Show>
- <For each={rows()}>
- {(message) => {
- const systemLine = () =>
- message.kind === 'system' &&
- message.rich?.type === 'system'
- ? message.rich
- : undefined;
- const meta = () =>
- listMeta()[
- message.kind === 'system'
- ? `activity:${message.id}`
- : message.id
- ];
- const quoted = () =>
- message.replyTo
- ? messagesById().get(message.replyTo)
- : undefined;
- const actions = actionsFor(message);
- const placeholders = () =>
- message.attachments.filter(
- (attachment) => attachment.state !== 'ready'
- );
- return (
- <Show
- when={message.kind !== 'system'}
- fallback={
- <>
- <DateDivider
- createdAt={message.sentAt}
- listMeta={meta()}
- />
- <Show when={systemLine()}>
- {(line) => (
- <WhatsAppSystemLine
- id={message.id}
- line={line()}
- occurredAt={message.sentAt}
- />
- )}
- </Show>
- </>
- }
+ <div class="flex w-full justify-center">
+ <div
+ ref={(content) => grown.observe(content)}
+ class="macro-message-width relative"
>
- <NewDivider
- createdAt={message.sentAt}
- listMeta={meta()}
- onDismiss={markRead}
- />
- <DateDivider
- createdAt={message.sentAt}
- listMeta={meta()}
- />
- <ChannelMessage
- parent={{
- type: 'whatsapp_group',
- id: source.group.data?.id ?? '',
- }}
- message={groupMessageData(message, props.userId)}
- actions={actions}
- listMeta={meta()}
- targeted={
- conversation.target()?.message.id === message.id
+ <Show
+ when={
+ source.group.isPending ||
+ source.timeline.isPending
}
- renderContent={(content) => (
- <>
- <Show
- when={!message.deleted && message.forwarded}
+ >
+ {/* The header already clears the top inset. */}
+ <div class="touch:[--mobile-content-inset-top:0px]">
+ <ChannelLoading />
+ </div>
+ </Show>
+ <Show
+ when={
+ source.group.isError || source.timeline.isError
+ }
+ >
+ <div class="p-4 text-sm">
+ <p role="alert">
+ Couldn't load this chat. You may need access
+ from its owner.
+ </p>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => {
+ source.group.refetch();
+ source.timeline.refetch();
+ }}
+ >
+ Try again
+ </Button>
+ </div>
+ </Show>
+ <Show when={source.hasOlder()}>
+ <div class="flex justify-center p-3">
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={source.loadingOlder()}
+ onClick={() =>
+ fireAndForget(older(), 'whatsapp-group.older')
+ }
+ >
+ {source.loadingOlder()
+ ? 'Loading…'
+ : 'Load earlier messages'}
+ </Button>
+ </div>
+ </Show>
+ <Show
+ when={source.timeline.data && !source.hasOlder()}
+ >
+ <Show
+ when={
+ source.group.data &&
+ disappearingNote(source.group.data)
+ }
+ >
+ {(note) => (
+ <p class="p-3 text-center text-xs text-ink-muted">
+ {note()}
+ </p>
+ )}
+ </Show>
+ <Show when={importing() ?? historyStart()}>
+ {(note) => (
+ <p
+ role="status"
+ class="p-3 text-center text-xs text-ink-muted"
>
- <ForwardedTag />
- </Show>
+ {note()}
+ </p>
+ )}
+ </Show>
+ </Show>
+ <Show
+ when={
+ source.timeline.data &&
+ rows().length === 0 &&
+ !importing()
+ }
+ >
+ <p class="p-6 text-center text-sm text-ink-muted">
+ No messages yet. New WhatsApp messages will appear
+ here.
+ </p>
+ </Show>
+ <For each={rows()}>
+ {(message) => {
+ const systemLine = () =>
+ message.kind === 'system' &&
+ message.rich?.type === 'system'
+ ? message.rich
+ : undefined;
+ const meta = () =>
+ listMeta()[
+ message.kind === 'system'
+ ? `activity:${message.id}`
+ : message.id
+ ];
+ const quoted = () =>
+ message.replyTo
+ ? messagesById().get(message.replyTo)
+ : undefined;
+ const actions = actionsFor(message);
+ const placeholders = () =>
+ message.attachments.flatMap((attachment) =>
+ attachment.state === 'ready'
+ ? []
+ : [
+ {
+ state: attachment.state,
+ fileName: attachment.fileName,
+ },
+ ]
+ );
+ return (
<Show
- when={!message.deleted && message.replyTo}
- >
- {(id) => (
- <button
- type="button"
- class="mb-1 block max-w-full truncate border-l-2 border-accent py-0.5 pl-3 text-left text-xs text-ink-muted"
- onClick={() =>
- fireAndForget(
- openQuoted(id()),
- 'whatsapp-group.quote'
- )
- }
- >
- <Show
- when={quoted()}
- fallback="View quoted message"
- >
- {(reply) => (
- <>
- <SenderName
- message={groupMessageData(
- reply(),
- props.userId
- )}
- />
- : {quotePreview(reply())}
- </>
+ when={message.kind !== 'system'}
+ fallback={
+ <>
+ <DateDivider
+ createdAt={message.sentAt}
+ listMeta={meta()}
+ />
+ <Show when={systemLine()}>
+ {(line) => (
+ <WhatsAppSystemLine
+ id={message.id}
+ line={line()}
+ chat={
+ source.group.data?.kind ?? 'group'
+ }
+ occurredAt={message.sentAt}
+ />
)}
</Show>
- </button>
- )}
- </Show>
- {content}
- <Show when={!message.deleted && message.rich}>
- {(rich) => <RichCard rich={rich()} />}
- </Show>
- <MessageMedia
- attachments={message.attachments}
- sent={conversation.sentFiles(message.id)}
- />
- <Show when={placeholders().length > 0}>
- <div class="mt-1 flex flex-wrap gap-2">
- <For each={placeholders()}>
- {(attachment) => (
- <InboundAttachmentPlaceholder
- attachment={attachment}
+ </>
+ }
+ >
+ <NewDivider
+ createdAt={message.sentAt}
+ listMeta={meta()}
+ onDismiss={markRead}
+ />
+ <DateDivider
+ createdAt={message.sentAt}
+ listMeta={meta()}
+ />
+ <ChannelMessage
+ timestampFormat="time"
+ message={groupMessageData(
+ message,
+ props.userId
+ )}
+ actions={actions}
+ listMeta={meta()}
+ targeted={
+ conversation.target()?.message.id ===
+ message.id
+ }
+ renderContent={(content) => (
+ <>
+ <Show
+ when={
+ !message.deleted &&
+ message.forwarded
+ }
+ >
+ <ForwardedTag />
+ </Show>
+ <Show
+ when={
+ !message.deleted && message.replyTo
+ }
+ >
+ {(id) => (
+ <button
+ type="button"
+ class="mb-1 block max-w-full truncate border-l-2 border-accent py-0.5 pl-3 text-left text-xs text-ink-muted"
+ onClick={() =>
+ fireAndForget(
+ openQuoted(id()),
+ 'whatsapp-group.quote'
+ )
+ }
+ >
+ <Show
+ when={quoted()}
+ fallback="View quoted message"
+ >
+ {(reply) => (
+ <>
+ <SenderName
+ message={groupMessageData(
+ reply(),
+ props.userId
+ )}
+ />
+ : {quotePreview(reply())}
+ </>
+ )}
+ </Show>
+ </button>
+ )}
+ </Show>
+ {content}
+ <Show
+ when={
+ !message.deleted && message.rich
+ }
+ >
+ {(rich) => <RichCard rich={rich()} />}
+ </Show>
+ <MessageMedia
+ attachments={message.attachments}
+ sent={conversation.sentFiles(
+ message.id
+ )}
/>
- )}
- </For>
- </div>
+ <Show when={placeholders().length > 0}>
+ <div class="mt-1 flex flex-wrap gap-2">
+ <For each={placeholders()}>
+ {(attachment) => (
+ <InboundAttachmentPlaceholder
+ state={attachment.state}
+ fileName={attachment.fileName}
+ />
+ )}
+ </For>
+ </div>
+ </Show>
+ </>
+ )}
+ />
</Show>
- </>
- )}
- />
- </Show>
- );
- }}
- </For>
- </div>
- </div>
- </div>
- <CustomScrollbar
- scrollContainer={scrollerElement}
- watchContent
- onScrollIntent={intent}
- />
- </div>
- </MaybeMessageActionDrawerManager>
- </StaticMarkdownContext>
- <Show when={source.group.data}>
- {(group) => (
- <FloatRegionOrInline region="accessory">
- <Show
- when={group().canSend && !stopped()}
- fallback={
- <ChannelInputContainer>
- <div class="macro-message-width flex shrink-0 flex-wrap items-center gap-2 border-t border-edge-muted px-4 pt-3 text-sm text-ink-muted touch:rounded-2xl touch:border-0 touch:island touch:px-3 touch:py-2">
- <span role="status">
- {stopped()
- ? 'This chat is no longer syncing'
- : composerNote(
- group(),
- getDisplayName(tryMacroId(group().ownerId)) ||
- undefined
- )}
- </span>
+ );
+ }}
+ </For>
+ </div>
+ </div>
+ </div>
+ <CustomScrollbar
+ scrollContainer={scrollerElement}
+ watchContent
+ onScrollIntent={intent}
+ />
+ </div>
+ </MaybeMessageActionDrawerManager>
+ </StaticMarkdownContext>
+ <Show when={source.group.data}>
+ {(group) => (
+ <FloatRegionOrInline region="accessory">
<Show
- when={
- group().sendReason === 'no_account' ||
- group().sendReason === 'disconnected'
+ when={group().canSend && !stopped()}
+ fallback={
+ <ChannelInputContainer>
+ <div class="macro-message-width flex shrink-0 flex-wrap items-center gap-2 border-t border-edge-muted px-4 pt-3 text-sm text-ink-muted touch:rounded-2xl touch:border-0 touch:island touch:px-3 touch:py-2">
+ <span role="status">
+ {stopped()
+ ? 'This chat is no longer syncing'
+ : composerNote(
+ group(),
+ getDisplayName(
+ tryMacroId(group().ownerId)
+ ) || undefined
+ )}
+ </span>
+ <Show
+ when={
+ group().sendReason === 'no_account' ||
+ group().sendReason === 'disconnected'
+ }
+ >
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={props.onConnect}
+ >
+ Connect WhatsApp
+ </Button>
+ </Show>
+ </div>
+ </ChannelInputContainer>
}
>
- <Button
- variant="outline"
- size="sm"
- onClick={props.onConnect}
- >
- Connect WhatsApp
- </Button>
- </Show>
- </div>
- </ChannelInputContainer>
- }
- >
- <ChannelInputContainer>
- <div
- data-keep-keyboard
- class="relative flex w-full flex-col items-center gap-1"
- >
- <Show when={conversation.target()}>
- {(target) => (
- <InputFlag
- label={
- target().kind === 'edit' ? (
- 'Editing message'
- ) : (
- <>
- Replying to{' '}
- <SenderName
- message={groupMessageData(
- target().message,
- props.userId
- )}
+ <ChannelInputContainer>
+ <div
+ data-keep-keyboard
+ class="relative flex w-full flex-col items-center gap-1"
+ >
+ <Show when={conversation.target()}>
+ {(target) => (
+ <InputFlag
+ label={
+ target().kind === 'edit' ? (
+ 'Editing message'
+ ) : (
+ <>
+ Replying to{' '}
+ <SenderName
+ message={groupMessageData(
+ target().message,
+ props.userId
+ )}
+ />
+ </>
+ )
+ }
+ onActivate={() =>
+ fireAndForget(
+ openQuoted(target().message.id),
+ 'whatsapp-group.quote'
+ )
+ }
+ dismissLabel={
+ target().kind === 'edit'
+ ? 'Cancel edit'
+ : 'Cancel reply'
+ }
+ onDismiss={() => setTarget(undefined)}
/>
- </>
- )
- }
- onActivate={() =>
- fireAndForget(
- openQuoted(target().message.id),
- 'whatsapp-group.quote'
- )
- }
- dismissLabel={
- target().kind === 'edit'
- ? 'Cancel edit'
- : 'Cancel reply'
- }
- onDismiss={() => setTarget(undefined)}
- />
- )}
- </Show>
- <ChannelInput
- input={{
- mode: 'channel',
- id: `whatsapp-group-input-${group().id}`,
- placeholder: composerPlaceholder(group()),
- }}
- features={WHATSAPP_COMPOSER}
- participants={() => mentionable(group())}
- fileAccept={group().limits.attachmentTypes.join(',')}
- uploadAttachment={async (file) => {
- const result = await conversation.upload(file);
- return result.isOk()
- ? {
- failed: false,
- destination: 'staged',
- id: result.value.uploadId,
- }
- : { failed: true, reason: result.error };
- }}
- onReady={(handle) => {
- input = handle;
- }}
- onChange={setInputSnapshot}
- onSend={send}
- onSendError={(error) =>
- toast.failure(
- error instanceof DraftRefusal
- ? error.message
- : "Couldn't send to WhatsApp. Try again."
- )
- }
- onEscape={
- conversation.target()
- ? () => setTarget(undefined)
- : undefined
- }
- />
- </div>
- </ChannelInputContainer>
- </Show>
- </FloatRegionOrInline>
- )}
- </Show>
+ )}
+ </Show>
+ <ChannelInput
+ input={{
+ mode: 'channel',
+ id: `whatsapp-group-input-${group().id}`,
+ placeholder: composerPlaceholder(group()),
+ }}
+ features={WHATSAPP_COMPOSER}
+ participants={() => mentionable(group())}
+ fileAccept={group().limits.attachmentTypes.join(
+ ','
+ )}
+ uploadAttachment={async (file) => {
+ const result = await conversation.upload(file);
+ return result.isOk()
+ ? {
+ failed: false,
+ destination: 'staged',
+ id: result.value.uploadId,
+ }
+ : { failed: true, reason: result.error };
+ }}
+ onReady={(handle) => {
+ input = handle;
+ }}
+ onChange={setInputSnapshot}
+ onSend={send}
+ onSendError={(error) =>
+ toast.failure(
+ error instanceof DraftRefusal
+ ? error.message
+ : "Couldn't send to WhatsApp. Try again."
+ )
+ }
+ onEscape={
+ conversation.target()
+ ? () => setTarget(undefined)
+ : undefined
+ }
+ />
+ </div>
+ </ChannelInputContainer>
+ </Show>
+ </FloatRegionOrInline>
+ )}
+ </Show>
+ </div>
+ </div>
+ </SidePanel.Layout>
+ </div>
<ConfirmDialog
open={!!deleting()}
onOpenChange={(open) => {
@@ -940,33 +980,6 @@ export function WhatsAppGroupView(props: {
if (id) await conversation.remove(id);
}}
/>
- <ConfirmDialog
- open={stopping()}
- onOpenChange={setStopping}
- title="Stop syncing this chat?"
- body="Its history stays in Macro. New messages will stop syncing."
- confirmLabel="Stop syncing"
- tone="danger"
- pending={stopPending()}
- onConfirm={async () => {
- setStopPending(true);
- try {
- await source.stopSync();
- if (!alive) return;
- setStopped(true);
- setStopping(false);
- } catch {
- if (alive) setStopError("Couldn't stop syncing. Try again.");
- } finally {
- if (alive) setStopPending(false);
- }
- }}
- />
- <Show when={stopError()}>
- <p role="alert" class="p-2 text-xs text-failure-ink">
- {stopError()}
- </p>
- </Show>
</div>
);
}
diff --git a/apps/web/src/features/whatsapp-group/whatsapp-group-entry.tsx b/apps/web/src/features/whatsapp-group/whatsapp-group-entry.tsx
index cd4174a917..6303a642dc 100644
--- a/apps/web/src/features/whatsapp-group/whatsapp-group-entry.tsx
+++ b/apps/web/src/features/whatsapp-group/whatsapp-group-entry.tsx
@@ -1,17 +1,35 @@
+import { ListSkeleton } from '@app/components/view-shell/ListSkeleton';
+import { ViewSkeleton } from '@app/components/view-shell/ViewSkeleton';
import { useFeatureFlag } from '@app/lib/analytics/posthog';
import { useNavigate } from '@app/lib/split-router';
import { homeSplitRoute } from '@app/routes/routes';
+import { ChannelLoading } from '@channel/Channel/ChannelLoading';
import { enableWhatsappLinked } from '@core/constant/featureFlags';
import { type JSX, lazy, onMount, Show, Suspense } from 'solid-js';
const Group = lazy(async () => ({
default: (await import('./whatsapp-group')).WhatsAppGroup,
}));
+/** The chat's header (badge, name, Share, details toggle) over Chat's loading rows. */
export function WhatsAppGroupSkeleton() {
return (
- <p role="status" class="p-6 text-sm text-ink-muted">
- Loading WhatsApp chat…
- </p>
+ <div class="flex h-full min-h-0 min-w-0 flex-col bg-panel">
+ <div
+ aria-hidden="true"
+ class="flex h-12 shrink-0 items-center gap-2 px-3 touch:h-auto touch:min-h-12 touch:px-(--mobile-chrome-gutter) touch:pt-[calc(var(--mobile-content-inset-top,var(--safe-top,0px))+0.75rem)]"
+ >
+ <ListSkeleton.Bar class="size-5 shrink-0" />
+ <ListSkeleton.Bar class="w-32" />
+ <div class="ml-auto flex shrink-0 items-center gap-2">
+ <ViewSkeleton.Control control="Share" />
+ <ViewSkeleton.Control control={1} />
+ </div>
+ </div>
+ {/* The header above already clears the top inset. */}
+ <div class="flex min-h-0 flex-1 flex-col touch:[--mobile-content-inset-top:0px]">
+ <ChannelLoading />
+ </div>
+ </div>
);
}
function DisabledGroup() {
diff --git a/apps/web/src/features/whatsapp-group/whatsapp-group.tsx b/apps/web/src/features/whatsapp-group/whatsapp-group.tsx
index 8b77230c63..2b34fa04e6 100644
--- a/apps/web/src/features/whatsapp-group/whatsapp-group.tsx
+++ b/apps/web/src/features/whatsapp-group/whatsapp-group.tsx
@@ -1,10 +1,10 @@
import { useNavigate } from '@app/lib/split-router';
import { externalRoute } from '@app/routes/routes';
+import { SidePanel } from '@components/app/side-panel';
import {
useSplitDisplayName,
useSplitPanel,
} from '@components/app/split-layout/layoutUtils';
-import { SplitPanel } from '@components/app/split-panel';
import { getPermissions } from '@core/component/SharePermissions';
import { ShareTrigger } from '@core/component/TopBar/ShareButton';
import { useShareModal } from '@core/component/TopBar/shareModal';
@@ -43,19 +43,24 @@ export function WhatsAppGroup(props: {
});
return (
<WhatsAppGroupProvider value={source}>
- <WhatsAppGroupView
- leading={props.leading ?? <SplitPanel.CloseButton class="shrink-0" />}
- userId={userId()}
- share={
- <ShareTrigger
- onClick={share}
- id={props.groupId}
- blockType="whatsapp_group"
- hotkeyScope={panel?.splitHotkeyScope}
- />
- }
- onConnect={() => navigate({ route: externalRoute, params: {} })}
- />
+ {/* Like an in-view email thread: the details panel floats over the
+ conversation and starts closed. */}
+ <SidePanel.Root floating defaultOpen={false}>
+ <WhatsAppGroupView
+ leading={props.leading}
+ userId={userId()}
+ share={
+ <ShareTrigger
+ onClick={share}
+ id={props.groupId}
+ blockType="whatsapp_group"
+ hotkeyScope={panel?.splitHotkeyScope}
+ />
+ }
+ onShare={share}
+ onConnect={() => navigate({ route: externalRoute, params: {} })}
+ />
+ </SidePanel.Root>
</WhatsAppGroupProvider>
);
}
diff --git a/apps/web/src/features/whatsapp-linked/AGENTS.md b/apps/web/src/features/whatsapp-linked/AGENTS.md
index 658ba473aa..1d04e90628 100644
--- a/apps/web/src/features/whatsapp-linked/AGENTS.md
+++ b/apps/web/src/features/whatsapp-linked/AGENTS.md
@@ -11,8 +11,13 @@ own shareable Macro entity. Each person sends from their own account. Behind the
- `whatsapp-linked.tsx`: production wiring (shared queries + split navigation).
- `context/whatsapp-linked-context.tsx`: the capability contract tests fake.
- `views/whatsapp-page.tsx`: account states, the header (search + account
- strip), the Add to Macro and Can't be added sections (plus In Macro while
- searching), and the pairing/confirm dialogs.
+ strip), the chat sections and Can't be added, and the pairing/confirm
+ dialogs.
+- `components/conversation-sections.tsx` + `core/chat.ts`
+ `conversationSections`: Direct messages / Groups / one section per
+ community, on view-shell's `CollapsibleSection` (what Chat's rail uses);
+ External's sidebar renders the same sections. Open state is
+ `primitives/open-sections.ts`, per user.
- `components/chat-list.tsx`: one-line chat rows styled like Macro's list rows
(`bg-list-hover`, actions on hover/focus, always on touch).
- `core/chat.ts`: chat sections, search matching and row wording.
@@ -41,6 +46,12 @@ own shareable Macro entity. Each person sends from their own account. Behind the
- The QR is encoded locally with `uqr`; never send the value to an image service.
- `core/pairing.ts` matches DSS's pairing states exhaustively; a new state
must be handled there, not fall through to "preparing".
+- `primitives/pairing-flow.ts` replaces an expired pairing on its own (like
+ WhatsApp Web) only when the server says `expired`, the tab stayed visible,
+ and fewer than `AUTO_ROLLS` codes rolled since the last click; otherwise the
+ QR square offers **Show a new code**. A pairing that arrives after Cancel is
+ cancelled at once.
+- Disconnect results are toasts, not page state.
- Wire types come from DSS's generated `@service-storage/generated/schemas`
(`Linked*`); change `crates/whatsapp_linked` and regenerate, never hand-type.
- Adoption failures carry DSS's `LinkedError` code (`whatsappErrorResponse`);
@@ -48,7 +59,8 @@ own shareable Macro entity. Each person sends from their own account. Behind the
- The chat list (`GET /meta/linked/chats`) arrives sorted by recent activity;
keep DSS's order. Sections follow its `group`/`shared`/`canAdd`/
`cannotAddReason` fields; direct chats are addable, except the chat with
- yourself.
+ yourself. DSS sends reason codes (`cannotAddReason`, and
+ `cannot_add_<reason>` on a refused add); `core/chat.ts` words them.
User-facing copy says "chat", not "group". Community groups show as "Community · Group"
(`communityTitle`); disappearing and community groups are addable, a
community itself is not.
diff --git a/apps/web/src/features/whatsapp-linked/components/account-card.tsx b/apps/web/src/features/whatsapp-linked/components/account-card.tsx
index a2bb8d8d40..852710083b 100644
--- a/apps/web/src/features/whatsapp-linked/components/account-card.tsx
+++ b/apps/web/src/features/whatsapp-linked/components/account-card.tsx
@@ -2,12 +2,18 @@ import DotsThreeIcon from '@phosphor/dots-three.svg';
import LinkBreakIcon from '@phosphor/link-break.svg';
import WhatsappIcon from '@phosphor/whatsapp-logo.svg';
import { Button, Dropdown, Item } from '@ui';
+import { Show } from 'solid-js';
import type { WhatsAppAccount } from '../core/account';
import { WhatsAppTile } from './whatsapp-tile';
-/** Nothing linked yet: what linking means, its risk, and Connect. */
+/**
+ * Nothing linked yet: what linking means, its risk, and Connect. A phone
+ * can't scan its own screen, so on one it says to link from a computer.
+ */
export function ConnectCard(props: {
reconnect: boolean;
+ /** This is the phone that would have to scan the code. */
+ phone: boolean;
/** Pairing is switched off on the server. */
unavailable: boolean;
pending: boolean;
@@ -27,20 +33,28 @@ export function ConnectCard(props: {
Macro connects as an unofficial WhatsApp client, which WhatsApp may
restrict or ban accounts for.
</Item.Metadata>
+ <Show when={props.phone}>
+ <Item.Description>
+ To link, open Macro on a computer, go to External → WhatsApp, and
+ scan the code it shows with this phone.
+ </Item.Description>
+ </Show>
</Item.Content>
- <Item.Actions class="self-center">
- <Button
- type="button"
- variant="strong"
- disabled={props.unavailable || props.pending}
- tooltip={
- props.unavailable ? 'Linking WhatsApp is turned off' : undefined
- }
- onClick={props.onConnect}
- >
- {props.reconnect ? 'Reconnect' : 'Connect'}
- </Button>
- </Item.Actions>
+ <Show when={!props.phone}>
+ <Item.Actions class="self-center">
+ <Button
+ type="button"
+ variant="strong"
+ disabled={props.unavailable || props.pending}
+ tooltip={
+ props.unavailable ? 'Linking WhatsApp is turned off' : undefined
+ }
+ onClick={props.onConnect}
+ >
+ {props.reconnect ? 'Reconnect' : 'Connect'}
+ </Button>
+ </Item.Actions>
+ </Show>
</Item>
);
}
diff --git a/apps/web/src/features/whatsapp-linked/components/chat-list.tsx b/apps/web/src/features/whatsapp-linked/components/chat-list.tsx
index d2532eb735..1af8c9fb96 100644
--- a/apps/web/src/features/whatsapp-linked/components/chat-list.tsx
+++ b/apps/web/src/features/whatsapp-linked/components/chat-list.tsx
@@ -1,30 +1,18 @@
-import { formatRelativeDate } from '@core/util/time';
-import CaretDownIcon from '@phosphor/caret-down.svg';
import MegaphoneIcon from '@phosphor/megaphone-simple.svg';
import PlusIcon from '@phosphor/plus.svg';
import UserIcon from '@phosphor/user.svg';
import UsersThreeIcon from '@phosphor/users-three.svg';
import { Button, cn } from '@ui';
-import { CollapseTransition } from '@ui/components/CollapseTransition';
import { createSignal, For, type JSX, Match, Show, Switch } from 'solid-js';
import {
cannotAddLabel,
chatMetadata,
communityTitle,
+ formatActivityDate,
+ nameInCommunity,
type WhatsAppChat,
} from '../core/chat';
-
-/** A list heading, on the same 16px rail as the rows' icons. */
-export function ChatSectionHeading(props: { id: string; children: string }) {
- return (
- <h2
- id={props.id}
- class="px-4 pt-4 pb-1 text-xs font-semibold tracking-tight text-ink-extra-muted"
- >
- {props.children}
- </h2>
- );
-}
+import { ConversationSection } from './conversation-sections';
/**
* One line per chat, like Macro's other lists: icon, name, muted kind and
@@ -33,6 +21,8 @@ export function ChatSectionHeading(props: { id: string; children: string }) {
*/
function ChatRow(props: {
chat: WhatsAppChat;
+ /** Under its community's heading a group goes by its own name. */
+ inCommunity?: boolean;
actions?: JSX.Element;
status?: JSX.Element;
error?: string;
@@ -41,7 +31,7 @@ function ChatRow(props: {
}) {
return (
<div
- class="group/chat mx-2 flex min-h-9 min-w-0 items-center gap-2 rounded-xl px-2 text-sm hover:bg-list-hover focus-within:bg-list-hover touch:min-h-11"
+ class="group/chat mx-2 flex min-h-9 min-w-0 items-center gap-2 rounded-xl px-2 text-sm not-touch:hover:bg-list-hover focus-within:bg-list-hover touch:min-h-11"
data-whatsapp-chat={props.chat.jid}
data-whatsapp-chat-kind={props.chat.kind}
>
@@ -56,7 +46,9 @@ function ChatRow(props: {
</Switch>
</span>
<span class="ph-no-capture min-w-0 shrink truncate font-medium text-ink">
- {communityTitle(props.chat.name, props.chat.community)}
+ {props.inCommunity
+ ? nameInCommunity(props.chat)
+ : communityTitle(props.chat.name, props.chat.community)}
</span>
<span class="min-w-0 shrink-[2] truncate text-xs text-ink-extra-muted">
{chatMetadata(props.chat)}
@@ -75,7 +67,7 @@ function ChatRow(props: {
<Show when={props.actions}>
<span
class={cn(
- 'flex items-center gap-1 opacity-0 group-hover/chat:opacity-100 group-focus-within/chat:opacity-100 touch:opacity-100',
+ 'flex items-center gap-1 opacity-0 not-touch:group-hover/chat:opacity-100 group-focus-within/chat:opacity-100 touch:opacity-100',
(props.pinActions || props.error) && 'opacity-100'
)}
>
@@ -86,9 +78,9 @@ function ChatRow(props: {
{(at) => (
<time
dateTime={at()}
- class="w-[8ch] shrink-0 text-right text-xs text-ink-extra-muted touch:hidden"
+ class="shrink-0 whitespace-nowrap text-right text-xs tabular-nums text-ink-extra-muted touch:hidden"
>
- {formatRelativeDate(at())}
+ {formatActivityDate(at())}
</time>
)}
</Show>
@@ -97,72 +89,35 @@ function ChatRow(props: {
);
}
-/** Chats this viewer already added; they also live in External's sidebar. */
-export function InMacroChatList(props: {
- chats: WhatsAppChat[];
- onOpenGroup: (groupId: string) => void;
-}) {
- return (
- <ul class="flex flex-col" aria-label="WhatsApp chats in Macro">
- <For each={props.chats}>
- {(chat) => (
- <li>
- <ChatRow
- chat={chat}
- actions={
- <Show
- when={chat.inMacro?.kind === 'own' ? chat.inMacro : undefined}
- >
- {(own) => (
- <Button
- type="button"
- variant="ghost"
- size="sm"
- onClick={() => props.onOpenGroup(own().groupId)}
- >
- Open
- </Button>
- )}
- </Show>
- }
- />
- </li>
- )}
- </For>
- </ul>
- );
-}
-
/**
- * Chats the viewer can bring into Macro with one click, and ones someone
- * already shared with them.
+ * One section's chats: ones to add with one click, ones someone shared with
+ * the viewer, and (while searching) the viewer's own added ones, each with
+ * the action that fits.
*/
-export function AddableChatList(props: {
+export function ChatList(props: {
+ label: string;
chats: WhatsAppChat[];
+ inCommunity?: boolean;
canAdd: boolean;
/** JIDs whose add is in flight. */
adding: ReadonlySet<string>;
errors: Readonly<Record<string, string>>;
- /** Shown when nothing is left to add. */
- empty: string;
onAdd: (chat: WhatsAppChat) => void;
onOpenGroup: (groupId: string) => void;
}) {
return (
- <ul class="flex flex-col" aria-label="Chats to add to Macro">
- <For
- each={props.chats}
- fallback={
- <li class="px-4 py-2 text-sm text-ink-extra-muted">{props.empty}</li>
- }
- >
+ <ul class="flex flex-col" aria-label={props.label}>
+ <For each={props.chats}>
{(chat) => {
const shared = () =>
chat.inMacro?.kind === 'shared' ? chat.inMacro : undefined;
+ const own = () =>
+ chat.inMacro?.kind === 'own' ? chat.inMacro : undefined;
return (
<li>
<ChatRow
chat={chat}
+ inCommunity={props.inCommunity}
error={props.errors[chat.jid]}
pinActions={props.adding.has(chat.jid)}
status={
@@ -200,6 +155,18 @@ export function AddableChatList(props: {
</Button>
}
>
+ <Match when={own()}>
+ {(mine) => (
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={() => props.onOpenGroup(mine().groupId)}
+ >
+ Open
+ </Button>
+ )}
+ </Match>
<Match when={shared()}>
{(by) => (
<Button
@@ -231,25 +198,13 @@ export function UnsupportedChatList(props: {
forceOpen: boolean;
}) {
const [open, setOpen] = createSignal(false);
- const expanded = () => open() || props.forceOpen;
return (
- <section class="flex flex-col">
- <button
- type="button"
- aria-expanded={expanded()}
- class="flex items-center gap-1 px-4 pt-4 pb-1 text-left text-xs font-semibold tracking-tight text-ink-extra-muted hover:text-ink"
- onClick={() => setOpen((value) => !value)}
+ <div class="px-2 pt-3">
+ <ConversationSection
+ title={`Can't be added (${props.chats.length})`}
+ open={open() || props.forceOpen}
+ onOpenChange={setOpen}
>
- Can't be added ({props.chats.length})
- <CaretDownIcon
- aria-hidden="true"
- class={cn(
- 'size-2.5 transition-transform',
- !expanded() && '-rotate-90'
- )}
- />
- </button>
- <CollapseTransition open={expanded()}>
<ul class="flex flex-col" aria-label="Can't be added">
<For each={props.chats}>
{(chat) => (
@@ -259,7 +214,7 @@ export function UnsupportedChatList(props: {
)}
</For>
</ul>
- </CollapseTransition>
- </section>
+ </ConversationSection>
+ </div>
);
}
diff --git a/apps/web/src/features/whatsapp-linked/components/conversation-sections.tsx b/apps/web/src/features/whatsapp-linked/components/conversation-sections.tsx
new file mode 100644
index 0000000000..afaf800fc9
--- /dev/null
+++ b/apps/web/src/features/whatsapp-linked/components/conversation-sections.tsx
@@ -0,0 +1,118 @@
+import { CollapsibleSection } from '@app/components/view-shell';
+import UsersFourIcon from '@phosphor/users-four.svg';
+import { For, type JSX, Show } from 'solid-js';
+import type { ChatCommunity, ConversationSections } from '../core/chat';
+
+/**
+ * A folding heading over a run of chats, on the same sidebar section Chat's
+ * rail and the other view sidebars use.
+ */
+export function ConversationSection(props: {
+ title: string;
+ icon?: JSX.Element;
+ /** Beside the heading, e.g. the unread count while folded. */
+ trailing?: JSX.Element;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ children: JSX.Element;
+}) {
+ return (
+ <CollapsibleSection.Root
+ open={props.open}
+ onOpenChange={props.onOpenChange}
+ >
+ <CollapsibleSection.Header>
+ <CollapsibleSection.Trigger class="flex-1">
+ {props.icon}
+ <span class="min-w-0 truncate">{props.title}</span>
+ <CollapsibleSection.Indicator />
+ </CollapsibleSection.Trigger>
+ {props.trailing}
+ </CollapsibleSection.Header>
+ <CollapsibleSection.Content>{props.children}</CollapsibleSection.Content>
+ </CollapsibleSection.Root>
+ );
+}
+
+/** Section ids, stable across sessions for the remembered open state. */
+export const sectionId = {
+ direct: 'direct',
+ groups: 'groups',
+ communities: 'communities',
+ community: (community: ChatCommunity) => `community:${community.id}`,
+};
+
+/**
+ * Direct messages, Groups, then Communities with one folding section per
+ * community; empty sections don't show. `list` renders one section's items.
+ */
+export function ConversationSectionList<Item>(props: {
+ sections: ConversationSections<Item>;
+ isOpen: (sectionId: string) => boolean;
+ onOpenChange: (sectionId: string, open: boolean) => void;
+ list: (items: Item[], label: string) => JSX.Element;
+ /** Beside a folded section's heading, e.g. its unread count. */
+ folded?: (items: Item[]) => JSX.Element;
+}) {
+ const section = (id: string, title: string, items: Item[]) => (
+ <Show when={items.length}>
+ <ConversationSection
+ title={title}
+ open={props.isOpen(id)}
+ onOpenChange={(open) => props.onOpenChange(id, open)}
+ trailing={props.isOpen(id) ? undefined : props.folded?.(items)}
+ >
+ {props.list(items, title)}
+ </ConversationSection>
+ </Show>
+ );
+ return (
+ <>
+ {section(sectionId.direct, 'Direct messages', props.sections.direct)}
+ {section(sectionId.groups, 'Groups', props.sections.groups)}
+ <Show when={props.sections.communities.length}>
+ <ConversationSection
+ title="Communities"
+ open={props.isOpen(sectionId.communities)}
+ onOpenChange={(open) =>
+ props.onOpenChange(sectionId.communities, open)
+ }
+ trailing={
+ props.isOpen(sectionId.communities)
+ ? undefined
+ : props.folded?.(
+ props.sections.communities.flatMap(({ items }) => items)
+ )
+ }
+ >
+ <For each={props.sections.communities}>
+ {({ community, items }) => (
+ <div class="pl-(--sidebar-item-inset)">
+ <ConversationSection
+ title={community.name}
+ icon={
+ <UsersFourIcon
+ aria-hidden="true"
+ class="size-3.5 shrink-0"
+ />
+ }
+ open={props.isOpen(sectionId.community(community))}
+ onOpenChange={(open) =>
+ props.onOpenChange(sectionId.community(community), open)
+ }
+ trailing={
+ props.isOpen(sectionId.community(community))
+ ? undefined
+ : props.folded?.(items)
+ }
+ >
+ {props.list(items, community.name)}
+ </ConversationSection>
+ </div>
+ )}
+ </For>
+ </ConversationSection>
+ </Show>
+ </>
+ );
+}
diff --git a/apps/web/src/features/whatsapp-linked/components/pairing-dialog.tsx b/apps/web/src/features/whatsapp-linked/components/pairing-dialog.tsx
index 110103fd6c..b6ae6c72c1 100644
--- a/apps/web/src/features/whatsapp-linked/components/pairing-dialog.tsx
+++ b/apps/web/src/features/whatsapp-linked/components/pairing-dialog.tsx
@@ -1,7 +1,8 @@
import { ActionDialogShell, Button, Dialog } from '@ui';
-import { For, Match, Show, Switch } from 'solid-js';
+import { For, type JSX, Match, Show, Switch } from 'solid-js';
+import { match } from 'ts-pattern';
import type { PasskeyCeremony } from '../context/whatsapp-linked-context';
-import { formatCountdown, type PairingStep } from '../core/pairing';
+import type { PairingStep } from '../core/pairing';
import { ConnectionCode } from './connection-code';
const STEPS = [
@@ -11,35 +12,50 @@ const STEPS = [
'Point your phone at this code',
];
+/** A square the size of the QR, so the dialog keeps its layout between codes. */
+function CodeBox(props: { children: JSX.Element; role?: 'status' }) {
+ return (
+ <div
+ role={props.role}
+ class="flex size-56 flex-col items-center justify-center gap-3 rounded-xl border border-edge-muted text-sm text-ink-muted"
+ >
+ {props.children}
+ </div>
+ );
+}
+
function CodeSlot(props: {
qr: string | undefined;
- secondsLeft: number | undefined;
+ refreshing: boolean;
+ expired: boolean;
+ onRetry: () => void;
}) {
return (
- <div class="flex flex-col items-center gap-2">
- <Show
- when={props.qr}
+ <div class="flex flex-col items-center">
+ <Switch
fallback={
- <div
- role="status"
- class="flex size-56 items-center justify-center rounded-xl border border-edge-muted text-sm text-ink-muted"
- >
- Preparing code…
- </div>
+ <CodeBox role="status">
+ {props.refreshing ? 'Refreshing code…' : 'Preparing code…'}
+ </CodeBox>
}
>
- {(qr) => (
- <ConnectionCode
- value={qr()}
- label="Scan this code with WhatsApp on your phone"
- />
- )}
- </Show>
- <p class="h-4 text-xs text-ink-subtle">
- <Show when={props.qr ? props.secondsLeft : undefined}>
- {(seconds) => <>Expires in {formatCountdown(seconds())}</>}
- </Show>
- </p>
+ <Match when={props.qr}>
+ {(qr) => (
+ <ConnectionCode
+ value={qr()}
+ label="Scan this code with WhatsApp on your phone"
+ />
+ )}
+ </Match>
+ <Match when={props.expired}>
+ <CodeBox>
+ <p role="status">Code expired</p>
+ <Button type="button" variant="strong" onClick={props.onRetry}>
+ Show a new code
+ </Button>
+ </CodeBox>
+ </Match>
+ </Switch>
</div>
);
}
@@ -164,6 +180,31 @@ function PasskeyStep(props: {
);
}
+function description(step: PairingStep): string {
+ return match(step)
+ .with(
+ { kind: 'preparing' },
+ { kind: 'scan' },
+ { kind: 'expired' },
+ () => 'Scan this code with the phone that has your WhatsApp account.'
+ )
+ .with(
+ { kind: 'code' },
+ () => 'Enter this code on the phone that has your WhatsApp account.'
+ )
+ .with(
+ { kind: 'passkey' },
+ () => 'WhatsApp wants to confirm it’s you before linking.'
+ )
+ .with({ kind: 'connected' }, () => 'Your phone linked WhatsApp to Macro.')
+ .with(
+ { kind: 'failed' },
+ { kind: 'cancelled' },
+ () => 'Get a new code to try again.'
+ )
+ .exhaustive();
+}
+
/**
* Linking WhatsApp as a device. Pairing material stays inside this
* `ph-no-capture` dialog, out of session replay.
@@ -171,7 +212,10 @@ function PasskeyStep(props: {
export function PairingDialog(props: {
open: boolean;
step: PairingStep;
- secondsLeft: number | undefined;
+ /** A code expired and its replacement is on its way. */
+ refreshing: boolean;
+ /** Asking for a new code failed; the last step stays up. */
+ retryFailed: boolean;
passkey: PasskeyMode;
ceremony: PasskeyCeremony;
onConfirmPasskey: () => void;
@@ -196,20 +240,28 @@ export function PairingDialog(props: {
<ActionDialogShell.Header>
<ActionDialogShell.Title>Link WhatsApp</ActionDialogShell.Title>
<ActionDialogShell.Description>
- {props.step.kind === 'passkey'
- ? 'WhatsApp wants to confirm it’s you before linking.'
- : props.step.kind === 'code'
- ? 'Enter this code on the phone that has your WhatsApp account.'
- : 'Scan this code with the phone that has your WhatsApp account.'}
+ {description(props.step)}
</ActionDialogShell.Description>
</ActionDialogShell.Header>
+ <Show when={props.retryFailed}>
+ <p role="alert" class="text-sm text-failure-ink">
+ Couldn't get a new code. Try again.
+ </p>
+ </Show>
<Switch>
<Match
when={
- props.step.kind === 'scan' || props.step.kind === 'preparing'
+ props.step.kind === 'scan' ||
+ props.step.kind === 'preparing' ||
+ props.step.kind === 'expired'
}
>
- <CodeSlot qr={qr()} secondsLeft={props.secondsLeft} />
+ <CodeSlot
+ qr={qr()}
+ refreshing={props.refreshing}
+ expired={props.step.kind === 'expired'}
+ onRetry={props.onRetry}
+ />
<Steps />
</Match>
<Match when={code()}>
@@ -238,20 +290,18 @@ export function PairingDialog(props: {
</Match>
<Match when={props.step.kind === 'connected'}>
<p role="status" class="text-sm text-ink-muted">
- Linked. Loading your groups…
+ Linked. Loading your chats…
</p>
</Match>
<Match
when={
- props.step.kind === 'expired' ||
- props.step.kind === 'failed' ||
- props.step.kind === 'cancelled'
+ props.step.kind === 'failed' || props.step.kind === 'cancelled'
}
>
<div class="flex flex-col items-start gap-3">
<p role="alert" class="text-sm text-ink-muted">
- {props.step.kind === 'expired'
- ? 'This code expired before it was scanned.'
+ {props.step.kind === 'cancelled'
+ ? 'Linking was cancelled.'
: "Linking didn't finish."}
</p>
<Button type="button" variant="strong" onClick={props.onRetry}>
diff --git a/apps/web/src/features/whatsapp-linked/context/whatsapp-linked-context.tsx b/apps/web/src/features/whatsapp-linked/context/whatsapp-linked-context.tsx
index f4acf9eeea..69c7348e17 100644
--- a/apps/web/src/features/whatsapp-linked/context/whatsapp-linked-context.tsx
+++ b/apps/web/src/features/whatsapp-linked/context/whatsapp-linked-context.tsx
@@ -10,6 +10,12 @@ import type { AdoptFailure } from '../core/adopt';
import type { WhatsAppChat } from '../core/chat';
import type { PairingStep, PasskeyChallenge } from '../core/pairing';
+/** Which collapsible sections of a list are open; unknown ones start open. */
+export type OpenSections = {
+ isOpen: (sectionId: string) => boolean;
+ setOpen: (sectionId: string, open: boolean) => void;
+};
+
/** A server read as the WhatsApp page needs it; `data` is set once loaded. */
export type SourceRead<Value> = {
readonly isPending: boolean;
@@ -95,6 +101,8 @@ export type WhatsAppLinkedCapabilities = {
isDisconnecting: Accessor<boolean>;
/** Host action: open a group in Macro. */
openGroup: (groupId: string) => void;
+ /** The chat list's folded sections, remembered per person. */
+ sections: OpenSections;
};
const Context = createContext<WhatsAppLinkedCapabilities>();
diff --git a/apps/web/src/features/whatsapp-linked/core/adopt.ts b/apps/web/src/features/whatsapp-linked/core/adopt.ts
index a6ab75762b..a2a81245de 100644
--- a/apps/web/src/features/whatsapp-linked/core/adopt.ts
+++ b/apps/web/src/features/whatsapp-linked/core/adopt.ts
@@ -1,4 +1,5 @@
import { match } from 'ts-pattern';
+import { type CannotAdd, cannotAddMessage } from './chat';
/** Why adding a group did not happen, in the page's vocabulary. */
export type AdoptRefusal =
@@ -8,7 +9,13 @@ export type AdoptRefusal =
| { reason: 'disconnected' }
| { reason: 'turned-off' }
| { reason: 'rate-limited' }
+ /** DSS's reason this chat can't be in Macro. */
+ | { reason: 'cannot-add'; why: CannotAdd }
| { reason: 'unavailable' }
+ /** DSS is behind on this account's WhatsApp work. */
+ | { reason: 'busy' }
+ /** DSS failed in a way retrying may not fix. */
+ | { reason: 'server-error' }
/** DSS rejected the request; its wording says why. */
| { reason: 'rejected'; detail: string }
| { reason: 'signed-out' }
@@ -38,6 +45,16 @@ export function adoptFailureMessage(failure: AdoptRefusal): string {
{ reason: 'rate-limited' },
() => 'Too many requests at once. Wait a second, then add it again.'
)
+ .with({ reason: 'cannot-add' }, ({ why }) => `${cannotAddMessage(why)}.`)
+ .with(
+ { reason: 'busy' },
+ () => 'Macro is catching up with your WhatsApp. Try again in a moment.'
+ )
+ .with(
+ { reason: 'server-error' },
+ () =>
+ 'Macro hit an error adding this chat. If it keeps happening, tell us.'
+ )
.with(
{ reason: 'unavailable' },
() => 'WhatsApp is temporarily unavailable. Try again in a moment.'
diff --git a/apps/web/src/features/whatsapp-linked/core/chat-date.test.ts b/apps/web/src/features/whatsapp-linked/core/chat-date.test.ts
new file mode 100644
index 0000000000..17dc8a3dfb
--- /dev/null
+++ b/apps/web/src/features/whatsapp-linked/core/chat-date.test.ts
@@ -0,0 +1,24 @@
+import { describe, expect, it } from 'vitest';
+import { formatActivityDate } from './chat';
+
+const now = new Date(2026, 9, 26, 15, 0);
+
+describe('formatActivityDate', () => {
+ it('says Today and Yesterday for the last two days', () => {
+ expect(
+ formatActivityDate(new Date(2026, 9, 26, 9).toISOString(), now)
+ ).toBe('Today');
+ expect(
+ formatActivityDate(new Date(2026, 9, 25, 23).toISOString(), now)
+ ).toBe('Yesterday');
+ });
+
+ it('always includes the year otherwise', () => {
+ expect(formatActivityDate(new Date(2026, 8, 2).toISOString(), now)).toBe(
+ 'Sep 2, 2026'
+ );
+ expect(formatActivityDate(new Date(2024, 7, 25).toISOString(), now)).toBe(
+ 'Aug 25, 2024'
+ );
+ });
+});
diff --git a/apps/web/src/features/whatsapp-linked/core/chat.ts b/apps/web/src/features/whatsapp-linked/core/chat.ts
index 4e57b807c8..6e1aeeb18a 100644
--- a/apps/web/src/features/whatsapp-linked/core/chat.ts
+++ b/apps/web/src/features/whatsapp-linked/core/chat.ts
@@ -1,3 +1,5 @@
+import { isSameDay } from '@core/util/time';
+import { match } from 'ts-pattern';
/** Where a WhatsApp chat already is in Macro for this viewer. */
export type InMacro =
| { kind: 'own'; groupId: string }
@@ -5,6 +7,8 @@ export type InMacro =
/** The WhatsApp community a group belongs to. */
export type ChatCommunity = {
+ /** The community's WhatsApp JID. */
+ id: string;
name: string;
/** The community's announcement group (named after the community). */
announcements: boolean;
@@ -35,24 +39,26 @@ export type WhatsAppChat = {
/** "Add to Macro" works now. */
canAdd: boolean;
/** DSS's reason this chat can't be added, when it can't. */
- cannotAddReason: string | undefined;
+ /** Why DSS says it can't be added; the words are ours (`cannotAddLabel`). */
+ cannotAddReason: CannotAdd | undefined;
/** Set for a group inside a WhatsApp community. */
community?: ChatCommunity;
};
/**
- * The WhatsApp page's three lists, in DSS's recent-activity order. `query`
- * keeps the chats whose name matches.
+ * The WhatsApp page's lists, in DSS's recent-activity order. `listed` holds
+ * the chats to add and those shared with the viewer, plus (while searching)
+ * the viewer's own added chats, which otherwise live in External's sidebar.
+ * `query` keeps the chats whose name matches.
*/
export function chatSections(chats: WhatsAppChat[], query = '') {
+ const searching = query.trim() !== '';
const visible = chats.filter((chat) => matchesChatQuery(chat, query));
return {
- inMacro: visible.filter((chat) => chat.inMacro?.kind === 'own'),
- /** Not yet in Macro for this viewer, or shared with them by someone else. */
- addable: visible.filter(
- (chat) =>
- chat.inMacro?.kind !== 'own' &&
- (chat.canAdd || chat.inMacro?.kind === 'shared')
+ listed: visible.filter((chat) =>
+ chat.inMacro?.kind === 'own'
+ ? searching
+ : chat.canAdd || chat.inMacro?.kind === 'shared'
),
unsupported: visible.filter(
(chat) => !chat.inMacro && !chat.canAdd && !!chat.cannotAddReason
@@ -60,6 +66,60 @@ export function chatSections(chats: WhatsAppChat[], query = '') {
};
}
+/** Anything listed as a WhatsApp conversation: a page chat or a sidebar group. */
+type Conversation = {
+ kind: 'group' | 'direct';
+ community?: ChatCommunity;
+};
+
+/** A list sorted the way WhatsApp's own app groups it, each part in list order. */
+export type ConversationSections<Item> = {
+ direct: Item[];
+ groups: Item[];
+ /** One per community, ordered by its most recent group. */
+ communities: { community: ChatCommunity; items: Item[] }[];
+};
+
+/** Splits a recent-first list into direct chats, plain groups and communities. */
+export function conversationSections<Item extends Conversation>(
+ items: readonly Item[]
+): ConversationSections<Item> {
+ const sections: ConversationSections<Item> = {
+ direct: [],
+ groups: [],
+ communities: [],
+ };
+ const byCommunity = new Map<string, Item[]>();
+ for (const item of items) {
+ if (item.kind === 'direct') {
+ sections.direct.push(item);
+ continue;
+ }
+ const community = item.community;
+ if (!community) {
+ sections.groups.push(item);
+ continue;
+ }
+ const known = byCommunity.get(community.id);
+ if (known) {
+ known.push(item);
+ continue;
+ }
+ const started = [item];
+ byCommunity.set(community.id, started);
+ sections.communities.push({ community, items: started });
+ }
+ return sections;
+}
+
+/** A community's group as listed under its community: its own name, or "Announcements". */
+export function nameInCommunity(item: {
+ name: string;
+ community?: ChatCommunity;
+}): string {
+ return item.community?.announcements ? 'Announcements' : item.name;
+}
+
const fold = (text: string) =>
text.normalize('NFD').replace(/\p{M}/gu, '').toLocaleLowerCase();
@@ -73,11 +133,33 @@ export function matchesChatQuery(chat: WhatsAppChat, query: string): boolean {
return /^\d+$/.test(digits) && chat.name.replace(/\D/g, '').includes(digits);
}
-/** DSS's refusal sentence, shortened for direct chats. */
+/** Why a chat can't be added to Macro, as DSS reports it. */
+export type CannotAdd =
+ | 'not_in_group'
+ | 'community'
+ | 'own_chat'
+ | 'not_in_chat_list';
+
+/** The reason a chat can't be added, in the page's words. */
+export function cannotAddMessage(reason: CannotAdd): string {
+ return match(reason)
+ .with('not_in_group', () => "Your WhatsApp isn't in this group anymore")
+ .with(
+ 'community',
+ () => 'A community has no messages of its own; add one of its groups'
+ )
+ .with('own_chat', () => "Your chat with yourself can't be added")
+ .with(
+ 'not_in_chat_list',
+ () => "This chat isn't in your WhatsApp chat list yet"
+ )
+ .exhaustive();
+}
+
+/** A row's "can't be added" note, when it has one. */
export function cannotAddLabel(chat: WhatsAppChat): string | undefined {
- const reason = chat.cannotAddReason;
- return reason
- ? `${reason.charAt(0).toUpperCase()}${reason.slice(1)}`
+ return chat.cannotAddReason
+ ? cannotAddMessage(chat.cannotAddReason)
: undefined;
}
@@ -96,3 +178,20 @@ export function chatMetadata(chat: WhatsAppChat): string {
.filter(Boolean)
.join(' · ');
}
+
+/** "Today", "Yesterday", or a full date with its year, so every row reads alike. */
+export function formatActivityDate(
+ value: string,
+ now: Date = new Date()
+): string {
+ const date = new Date(value);
+ if (isSameDay(date, now)) return 'Today';
+ const yesterday = new Date(now);
+ yesterday.setDate(now.getDate() - 1);
+ if (isSameDay(date, yesterday)) return 'Yesterday';
+ return date.toLocaleDateString('en-US', {
+ month: 'short',
+ day: 'numeric',
+ year: 'numeric',
+ });
+}
diff --git a/apps/web/src/features/whatsapp-linked/core/core.test.ts b/apps/web/src/features/whatsapp-linked/core/core.test.ts
index 020bc9990a..e6d37738e9 100644
--- a/apps/web/src/features/whatsapp-linked/core/core.test.ts
+++ b/apps/web/src/features/whatsapp-linked/core/core.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
import { accountStatus, phoneFromJid } from './account';
-import { formatCountdown, pairingStep, secondsLeft } from './pairing';
+import { pairingStep, secondsLeft } from './pairing';
describe('pairingStep', () => {
it('shows the QR only once the server has one', () => {
@@ -44,8 +44,6 @@ describe('countdown', () => {
expect(secondsLeft(deadline, Date.parse('2026-10-20T12:01:00.000Z'))).toBe(
0
);
- expect(formatCountdown(52)).toBe('0:52');
- expect(formatCountdown(125)).toBe('2:05');
});
});
diff --git a/apps/web/src/features/whatsapp-linked/core/pairing.ts b/apps/web/src/features/whatsapp-linked/core/pairing.ts
index 5936cc04df..f56da2094a 100644
--- a/apps/web/src/features/whatsapp-linked/core/pairing.ts
+++ b/apps/web/src/features/whatsapp-linked/core/pairing.ts
@@ -60,10 +60,3 @@ export function pairingStep(state: {
export function secondsLeft(expiresAt: string, now: number): number {
return Math.max(0, Math.ceil((Date.parse(expiresAt) - now) / 1000));
}
-
-/** `52` → `0:52`, `125` → `2:05`. */
-export function formatCountdown(seconds: number): string {
- const minutes = Math.floor(seconds / 60);
- const rest = seconds % 60;
- return `${minutes}:${rest.toString().padStart(2, '0')}`;
-}
diff --git a/apps/web/src/features/whatsapp-linked/primitives/open-sections.ts b/apps/web/src/features/whatsapp-linked/primitives/open-sections.ts
new file mode 100644
index 0000000000..ca8aeb4bf6
--- /dev/null
+++ b/apps/web/src/features/whatsapp-linked/primitives/open-sections.ts
@@ -0,0 +1,56 @@
+import {
+ type CollapsedSidebarSectionsState,
+ createCollapsedSidebarSectionsStorage,
+ setSidebarSectionCollapsed,
+} from '@app/components/view-shell/collapsed-sections';
+import { makePersistedState } from '@app/lib/persistence';
+import { type Accessor, createEffect, on } from 'solid-js';
+import { createStore } from 'solid-js/store';
+import type { OpenSections } from '../context/whatsapp-linked-context';
+
+/**
+ * Open and closed sections, remembered per person under `storageKey` with
+ * the view shell's folded-section storage (as Email and Tasks do). Unknown
+ * sections start open.
+ */
+export function createOpenSections(
+ storageKey: string,
+ userId: Accessor<string | undefined>
+): OpenSections {
+ const storage =
+ createCollapsedSidebarSectionsStorage<CollapsedSidebarSectionsState>({
+ key: storageKey,
+ userId,
+ restore: true,
+ });
+ const [state, setState] = makePersistedState(
+ createStore<CollapsedSidebarSectionsState>({
+ collapsedSidebarSectionIds: [],
+ }),
+ { storages: storage }
+ );
+ // The signed-in user can arrive after the list mounts, e.g. on a reload.
+ createEffect(
+ on(
+ userId,
+ () => {
+ const restored = storage.restore(state);
+ if (restored)
+ setState(
+ 'collapsedSidebarSectionIds',
+ restored.collapsedSidebarSectionIds
+ );
+ },
+ { defer: true }
+ )
+ );
+ return {
+ isOpen: (sectionId) =>
+ !state.collapsedSidebarSectionIds.includes(sectionId),
+ setOpen: (sectionId, open) =>
+ setState(
+ 'collapsedSidebarSectionIds',
+ setSidebarSectionCollapsed(sectionId, open)
+ ),
+ };
+}
diff --git a/apps/web/src/features/whatsapp-linked/primitives/pairing-flow.ts b/apps/web/src/features/whatsapp-linked/primitives/pairing-flow.ts
index 9121023a85..9a059b34a7 100644
--- a/apps/web/src/features/whatsapp-linked/primitives/pairing-flow.ts
+++ b/apps/web/src/features/whatsapp-linked/primitives/pairing-flow.ts
@@ -1,5 +1,11 @@
import { fireAndForget } from '@core/util/fireAndForget';
-import { type Accessor, createEffect, createSignal, on } from 'solid-js';
+import {
+ type Accessor,
+ createEffect,
+ createSignal,
+ on,
+ onCleanup,
+} from 'solid-js';
import type {
PasskeyCeremony,
StartedPairing,
@@ -8,12 +14,19 @@ import type {
import type { PairingStep } from '../core/pairing';
import { createCountdown } from './countdown';
+/**
+ * Expired codes replaced without a click before the dialog asks for one.
+ * WhatsApp's QR session lasts ~2.7 minutes, so this covers about ten.
+ */
+export const AUTO_ROLLS = 3;
+
export type PairingFlow = {
/** Whether the pairing dialog is open. */
open: Accessor<boolean>;
step: Accessor<PairingStep>;
- secondsLeft: Accessor<number | undefined>;
- /** Starting a pairing failed before any dialog opened. */
+ /** A code expired and its replacement is on its way. */
+ refreshing: Accessor<boolean>;
+ /** The last start (or the dialog's retry) failed. */
startFailed: Accessor<boolean>;
start: () => Promise<void>;
/** Shows a pairing started elsewhere, e.g. handed off to Macro desktop. */
@@ -28,9 +41,14 @@ export type PairingFlow = {
cancel: () => Promise<void>;
};
+const visible = () => document.visibilityState === 'visible';
+
/**
- * One owner-bound pairing at a time: start it, poll its step, count down its
- * deadline, and close once WhatsApp reports the device linked.
+ * One owner-bound pairing at a time: start it, poll its step, and close once
+ * WhatsApp reports the device linked. Like WhatsApp Web, an expired code is
+ * replaced by a new pairing on its own while someone is watching, up to
+ * [`AUTO_ROLLS`] times; after that, or once the tab was hidden, the dialog
+ * asks for a click.
*/
export function createPairingFlow(
/** The account already reads as linked, e.g. its poll beat the pairing poll. */
@@ -46,19 +64,50 @@ export function createPairingFlow(
const [passkey, setPasskey] = createSignal<PasskeyCeremony>({
kind: 'idle',
});
+ const [rolls, setRolls] = createSignal(0);
+ const [rolling, setRolling] = createSignal(false);
+ const [rollFailed, setRollFailed] = createSignal(false);
+ // Whether the tab stayed visible for the whole life of the current code.
+ const [watched, setWatched] = createSignal(visible());
+ const onVisibility = () => {
+ if (!visible()) setWatched(false);
+ };
+ document.addEventListener('visibilitychange', onVisibility);
+ onCleanup(() =>
+ document.removeEventListener('visibilitychange', onVisibility)
+ );
+
const poll = capabilities.pairing(() => current()?.pairingId ?? '');
const secondsLeft = createCountdown(
() => current()?.expiresAt ?? poll.data?.expiresAt
);
- const linkedByAccount = accountLinked;
+ const autoRolls = () => watched() && rolls() < AUTO_ROLLS;
+ // A pairing the server can't find (expired long ago, or opened by someone
+ // else from a desktop handoff link) has failed; its poll has stopped.
+ const polled = (): PairingStep =>
+ poll.isError
+ ? { kind: 'failed' }
+ : (poll.data?.step ?? { kind: 'preparing' });
+ /** The server ended the current code: WhatsApp ran out of codes or the deadline passed. */
+ const serverExpired = () => polled().kind === 'expired';
+ // The deadline is the server's; once it passes, a stale QR is not scannable.
+ const codeExpired = () =>
+ serverExpired() || (polled().kind === 'scan' && secondsLeft() === 0);
const step = (): PairingStep => {
- const polled = poll.data?.step ?? { kind: 'preparing' };
- // The deadline is the server's; once it passes, a stale QR is not scannable.
- if (polled.kind === 'scan' && secondsLeft() === 0) {
- return { kind: 'expired' };
- }
- return polled;
+ if (rollFailed()) return { kind: 'failed' };
+ // About to be replaced: no flash of the expired state in between.
+ if (rolling() || (codeExpired() && autoRolls()))
+ return { kind: 'preparing' };
+ return codeExpired() ? { kind: 'expired' } : polled();
+ };
+
+ const begin = (pairing: StartedPairing) => {
+ setPasskey({ kind: 'idle' });
+ setHandedOff(false);
+ setRollFailed(false);
+ setWatched(visible());
+ setCurrent(pairing);
};
const finish = async () => {
@@ -71,13 +120,43 @@ export function createPairingFlow(
on(
() =>
current() !== undefined &&
- (step().kind === 'connected' || linkedByAccount()),
+ (step().kind === 'connected' || accountLinked()),
(connected) => {
if (connected) fireAndForget(finish(), 'whatsapp-linked.pairing');
}
)
);
+ const roll = async (expired: string) => {
+ setRolls((count) => count + 1);
+ setRolling(true);
+ const started = await capabilities.connect();
+ setRolling(false);
+ const now = current()?.pairingId;
+ if (now !== expired) {
+ // Closed (or restarted) while the next code was on its way: end it.
+ if (started.isOk() && started.value.pairingId !== now)
+ await capabilities.cancelPairing(started.value.pairingId);
+ return;
+ }
+ if (started.isErr()) {
+ setRollFailed(true);
+ return;
+ }
+ begin(started.value);
+ };
+
+ // Only the server's word starts a new pairing; a fast local clock must not.
+ createEffect(
+ on(
+ () => (serverExpired() ? current()?.pairingId : undefined),
+ (expired) => {
+ if (expired && autoRolls() && !rolling())
+ fireAndForget(roll(expired), 'whatsapp-linked.pairing');
+ }
+ )
+ );
+
const start = async () => {
setStartFailed(false);
const started = await capabilities.connect();
@@ -85,9 +164,8 @@ export function createPairingFlow(
setStartFailed(true);
return;
}
- setPasskey({ kind: 'idle' });
- setHandedOff(false);
- setCurrent(started.value);
+ setRolls(0);
+ begin(started.value);
};
const confirmPasskey = async () => {
@@ -119,9 +197,10 @@ export function createPairingFlow(
};
const cancel = async () => {
+ setStartFailed(false);
const pairing = current();
const finished =
- step().kind === 'connected' || linkedByAccount() || handedOff();
+ step().kind === 'connected' || accountLinked() || handedOff();
setCurrent(undefined);
if (!pairing || finished) return;
// The server also expires an abandoned pairing; nothing to recover here.
@@ -131,13 +210,13 @@ export function createPairingFlow(
return {
open: () => current() !== undefined,
step,
- secondsLeft,
+ refreshing: () =>
+ step().kind === 'preparing' && (rolls() > 0 || codeExpired()),
startFailed,
start,
resume: (pairingId) => {
- setHandedOff(false);
- setPasskey({ kind: 'idle' });
- setCurrent({ pairingId });
+ setRolls(0);
+ begin({ pairingId });
},
pairingId: () => current()?.pairingId,
passkey,
diff --git a/apps/web/src/features/whatsapp-linked/queries/decode.ts b/apps/web/src/features/whatsapp-linked/queries/decode.ts
index 569e89ba7a..42df25c4e1 100644
--- a/apps/web/src/features/whatsapp-linked/queries/decode.ts
+++ b/apps/web/src/features/whatsapp-linked/queries/decode.ts
@@ -14,10 +14,8 @@ export function decodeAccount(
): WhatsAppAccount | null {
if (!account) return null;
return {
- generation: account.authorization_generation,
- phone: account.identity_jid
- ? phoneFromJid(account.identity_jid)
- : undefined,
+ generation: account.authorizationGeneration,
+ phone: account.identityJid ? phoneFromJid(account.identityJid) : undefined,
health: account.state,
};
}
@@ -47,6 +45,7 @@ export function decodeChat(
cannotAddReason: chat.cannotAddReason ?? undefined,
community: chat.community
? {
+ id: chat.community.id,
name: chat.community.name,
announcements: chat.community.announcements,
}
@@ -64,11 +63,27 @@ export function decodeAdoptRefusal(error: unknown): AdoptRefusal {
.with('forbidden', 'FORBIDDEN', () => ({ reason: 'not-allowed' }))
.with('not_found', 'NOT_FOUND', 'GONE', () => ({ reason: 'gone' }))
.with('conflict', 'CONFLICT', () => ({ reason: 'already-added' }))
- .with('disconnected', 'identity_conflict', () => ({
- reason: 'disconnected',
+ .with('disconnected', () => ({ reason: 'disconnected' }))
+ .with('cannot_add_not_in_group', () => ({
+ reason: 'cannot-add',
+ why: 'not_in_group',
+ }))
+ .with('cannot_add_community', () => ({
+ reason: 'cannot-add',
+ why: 'community',
+ }))
+ .with('cannot_add_own_chat', () => ({
+ reason: 'cannot-add',
+ why: 'own_chat',
+ }))
+ .with('cannot_add_not_in_chat_list', () => ({
+ reason: 'cannot-add',
+ why: 'not_in_chat_list',
}))
.with('configuration_required', () => ({ reason: 'turned-off' }))
.with('rate_limited', () => ({ reason: 'rate-limited' }))
+ .with('backlogged', () => ({ reason: 'busy' }))
+ .with('internal_error', () => ({ reason: 'server-error' }))
.with('invalid_input', () => ({
reason: 'rejected',
detail: first.message,
diff --git a/apps/web/src/features/whatsapp-linked/queries/production-capabilities.ts b/apps/web/src/features/whatsapp-linked/queries/production-capabilities.ts
index c363a48e8c..00e1061612 100644
--- a/apps/web/src/features/whatsapp-linked/queries/production-capabilities.ts
+++ b/apps/web/src/features/whatsapp-linked/queries/production-capabilities.ts
@@ -24,6 +24,7 @@ import type { UseQueryResult } from '@tanstack/solid-query';
import { ResultAsync } from 'neverthrow';
import { type Accessor, createMemo, createSignal } from 'solid-js';
import type {
+ OpenSections,
PasskeyCapability,
RequestFailure,
SourceRead,
@@ -94,6 +95,7 @@ function pageLoad(
/** The WhatsApp page's capabilities, from the shared linked-device queries. */
export function createWhatsAppLinkedCapabilities(host: {
openGroup: (groupId: string) => void;
+ sections: OpenSections;
}): WhatsAppLinkedCapabilities {
const user = useUserId();
const currentUser = () => user() ?? '';
@@ -128,6 +130,7 @@ export function createWhatsAppLinkedCapabilities(host: {
const [chatsRead, setChatsRead] = createSignal<SourceRead<WhatsAppChat[]>>();
traceWhatsappLoad('page.load', () => pageLoad(account, chatsRead()));
return {
+ sections: host.sections,
features: sourceRead(useWhatsappLinkedConfigurationQuery(), (features) => ({
pairing: features.pairing,
adoption: features.adoption,
@@ -154,7 +157,7 @@ export function createWhatsAppLinkedCapabilities(host: {
),
connect: () =>
ResultAsync.fromPromise(connect.mutateAsync(), failure).map(
- (pairing) => ({ pairingId: pairing.id, expiresAt: pairing.expires_at })
+ (pairing) => ({ pairingId: pairing.id, expiresAt: pairing.expiresAt })
),
cancelPairing: (pairingId) =>
ResultAsync.fromPromise(cancel.mutateAsync(pairingId), failure).map(
@@ -164,17 +167,17 @@ export function createWhatsAppLinkedCapabilities(host: {
disconnect: (generation) =>
ResultAsync.fromPromise(disconnect.mutateAsync(generation), failure).map(
(result) => ({
- remoteUnlinkRequested: result.remote_unlink_requested,
+ remoteUnlinkRequested: result.remoteUnlinkRequested,
})
),
adopt: (groupJid) =>
ResultAsync.fromPromise(
- adopt.mutateAsync({ group_jid: groupJid }),
+ adopt.mutateAsync({ groupJid }),
(error): AdoptFailure => ({
kind: 'adopt-failed',
...decodeAdoptRefusal(error),
})
- ).map((binding) => ({ groupId: binding.group_id })),
+ ).map((binding) => ({ groupId: binding.groupId })),
isConnecting: () => connect.isPending,
isDisconnecting: () => disconnect.isPending,
openGroup: host.openGroup,
diff --git a/apps/web/src/features/whatsapp-linked/tests/fake-capabilities.ts b/apps/web/src/features/whatsapp-linked/tests/fake-capabilities.ts
index c1bb0edfb6..18419c7b69 100644
--- a/apps/web/src/features/whatsapp-linked/tests/fake-capabilities.ts
+++ b/apps/web/src/features/whatsapp-linked/tests/fake-capabilities.ts
@@ -12,6 +12,7 @@ import type { WhatsAppAccount } from '../core/account';
import type { AdoptFailure } from '../core/adopt';
import type { WhatsAppChat } from '../core/chat';
import type { PairingStep } from '../core/pairing';
+import { createOpenSections } from '../primitives/open-sections';
function signalRead<Value>(
initial: Value | undefined
@@ -43,12 +44,42 @@ export function createFakeWhatsApp(initial: {
);
const [chats, setChats] = signalRead<WhatsAppChat[]>(initial.chats);
const [features] = signalRead({ pairing: true, adoption: true });
- const [pairing, setPairingRead] = signalRead<PairingRead>(undefined);
- const setPairing = (step: PairingStep, expiresAt?: string) =>
- setPairingRead({
- step,
- expiresAt: expiresAt ?? new Date(Date.now() + 52_000).toISOString(),
- });
+ // Pairings are numbered as `connect` starts them; reads are per pairing.
+ let started = 0;
+ const [pairings, setPairings] = createSignal<
+ Record<string, PairingRead | 'error'>
+ >({});
+ /** The server can't read a pairing (gone, or not the caller's). */
+ const failPairingRead = (pairingId: string) =>
+ setPairings((current) => ({ ...current, [pairingId]: 'error' }));
+ /** Report `step` for a pairing, the latest started one by default. */
+ const setPairing = (
+ step: PairingStep,
+ options: { pairingId?: string; expiresAt?: string } = {}
+ ) =>
+ setPairings((current) => ({
+ ...current,
+ [options.pairingId ?? `pairing-${started}`]: {
+ step,
+ expiresAt:
+ options.expiresAt ?? new Date(Date.now() + 52_000).toISOString(),
+ },
+ }));
+ const pairingRead = (
+ pairingId: Accessor<string>
+ ): SourceRead<PairingRead> => ({
+ get isPending() {
+ return pairings()[pairingId()] === undefined;
+ },
+ get isError() {
+ return pairings()[pairingId()] === 'error';
+ },
+ get data() {
+ const read = pairings()[pairingId()];
+ return read === 'error' ? undefined : read;
+ },
+ refetch: vi.fn(),
+ });
const chatsEnabled: Accessor<boolean>[] = [];
const capabilities = {
features,
@@ -62,14 +93,14 @@ export function createFakeWhatsApp(initial: {
desktopUrl: (pairingId: string) =>
`macro:///external?whatsappPairing=${pairingId}`,
},
- pairing: vi.fn((_pairingId: Accessor<string>) => pairing),
+ pairing: vi.fn(pairingRead),
connect: vi.fn(
(): ResultAsync<
{ pairingId: string; expiresAt: string },
RequestFailure
> =>
okAsync({
- pairingId: 'pairing-1',
+ pairingId: `pairing-${++started}`,
expiresAt: new Date(Date.now() + 52_000).toISOString(),
})
),
@@ -91,6 +122,14 @@ export function createFakeWhatsApp(initial: {
isConnecting: () => false,
isDisconnecting: () => false,
openGroup: vi.fn(),
+ sections: createOpenSections('test:whatsapp-sections', () => undefined),
} satisfies WhatsAppLinkedCapabilities;
- return { capabilities, setAccount, setChats, setPairing, chatsEnabled };
+ return {
+ capabilities,
+ setAccount,
+ setChats,
+ setPairing,
+ failPairingRead,
+ chatsEnabled,
+ };
}
diff --git a/apps/web/src/features/whatsapp-linked/views/whatsapp-page.test.tsx b/apps/web/src/features/whatsapp-linked/views/whatsapp-page.test.tsx
index 370831c171..c236d540ee 100644
--- a/apps/web/src/features/whatsapp-linked/views/whatsapp-page.test.tsx
+++ b/apps/web/src/features/whatsapp-linked/views/whatsapp-page.test.tsx
@@ -6,13 +6,24 @@ import {
waitFor,
within,
} from '@solidjs/testing-library';
-import { errAsync, okAsync } from 'neverthrow';
+import { errAsync, okAsync, ResultAsync } from 'neverthrow';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { WhatsAppLinkedProvider } from '../context/whatsapp-linked-context';
+import { AUTO_ROLLS } from '../primitives/pairing-flow';
import { createFakeWhatsApp } from '../tests/fake-capabilities';
import { WhatsAppPage } from './whatsapp-page';
vi.mock('@core/mobile/isMobile', () => ({ isMobile: () => false }));
+const toast = vi.hoisted(() => ({ success: vi.fn(), failure: vi.fn() }));
+vi.mock('@core/component/Toast/Toast', () => ({ toast }));
+
+function setTabVisibility(state: DocumentVisibilityState) {
+ Object.defineProperty(document, 'visibilityState', {
+ configurable: true,
+ get: () => state,
+ });
+ document.dispatchEvent(new Event('visibilitychange'));
+}
beforeEach(() => {
vi.stubGlobal('scrollTo', vi.fn());
@@ -28,6 +39,8 @@ beforeEach(() => {
afterEach(() => {
cleanup();
+ setTabVisibility('visible');
+ vi.clearAllMocks();
vi.useRealTimers();
vi.unstubAllGlobals();
});
@@ -49,6 +62,12 @@ const dialogOpen = () =>
.queryAllByRole('dialog')
.some((dialog) => !dialog.hasAttribute('data-closed'));
+const launch = (announcements: boolean) => ({
+ name: 'Launch',
+ announcements,
+});
+
const chat = {
kind: 'group' as const,
lastActivityAt: undefined,
@@ -67,7 +86,7 @@ const chats = [
name: 'Ana Ruiz',
lastActivityAt: '2025-03-07T10:00:00Z',
canAdd: false,
- cannotAddReason: "your chat with yourself can't be added to Macro",
+ cannotAddReason: 'own_chat' as const,
},
{
...chat,
@@ -101,15 +120,12 @@ const chats = [
name: 'Neighbourhood',
archived: true,
canAdd: false,
- cannotAddReason:
- 'a community has no messages of its own; add one of its groups',
+ cannotAddReason: 'community' as const,
},
];
describe('not connected', () => {
it('explains the account risk and links WhatsApp through a QR dialog', async () => {
- vi.useFakeTimers({ toFake: ['Date', 'setInterval', 'clearInterval'] });
- vi.setSystemTime(new Date('2026-10-20T12:00:00.000Z'));
const fake = createFakeWhatsApp({ account: null });
mount(fake);
@@ -131,9 +147,10 @@ describe('not connected', () => {
name: 'Scan this code with WhatsApp on your phone',
})
).toBeTruthy();
- expect(dialog.getByText('Expires in 0:52')).toBeTruthy();
- vi.advanceTimersByTime(2_000);
- expect(dialog.getByText('Expires in 0:50')).toBeTruthy();
+ // WhatsApp rotates the code within one pairing; the dialog follows it.
+ const firstCode = dialog.getByRole('img').innerHTML;
+ fake.setPairing({ kind: 'scan', qr: '2@rotated-ref,key,identity,adv' });
+ expect(dialog.getByRole('img').innerHTML).not.toBe(firstCode);
fireEvent.click(dialog.getByRole('button', { name: 'Cancel' }));
await waitFor(() =>
@@ -142,7 +159,65 @@ describe('not connected', () => {
await waitFor(() => expect(dialogOpen()).toBe(false));
});
- it('turns a QR that outlived its deadline into an expired step with a retry', async () => {
+ it('replaces an expired code with a new pairing without a click', async () => {
+ const fake = createFakeWhatsApp({ account: null });
+ mount(fake);
+ fireEvent.click(screen.getByRole('button', { name: 'Connect' }));
+ const dialog = within(await screen.findByRole('dialog'));
+ fake.setPairing({ kind: 'scan', qr: '2@first-ref' });
+
+ fake.setPairing({ kind: 'expired' });
+ expect(dialog.getByText('Refreshing code…')).toBeTruthy();
+ expect(dialog.queryByText('Code expired')).toBeNull();
+ expect(dialog.queryByRole('alert')).toBeNull();
+ await waitFor(() =>
+ expect(fake.capabilities.connect).toHaveBeenCalledTimes(2)
+ );
+ expect(dialog.getByText('Refreshing code…')).toBeTruthy();
+ expect(dialog.getByText('Tap Link a device')).toBeTruthy();
+
+ fake.setPairing({ kind: 'scan', qr: '2@second-ref' });
+ expect(
+ await dialog.findByRole('img', {
+ name: 'Scan this code with WhatsApp on your phone',
+ })
+ ).toBeTruthy();
+ expect(fake.capabilities.cancelPairing).not.toHaveBeenCalled();
+ });
+
+ it('asks for a click once it has rolled enough codes without a scan', async () => {
+ const fake = createFakeWhatsApp({ account: null });
+ mount(fake);
+ fireEvent.click(screen.getByRole('button', { name: 'Connect' }));
+ const dialog = within(await screen.findByRole('dialog'));
+ for (let roll = 1; roll <= AUTO_ROLLS; roll++) {
+ fake.setPairing({ kind: 'scan', qr: `2@ref-${roll}` });
+ fake.setPairing({ kind: 'expired' });
+ await waitFor(() =>
+ expect(fake.capabilities.connect).toHaveBeenCalledTimes(roll + 1)
+ );
+ }
+ fake.setPairing({ kind: 'scan', qr: '2@last-ref' });
+ fake.setPairing({ kind: 'expired' });
+
+ expect(await dialog.findByText('Code expired')).toBeTruthy();
+ expect(dialog.queryByRole('img')).toBeNull();
+ expect(dialog.getByText('Tap Link a device')).toBeTruthy();
+ expect(fake.capabilities.connect).toHaveBeenCalledTimes(AUTO_ROLLS + 1);
+
+ fireEvent.click(dialog.getByRole('button', { name: 'Show a new code' }));
+ await waitFor(() =>
+ expect(fake.capabilities.connect).toHaveBeenCalledTimes(AUTO_ROLLS + 2)
+ );
+ // A click starts a fresh run of automatic codes.
+ fake.setPairing({ kind: 'scan', qr: '2@clicked-ref' });
+ fake.setPairing({ kind: 'expired' });
+ await waitFor(() =>
+ expect(fake.capabilities.connect).toHaveBeenCalledTimes(AUTO_ROLLS + 3)
+ );
+ });
+
+ it('does not roll a code that expired while the tab was hidden', async () => {
vi.useFakeTimers({ toFake: ['Date', 'setInterval', 'clearInterval'] });
vi.setSystemTime(new Date('2026-10-20T12:00:00.000Z'));
const fake = createFakeWhatsApp({ account: null });
@@ -151,14 +226,111 @@ describe('not connected', () => {
const dialog = within(await screen.findByRole('dialog'));
fake.setPairing({ kind: 'scan', qr: '2@pairing-ref' });
+ setTabVisibility('hidden');
+ // The local deadline passes while nobody watches; the poll is paused.
vi.advanceTimersByTime(53_000);
- expect(
- dialog.getByText('This code expired before it was scanned.')
- ).toBeTruthy();
+ expect(dialog.getByText('Code expired')).toBeTruthy();
+ setTabVisibility('visible');
+ fake.setPairing({ kind: 'expired' });
+ expect(dialog.getByText('Code expired')).toBeTruthy();
+ expect(fake.capabilities.connect).toHaveBeenCalledOnce();
+
+ fireEvent.click(dialog.getByRole('button', { name: 'Show a new code' }));
+ await waitFor(() =>
+ expect(fake.capabilities.connect).toHaveBeenCalledTimes(2)
+ );
+ });
+
+ it('waits for the server before rolling a code whose local deadline passed', async () => {
+ vi.useFakeTimers({ toFake: ['Date', 'setInterval', 'clearInterval'] });
+ vi.setSystemTime(new Date('2026-10-20T12:00:00.000Z'));
+ const fake = createFakeWhatsApp({ account: null });
+ mount(fake);
+ fireEvent.click(screen.getByRole('button', { name: 'Connect' }));
+ const dialog = within(await screen.findByRole('dialog'));
+ fake.setPairing({ kind: 'scan', qr: '2@pairing-ref' });
+
+ vi.advanceTimersByTime(53_000);
+ expect(dialog.getByText('Refreshing code…')).toBeTruthy();
expect(dialog.queryByRole('img')).toBeNull();
+ expect(fake.capabilities.connect).toHaveBeenCalledOnce();
+ fake.setPairing({ kind: 'expired' });
+ await waitFor(() =>
+ expect(fake.capabilities.connect).toHaveBeenCalledTimes(2)
+ );
+ });
+
+ it('shows a real failure instead of rolling', async () => {
+ const fake = createFakeWhatsApp({ account: null });
+ mount(fake);
+ fireEvent.click(screen.getByRole('button', { name: 'Connect' }));
+ const dialog = within(await screen.findByRole('dialog'));
+ fake.setPairing({ kind: 'scan', qr: '2@pairing-ref' });
+ fake.setPairing({ kind: 'failed' });
+ expect(dialog.getByRole('alert').textContent).toBe(
+ "Linking didn't finish."
+ );
+ expect(fake.capabilities.connect).toHaveBeenCalledOnce();
fireEvent.click(dialog.getByRole('button', { name: 'Show a new code' }));
- expect(fake.capabilities.connect).toHaveBeenCalledTimes(2);
+ await waitFor(() =>
+ expect(fake.capabilities.connect).toHaveBeenCalledTimes(2)
+ );
+ });
+
+ it('says in the dialog when a new code could not be started', async () => {
+ const fake = createFakeWhatsApp({ account: null });
+ mount(fake);
+ fireEvent.click(screen.getByRole('button', { name: 'Connect' }));
+ const dialog = within(await screen.findByRole('dialog'));
+ fake.setPairing({ kind: 'failed' });
+ fake.capabilities.connect.mockReturnValueOnce(
+ errAsync({ kind: 'request-failed' })
+ );
+
+ fireEvent.click(dialog.getByRole('button', { name: 'Show a new code' }));
+ expect(
+ await dialog.findByText("Couldn't get a new code. Try again.")
+ ).toBeTruthy();
+ fireEvent.click(dialog.getByRole('button', { name: 'Cancel' }));
+ await waitFor(() => expect(dialogOpen()).toBe(false));
+ expect(
+ screen.queryByText("Couldn't start linking WhatsApp. Try again.")
+ ).toBeNull();
+ });
+
+ it('cancels the next pairing when the dialog closes while it is starting', async () => {
+ const fake = createFakeWhatsApp({ account: null });
+ mount(fake);
+ fireEvent.click(screen.getByRole('button', { name: 'Connect' }));
+ const dialog = within(await screen.findByRole('dialog'));
+ fake.setPairing({ kind: 'scan', qr: '2@pairing-ref' });
+ let resolveNext!: (pairing: {
+ pairingId: string;
+ expiresAt: string;
+ }) => void;
+ fake.capabilities.connect.mockReturnValueOnce(
+ ResultAsync.fromSafePromise(
+ new Promise((resolve) => {
+ resolveNext = resolve;
+ })
+ )
+ );
+
+ fake.setPairing({ kind: 'expired' });
+ await waitFor(() =>
+ expect(fake.capabilities.connect).toHaveBeenCalledTimes(2)
+ );
+ fireEvent.click(dialog.getByRole('button', { name: 'Cancel' }));
+ await waitFor(() => expect(dialogOpen()).toBe(false));
+ resolveNext({
+ pairingId: 'pairing-2',
+ expiresAt: new Date(Date.now() + 52_000).toISOString(),
+ });
+ await waitFor(() =>
+ expect(fake.capabilities.cancelPairing).toHaveBeenCalledWith('pairing-2')
+ );
+ expect(dialogOpen()).toBe(false);
});
it('closes the dialog and refreshes the account once the phone links', async () => {
@@ -218,14 +390,10 @@ describe('connected', () => {
expect(screen.getByText('Connected')).toBeTruthy();
expect(fake.chatsEnabled[0]?.()).toBe(true);
// Added chats live in External's sidebar until a search finds them.
- expect(
- screen.queryByRole('list', { name: 'WhatsApp chats in Macro' })
- ).toBeNull();
-
- const list = within(
- screen.getByRole('list', { name: 'Chats to add to Macro' })
- );
- expect(list.queryByText('Design Crit')).toBeNull();
+ expect(screen.queryByText('Design Crit')).toBeNull();
+ // Only sections with chats show: no direct chat here can be added.
+ expect(screen.queryByRole('list', { name: 'Direct messages' })).toBeNull();
+ const list = within(screen.getByRole('list', { name: 'Groups' }));
expect(list.getAllByRole('listitem').map((row) => row.textContent)).toEqual(
[
'Launch War RoomGroupAdd to MacroMar 5, 2025',
@@ -250,7 +418,7 @@ describe('connected', () => {
expect(direct.getByText('Direct chat')).toBeTruthy();
expect(direct.getByText('Mar 7, 2025')).toBeTruthy();
expect(
- direct.getByText("Your chat with yourself can't be added to Macro")
+ direct.getByText("Your chat with yourself can't be added")
).toBeTruthy();
expect(direct.queryByRole('button')).toBeNull();
expect(
@@ -274,11 +442,23 @@ describe('connected', () => {
await waitFor(() =>
expect(fake.capabilities.disconnect).toHaveBeenCalledWith(3)
);
+ await waitFor(() =>
+ expect(toast.success).toHaveBeenCalledWith(
+ 'Disconnected in Macro. To finish, remove Macro under WhatsApp → Linked devices on your phone.'
+ )
+ );
fake.setAccount(null);
- expect(
- await screen.findByText(/remove Macro under WhatsApp → Linked devices/)
- ).toBeTruthy();
expect(screen.getByRole('button', { name: 'Connect' })).toBeTruthy();
+
+ // Linking again leaves nothing of the disconnect on the page.
+ fake.setAccount({
+ generation: 4,
+ phone: '+14155550142',
+ health: 'connected',
+ });
+ expect(await screen.findByText('Connected')).toBeTruthy();
+ expect(screen.queryByText(/Linked devices on your phone/)).toBeNull();
+ expect(screen.queryByRole('alert')).toBeNull();
});
it('searches every section, added chats included, by name or phone digits', async () => {
@@ -292,7 +472,7 @@ describe('connected', () => {
kind: 'direct' as const,
name: '+1 415-555-0123',
canAdd: false,
- cannotAddReason: "direct chats can't be added to Macro yet",
+ cannotAddReason: 'not_in_chat_list' as const,
},
],
});
@@ -301,22 +481,19 @@ describe('connected', () => {
const search = screen.getByRole('searchbox', {
name: 'Search WhatsApp chats',
});
+ // A folded section still shows what a search finds in it.
+ fireEvent.click(screen.getByRole('button', { name: 'Groups' }));
+ expect(fake.capabilities.sections.isOpen('groups')).toBe(false);
fireEvent.input(search, { target: { value: 'design' } });
- const inMacro = within(
- screen.getByRole('list', { name: 'WhatsApp chats in Macro' })
- );
- fireEvent.click(inMacro.getByRole('button', { name: 'Open' }));
+ const found = within(screen.getByRole('list', { name: 'Groups' }));
+ fireEvent.click(found.getByRole('button', { name: 'Open' }));
expect(fake.capabilities.openGroup).toHaveBeenCalledWith('group-design');
fireEvent.input(search, { target: { value: 'ana' } });
- const list = within(
- screen.getByRole('list', { name: 'Chats to add to Macro' })
- );
+ const list = within(screen.getByRole('list', { name: 'Groups' }));
expect(list.getByText('Ana, Ben, +2')).toBeTruthy();
expect(list.queryByText('Launch War Room')).toBeNull();
- expect(
- screen.queryByRole('list', { name: 'WhatsApp chats in Macro' })
- ).toBeNull();
+ expect(list.queryByText('Design Crit')).toBeNull();
// Matches in the folded section show without unfolding it.
expect(
screen
@@ -361,7 +538,7 @@ describe('connected', () => {
});
mount(fake);
const row = within(
- within(screen.getByRole('list', { name: 'Chats to add to Macro' }))
+ within(screen.getByRole('list', { name: 'Direct messages' }))
.getByText('Ben Ode')
.closest('li') as HTMLElement
);
@@ -374,7 +551,7 @@ describe('connected', () => {
);
});
- it('offers community and disappearing-message groups like any group', async () => {
+ it('lists direct chats, groups and each community apart, recent first, and offers them all', async () => {
const fake = createFakeWhatsApp({
account: { generation: 3, phone: '+14155550142', health: 'connected' },
chats: [
@@ -382,13 +559,29 @@ describe('connected', () => {
...chat,
name: 'Design',
- community: { name: 'Launch', announcements: false },
+ community: launch(false),
},
{
...chat,
name: 'Launch',
- community: { name: 'Launch', announcements: true },
+ community: launch(true),
+ },
+ {
+ ...chat,
+ kind: 'direct' as const,
+ name: 'Ben Ode',
+ },
+ {
+ ...chat,
+ name: 'Kitchen',
+ community: {
+ name: 'Building',
+ announcements: false,
+ },
},
// Disappearing messages no longer keep a group out.
{ ...chat, jid: '[email protected]', name: 'Night shift' },
@@ -397,25 +590,46 @@ describe('connected', () => {
name: 'Launch',
canAdd: false,
- cannotAddReason:
- 'a community has no messages of its own; add one of its groups',
+ cannotAddReason: 'community' as const,
},
],
});
mount(fake);
- const addable = within(
- screen.getByRole('list', { name: 'Chats to add to Macro' })
- );
+ const names = (label: string) =>
+ within(screen.getByRole('list', { name: label }))
+ .getAllByRole('listitem')
+ .map((row) => row.querySelector('.font-medium')?.textContent);
+ expect(names('Direct messages')).toEqual(['Ben Ode']);
+ expect(names('Groups')).toEqual(['Night shift']);
+ // One section per community, by its latest group; groups by their own name.
+ expect(names('Launch')).toEqual(['Design', 'Announcements']);
+ expect(names('Building')).toEqual(['Kitchen']);
+ expect(
+ screen
+ .getAllByRole('button', { expanded: true })
+ .map((trigger) => trigger.textContent)
+ ).toEqual([
+ 'Direct messages',
+ 'Groups',
+ 'Communities',
+ 'Launch',
+ 'Building',
+ ]);
+ const launchList = within(screen.getByRole('list', { name: 'Launch' }));
const design = within(
- addable.getByText('Launch · Design').closest('li') as HTMLElement
+ launchList.getByText('Design').closest('li') as HTMLElement
);
expect(design.getByText('Community group')).toBeTruthy();
- expect(addable.getByText('Launch · Announcements')).toBeTruthy();
- expect(addable.getByText('Announcement group')).toBeTruthy();
- expect(addable.getByText('Night shift')).toBeTruthy();
+ expect(launchList.getByText('Announcement group')).toBeTruthy();
expect(
- addable.getAllByRole('button', { name: 'Add to Macro' })
- ).toHaveLength(3);
+ screen.getAllByRole('button', { name: 'Add to Macro' })
+ ).toHaveLength(5);
+
+ // Folding a community is remembered.
+ fireEvent.click(screen.getByRole('button', { name: 'Building' }));
+ expect(
+ fake.capabilities.sections.isOpen('community:[email protected]')
+ ).toBe(false);
fireEvent.click(
screen.getByRole('button', { name: /Can't be added \(1\)/ })
);
@@ -424,14 +638,16 @@ describe('connected', () => {
'A community has no messages of its own; add one of its groups'
)
).toBeTruthy();
- // Searching the community finds its groups.
+ // Searching the community finds its groups, and only them.
fireEvent.input(
screen.getByRole('searchbox', { name: 'Search WhatsApp chats' }),
{
target: { value: 'launch' },
}
);
- expect(addable.getByText('Launch · Design')).toBeTruthy();
+ expect(names('Launch')).toEqual(['Design', 'Announcements']);
+ expect(screen.queryByRole('list', { name: 'Groups' })).toBeNull();
+ expect(screen.queryByRole('list', { name: 'Building' })).toBeNull();
});
it('says exactly why adding failed, on the group it failed for', async () => {
@@ -538,6 +754,22 @@ describe('passkey', () => {
expect(fake.capabilities.cancelPairing).not.toHaveBeenCalled();
});
+ it('says a handed-off pairing that cannot be read did not finish, and offers a new code', async () => {
+ const fake = createFakeWhatsApp({ account: null });
+ mount(fake, '01920000-0000-7000-8000-000000000009');
+ const dialog = within(await screen.findByRole('dialog'));
+ expect(dialog.getByText('Preparing code…')).toBeTruthy();
+
+ fake.failPairingRead('01920000-0000-7000-8000-000000000009');
+ expect(dialog.getByRole('alert').textContent).toBe(
+ "Linking didn't finish."
+ );
+ fireEvent.click(dialog.getByRole('button', { name: 'Show a new code' }));
+ await waitFor(() =>
+ expect(fake.capabilities.connect).toHaveBeenCalledOnce()
+ );
+ });
+
it('opens a handed-off pairing at once in desktop', async () => {
const fake = createFakeWhatsApp({ account: null });
mount(fake, '01920000-0000-7000-8000-000000000009');
diff --git a/apps/web/src/features/whatsapp-linked/views/whatsapp-page.tsx b/apps/web/src/features/whatsapp-linked/views/whatsapp-page.tsx
index e38eecc118..706a83dd51 100644
--- a/apps/web/src/features/whatsapp-linked/views/whatsapp-page.tsx
+++ b/apps/web/src/features/whatsapp-linked/views/whatsapp-page.tsx
@@ -1,21 +1,23 @@
import { SearchBar } from '@app/components/view-shell';
import { ViewSkeleton } from '@app/components/view-shell/ViewSkeleton';
+import { toast } from '@core/component/Toast/Toast';
+import { isMobile } from '@core/mobile/isMobile';
import { fireAndForget } from '@core/util/fireAndForget';
import { Button, ConfirmDialog } from '@ui';
-import { createSignal, type JSX, Match, onMount, Show, Switch } from 'solid-js';
+import { createSignal, Match, onMount, Show, Switch } from 'solid-js';
import { match } from 'ts-pattern';
import { AccountStrip, ConnectCard } from '../components/account-card';
-import {
- AddableChatList,
- ChatSectionHeading,
- InMacroChatList,
- UnsupportedChatList,
-} from '../components/chat-list';
+import { ChatList, UnsupportedChatList } from '../components/chat-list';
+import { ConversationSectionList } from '../components/conversation-sections';
import { PairingDialog, type PasskeyMode } from '../components/pairing-dialog';
import { useWhatsAppLinked } from '../context/whatsapp-linked-context';
import { accountStatus } from '../core/account';
import { adoptFailureMessage } from '../core/adopt';
-import { chatSections, type WhatsAppChat } from '../core/chat';
+import {
+ chatSections,
+ conversationSections,
+ type WhatsAppChat,
+} from '../core/chat';
import { createPairingFlow } from '../primitives/pairing-flow';
function Notice(props: { children: string }) {
@@ -37,19 +39,6 @@ function LoadFailure(props: { what: string; onRetry: () => void }) {
);
}
-function ChatSection(props: {
- id: string;
- title: string;
- children: JSX.Element;
-}) {
- return (
- <section class="flex flex-col" aria-labelledby={props.id}>
- <ChatSectionHeading id={props.id}>{props.title}</ChatSectionHeading>
- {props.children}
- </section>
- );
-}
-
/**
* The External tab's WhatsApp page: link an account, then add its chats from
* WhatsApp's chat list, newest activity first.
@@ -93,21 +82,19 @@ export function WhatsAppPage(props: {
.exhaustive();
};
const [confirmingDisconnect, setConfirmingDisconnect] = createSignal(false);
- const [notice, setNotice] = createSignal<string>();
const [adding, setAdding] = createSignal<ReadonlySet<string>>(new Set());
const [addErrors, setAddErrors] = createSignal<Record<string, string>>({});
const disconnect = async (generation: number) => {
- setNotice(undefined);
const result = await whatsapp.disconnect(generation);
setConfirmingDisconnect(false);
if (result.isErr()) {
- setNotice("Couldn't disconnect WhatsApp. Try again.");
+ toast.failure("Couldn't disconnect WhatsApp. Try again.");
return;
}
// WhatsApp unlinks the device asynchronously; its Linked devices list is
// the authority either way.
- setNotice(
+ toast.success(
result.value.remoteUnlinkRequested
? 'Disconnected. Macro will disappear from WhatsApp → Linked devices on your phone shortly.'
: 'Disconnected in Macro. To finish, remove Macro under WhatsApp → Linked devices on your phone.'
@@ -138,9 +125,11 @@ export function WhatsAppPage(props: {
<div class="flex min-w-0 flex-col">
<Switch>
<Match when={whatsapp.account.isPending}>
- <p role="status" class="px-4 py-4 text-sm text-ink-muted">
- Loading your WhatsApp connection…
- </p>
+ <ViewSkeleton.Rows
+ label="Loading your WhatsApp connection"
+ count={2}
+ class="px-2 py-3"
+ />
</Match>
<Match when={!status()}>
<LoadFailure
@@ -170,53 +159,53 @@ export function WhatsAppPage(props: {
/>
</div>
</div>
- <Show when={pairing.startFailed()}>
- <Notice>Couldn't start linking WhatsApp. Try again.</Notice>
- </Show>
- <Show when={notice()}>
- {(text) => <Notice>{text()}</Notice>}
- </Show>
</div>
<Switch>
<Match when={chats.data}>
{(list) => {
const sections = () => chatSections(list(), query());
const searching = () => query().trim() !== '';
+ const kinds = () => conversationSections(sections().listed);
return (
<>
{/* External's sidebar (or the phone's drill-in list)
already lists added chats; here only search hits. */}
- <Show when={searching() && sections().inMacro.length}>
- <ChatSection id="whatsapp-in-macro" title="In Macro">
- <InMacroChatList
- chats={sections().inMacro}
- onOpenGroup={whatsapp.openGroup}
- />
- </ChatSection>
- </Show>
- <ChatSection
- id="whatsapp-add-groups"
- title="Add to Macro"
- >
- <AddableChatList
- chats={sections().addable}
- canAdd={whatsapp.features.data?.adoption ?? false}
- adding={adding()}
- errors={addErrors()}
- empty={
- searching()
- ? 'No chats to add match your search.'
- : 'Every WhatsApp chat you can add is already in Macro.'
- }
- onAdd={(chat) =>
- fireAndForget(
- adopt(chat),
- 'whatsapp-linked.adopt'
- )
+ <div class="flex flex-col gap-(--sidebar-section-gap) px-2 pt-3">
+ <ConversationSectionList
+ sections={kinds()}
+ // A search shows its matches in every section.
+ isOpen={(id) =>
+ searching() || whatsapp.sections.isOpen(id)
}
- onOpenGroup={whatsapp.openGroup}
+ onOpenChange={whatsapp.sections.setOpen}
+ list={(items, label) => (
+ <ChatList
+ label={label}
+ chats={items}
+ inCommunity={items[0]?.community !== undefined}
+ canAdd={
+ whatsapp.features.data?.adoption ?? false
+ }
+ adding={adding()}
+ errors={addErrors()}
+ onAdd={(chat) =>
+ fireAndForget(
+ adopt(chat),
+ 'whatsapp-linked.adopt'
+ )
+ }
+ onOpenGroup={whatsapp.openGroup}
+ />
+ )}
/>
- </ChatSection>
+ </div>
+ <Show when={!sections().listed.length}>
+ <p class="px-4 py-2 text-sm text-ink-extra-muted">
+ {searching()
+ ? 'No chats to add match your search.'
+ : 'Every WhatsApp chat you can add is already in Macro.'}
+ </p>
+ </Show>
<Show when={sections().unsupported.length}>
<UnsupportedChatList
chats={sections().unsupported}
@@ -252,14 +241,14 @@ export function WhatsAppPage(props: {
<div class="flex flex-col gap-3 px-4 py-4">
<ConnectCard
reconnect={current().reconnect}
+ phone={isMobile()}
unavailable={whatsapp.features.data?.pairing === false}
pending={whatsapp.isConnecting()}
onConnect={() => pairing.start()}
/>
- <Show when={pairing.startFailed()}>
+ <Show when={pairing.startFailed() && !pairing.open()}>
<Notice>Couldn't start linking WhatsApp. Try again.</Notice>
</Show>
- <Show when={notice()}>{(text) => <Notice>{text()}</Notice>}</Show>
</div>
)}
</Match>
@@ -267,7 +256,8 @@ export function WhatsAppPage(props: {
<PairingDialog
open={pairing.open()}
step={pairing.step()}
- secondsLeft={pairing.secondsLeft()}
+ refreshing={pairing.refreshing()}
+ retryFailed={pairing.startFailed()}
passkey={passkeyMode()}
ceremony={pairing.passkey()}
onConfirmPasskey={() =>
diff --git a/apps/web/src/features/whatsapp-linked/whatsapp-linked.tsx b/apps/web/src/features/whatsapp-linked/whatsapp-linked.tsx
index 8713b4982e..89accbabfd 100644
--- a/apps/web/src/features/whatsapp-linked/whatsapp-linked.tsx
+++ b/apps/web/src/features/whatsapp-linked/whatsapp-linked.tsx
@@ -1,6 +1,8 @@
import { useNavigate } from '@app/lib/split-router';
import { externalWhatsappGroupRoute } from '@app/routes/routes';
+import { useUserId } from '@core/context/user';
import { WhatsAppLinkedProvider } from './context/whatsapp-linked-context';
+import { createOpenSections } from './primitives/open-sections';
import { createWhatsAppLinkedCapabilities } from './queries/production-capabilities';
import { WhatsAppPage } from './views/whatsapp-page';
@@ -10,6 +12,10 @@ export function WhatsAppLinked(props: { resumePairingId?: string }) {
const capabilities = createWhatsAppLinkedCapabilities({
openGroup: (groupId) =>
navigate({ route: externalWhatsappGroupRoute, params: { groupId } }),
+ sections: createOpenSections(
+ 'macro:whatsapp:chat-sections:v2',
+ useUserId()
+ ),
});
return (
<WhatsAppLinkedProvider value={capabilities}>
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.test.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.test.tsx
index 3d38745a0a..e9da85d163 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.test.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.test.tsx
@@ -67,8 +67,28 @@ vi.mock('@queries/whatsapp-groups', () => ({
return userId() !== '';
},
data: [
- { id: 'group-1', name: 'Design Crit', unreadCount: 0, canSend: true },
- { id: 'group-2', name: 'Launch Room', unreadCount: 0, canSend: true },
+ {
+ id: 'group-1',
+ name: 'Design Crit',
+ ownerId: 'macro|[email protected]',
+ unreadCount: 0,
+ canSend: true,
+ },
+ {
+ id: 'group-2',
+ name: 'Launch Room',
+ ownerId: 'macro|[email protected]',
+ unreadCount: 0,
+ canSend: true,
+ },
+ // Shared with the viewer: only its owner may share it on.
+ {
+ id: 'group-3',
+ name: 'Design Review',
+ ownerId: 'macro|[email protected]',
+ unreadCount: 0,
+ canSend: false,
+ },
],
}),
}));
@@ -456,7 +476,7 @@ it('records mentions against the editing source outside a legacy block', () => {
);
});
-it('offers WhatsApp groups to share by mention, only in channel composers', () => {
+it("offers the viewer's own WhatsApp chats to share by mention, only in channel composers", () => {
mocks.whatsappEnabled = true;
Element.prototype.scrollIntoView = vi.fn();
vi.mocked(useEmailSearchMention).mockReturnValue({
@@ -481,6 +501,7 @@ it('offers WhatsApp groups to share by mention, only in channel composers', () =
expect(screen.getByText('WhatsApp chats')).toBeTruthy();
expect(screen.getByText('Design Crit')).toBeTruthy();
expect(screen.queryByText('Launch Room')).toBeNull();
+ expect(screen.queryByText('Design Review')).toBeNull();
cleanup();
mocks.whatsappUserIds = [];
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx
index 09153d52e0..d0375ff493 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx
@@ -264,7 +264,8 @@ function MentionsMenuInner(props: MentionsMenuProps) {
enabled: () => !props.sources || props.sources.includes('emails'),
});
- // A WhatsApp group mentioned in a channel is shared with its members.
+ // A WhatsApp chat mentioned in a channel is shared with its members; only
+ // its owner can do that, so only the viewer's own chats are offered.
const whatsappGroupsEnabled = () =>
!hasCustomEntities() &&
props.block === 'channel' &&
@@ -280,7 +281,11 @@ function MentionsMenuInner(props: MentionsMenuProps) {
return [];
const term = searchTerm().trim().toLocaleLowerCase();
return whatsappGroupsQuery.data
- .filter((group) => group.name.toLocaleLowerCase().includes(term))
+ .filter(
+ (group) =>
+ group.ownerId === userId() &&
+ group.name.toLocaleLowerCase().includes(term)
+ )
.map((group) => ({
kind: 'whatsappGroup',
id: group.id,
diff --git a/apps/web/src/lib/queries/whatsapp-groups/sync.ts b/apps/web/src/lib/queries/whatsapp-groups/sync.ts
index 97df959488..987eb42b36 100644
--- a/apps/web/src/lib/queries/whatsapp-groups/sync.ts
+++ b/apps/web/src/lib/queries/whatsapp-groups/sync.ts
@@ -15,7 +15,7 @@ import { whatsappGroupsKeys } from './keys';
const WHATSAPP_CHANGED_MESSAGE_TYPE = 'whatsapp_changed';
const whatsappChangedSchema = z.discriminatedUnion('scope', [
z.object({ scope: z.literal('groups') }),
- z.object({ scope: z.literal('group'), group_id: z.string() }),
+ z.object({ scope: z.literal('group'), groupId: z.string() }),
]);
type WhatsappChange = z.infer<typeof whatsappChangedSchema>;
@@ -93,7 +93,7 @@ export function useWhatsappGroupSync(
)
);
onWhatsappChanged((change) => {
- if (change.scope !== 'group' || change.group_id !== groupId()) return;
+ if (change.scope !== 'group' || change.groupId !== groupId()) return;
cancel();
fireAndForget(refreshGroup(userId(), groupId()), 'whatsapp-sync');
});
diff --git a/apps/web/src/lib/queries/whatsapp-linked/index.ts b/apps/web/src/lib/queries/whatsapp-linked/index.ts
index c5ccf23cd9..7fe71b8c09 100644
--- a/apps/web/src/lib/queries/whatsapp-linked/index.ts
+++ b/apps/web/src/lib/queries/whatsapp-linked/index.ts
@@ -35,7 +35,9 @@ function pairingOptions(userId: string, pairingId: string) {
gcTime: 0,
staleTime: 0,
retry: false,
- refetchInterval: PAIRING_POLL_MS,
+ // A pairing that can't be read (gone, or someone else's) never comes back.
+ refetchInterval: (query) =>
+ query.state.status === 'error' ? false : PAIRING_POLL_MS,
refetchIntervalInBackground: false,
});
}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/adoptedGroup.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/adoptedGroup.ts
index 2a975e6df7..273ab41a7f 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/adoptedGroup.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/adoptedGroup.ts
@@ -10,5 +10,5 @@
*/
export interface AdoptedGroup {
/** Shareable entity identifier. */
- group_id: string;
+ groupId: string;
}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
index 62514ee5e2..807b732500 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
@@ -1232,13 +1232,7 @@ export * from './linkedDeliveryState';
export * from './linkedDisconnect';
export * from './linkedDisconnectRequest';
export * from './linkedFeatures';
-export * from './linkedGroupInfo';
-export * from './linkedGroupInfoCommunityJid';
-export * from './linkedGroupInfoDisappearingSeconds';
export * from './linkedGroupReference';
-export * from './linkedIdentity';
-export * from './linkedIdentityAlternateJid';
-export * from './linkedIdentityDisplayName';
export * from './linkedMediaKind';
export * from './linkedMediaPresentation';
export * from './linkedMessageAttachments';
@@ -1251,8 +1245,6 @@ export * from './linkedPairStateChallengeAnyOf';
export * from './linkedPairStateCode';
export * from './linkedPairStateIdentityJid';
export * from './linkedPairStateQr';
-export * from './linkedParticipant';
-export * from './linkedParticipantAllOf';
export * from './linkedPasskeyBody';
export * from './linkedReplyBlock';
export * from './linkedReplyContent';
@@ -2267,7 +2259,6 @@ export * from './whatsAppEventLocation';
export * from './whatsAppEventStartAt';
export * from './whatsAppGroupDetail';
export * from './whatsAppGroupDetailAllOf';
-export * from './whatsAppGroupDetailAllOfCommunity';
export * from './whatsAppGroupDetailAllOfDisappearingSeconds';
export * from './whatsAppGroupDetailAllOfRoster';
export * from './whatsAppGroupDetailAllOfSendingIdentity';
@@ -2283,6 +2274,7 @@ export * from './whatsAppGroupSender';
export * from './whatsAppGroupSenderUserId';
export * from './whatsAppGroupSummary';
export * from './whatsAppGroupSummaryBackfill';
+export * from './whatsAppGroupSummaryCommunity';
export * from './whatsAppGroupSummaryLastMessageAt';
export * from './whatsAppGroupSummarySendReason';
export * from './whatsAppLocation';
@@ -2293,6 +2285,9 @@ export * from './whatsAppLocationUrl';
export * from './whatsAppMention';
export * from './whatsAppMentionAllOf';
export * from './whatsAppMessageKind';
+export * from './whatsAppParticipant';
+export * from './whatsAppParticipantAlternateJid';
+export * from './whatsAppParticipantDisplayName';
export * from './whatsAppPersonRef';
export * from './whatsAppPersonRefUserId';
export * from './whatsAppPoll';
@@ -2313,6 +2308,7 @@ export * from './whatsAppRichContentOneOfOnezeroAllOfType';
export * from './whatsAppRichContentOneOfSeven';
export * from './whatsAppRichContentOneOfSevenAllOf';
export * from './whatsAppRichContentOneOfSevenAllOfType';
+export * from './whatsAppRoster';
export * from './whatsAppSystemAction';
export * from './whatsAppSystemLine';
export * from './whatsAppSystemLineActor';
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedAccount.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedAccount.ts
index 351809a3c7..918dc02e66 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedAccount.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedAccount.ts
@@ -12,13 +12,13 @@ import type { LinkedAccountState } from './linkedAccountState';
*/
export interface LinkedAccount {
/** Explicit consent generation; reconnecting a socket never changes it. */
- authorization_generation: number;
+ authorizationGeneration: number;
/** Stable account identity. */
id: string;
/** WhatsApp-verified identity, absent until the first pairing succeeds. */
- identity_jid?: LinkedAccountIdentityJid;
+ identityJid?: LinkedAccountIdentityJid;
/** Lifecycle. */
state: LinkedAccountState;
/** Authenticated owner. */
- user_id: string;
+ userId: string;
}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedAdoptGroup.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedAdoptGroup.ts
index b63d0c0f37..1242fe437a 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedAdoptGroup.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedAdoptGroup.ts
@@ -12,5 +12,5 @@ group's name always follows WhatsApp.
export interface LinkedAdoptGroup {
/** A group the requester's account has joined, or a direct chat from
their chat list (the other person's JID, as the list names it). */
- group_jid: string;
+ groupJid: string;
}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedAttachment.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedAttachment.ts
index f535bab6eb..bb96bf732c 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedAttachment.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedAttachment.ts
@@ -16,14 +16,14 @@ import type { LinkedAttachmentWidth } from './linkedAttachmentWidth';
*/
export interface LinkedAttachment {
/** The private document, once ready. */
- document_id?: LinkedAttachmentDocumentId;
+ documentId?: LinkedAttachmentDocumentId;
/**
* Length of audio or video in whole seconds, when declared.
* @minimum 0
*/
- duration_seconds?: LinkedAttachmentDurationSeconds;
+ durationSeconds?: LinkedAttachmentDurationSeconds;
/** Display filename. */
- file_name: string;
+ fileName: string;
/**
* Pixel height, when declared.
* @minimum 0
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedBackfillState.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedBackfillState.ts
index 1f13e8293e..9c9244484e 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedBackfillState.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedBackfillState.ts
@@ -13,6 +13,7 @@ export type LinkedBackfillState =
// eslint-disable-next-line @typescript-eslint/no-redeclare
export const LinkedBackfillState = {
+ waiting_for_message: 'waiting_for_message',
pending: 'pending',
running: 'running',
waiting_for_phone: 'waiting_for_phone',
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedCapabilities.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedCapabilities.ts
index 4cf21867f3..b3e0b72fea 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedCapabilities.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedCapabilities.ts
@@ -14,24 +14,24 @@ export interface LinkedCapabilities {
* Largest attachment in bytes.
* @minimum 0
*/
- attachment_limit_bytes: number;
+ attachmentLimitBytes: number;
/** Supported attachment MIME types. */
- attachment_types: string[];
+ attachmentTypes: string[];
/**
* Attachments per send.
* @minimum 0
*/
- max_attachments: number;
+ maxAttachments: number;
/**
* Edits and deletes are offered this long after sending.
* @minimum 0
*/
- mutation_window_seconds: number;
+ mutationWindowSeconds: number;
/** Supported message operations. */
mutations: LinkedMutation[];
/**
* Maximum UTF-8 bytes per text send.
* @minimum 0
*/
- text_limit_bytes: number;
+ textLimitBytes: number;
}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedDeliveryState.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedDeliveryState.ts
index 6fc9b6f3e6..d34543e174 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedDeliveryState.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedDeliveryState.ts
@@ -18,8 +18,5 @@ export const LinkedDeliveryState = {
sending: 'sending',
unknown: 'unknown',
accepted: 'accepted',
- sent: 'sent',
- delivered: 'delivered',
- read: 'read',
failed: 'failed',
} as const;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedDisconnect.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedDisconnect.ts
index fd9bbdb397..b1dd7a310d 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedDisconnect.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedDisconnect.ts
@@ -11,5 +11,5 @@
export interface LinkedDisconnect {
/** The session service was asked to log the device out of WhatsApp. It
unlinks asynchronously; WhatsApp's Linked devices list is authoritative. */
- remote_unlink_requested: boolean;
+ remoteUnlinkRequested: boolean;
}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedDisconnectRequest.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedDisconnectRequest.ts
index ecd31dcda4..dc000ad12c 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedDisconnectRequest.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedDisconnectRequest.ts
@@ -10,5 +10,5 @@
*/
export interface LinkedDisconnectRequest {
/** Fences retries against a later reconnect or replacement. */
- authorization_generation: number;
+ authorizationGeneration: number;
}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedGroupInfo.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedGroupInfo.ts
deleted file mode 100644
index da06e832d9..0000000000
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedGroupInfo.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * document_storage_service
- * OpenAPI spec version: 0.1.0
- */
-import type { LinkedGroupInfoCommunityJid } from './linkedGroupInfoCommunityJid';
-import type { LinkedGroupInfoDisappearingSeconds } from './linkedGroupInfoDisappearingSeconds';
-import type { LinkedParticipant } from './linkedParticipant';
-
-/**
- * One full metadata read of a group, never an incomplete membership delta.
- */
-export interface LinkedGroupInfo {
- /** Only admins may post. */
- announce: boolean;
- /** The community's announcement group (everyone reads, admins post). */
- communityAnnouncements?: boolean;
- /** The community a linked subgroup or announcement group belongs to. */
- communityJid?: LinkedGroupInfoCommunityJid;
- /** The community itself: it has no messages of its own and can't be added. */
- communityParent?: boolean;
- /**
- * Disappearing-messages timer in seconds while it is on. Macro keeps the
-messages; its sends carry the timer so phones treat them like their own.
- * @minimum 0
- */
- disappearingSeconds?: LinkedGroupInfoDisappearingSeconds;
- /** Remote group JID. */
- jid: string;
- /** Current subject. */
- name: string;
- /** When the session service read this metadata. */
- observedAt: string;
- /** Full roster. */
- participants: LinkedParticipant[];
-}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedGroupInfoDisappearingSeconds.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedGroupInfoDisappearingSeconds.ts
deleted file mode 100644
index 8dde4a28ec..0000000000
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedGroupInfoDisappearingSeconds.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * document_storage_service
- * OpenAPI spec version: 0.1.0
- */
-
-/**
- * Disappearing-messages timer in seconds while it is on. Macro keeps the
-messages; its sends carry the timer so phones treat them like their own.
- * @minimum 0
- */
-export type LinkedGroupInfoDisappearingSeconds = number | null;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedIdentity.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedIdentity.ts
deleted file mode 100644
index 5a0baa5454..0000000000
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedIdentity.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * document_storage_service
- * OpenAPI spec version: 0.1.0
- */
-import type { LinkedIdentityAlternateJid } from './linkedIdentityAlternateJid';
-import type { LinkedIdentityDisplayName } from './linkedIdentityDisplayName';
-
-/**
- * Verified sender aliases, supplied only by protocol metadata.
- */
-export interface LinkedIdentity {
- /** Verified alternate identity, never inferred from a name or phone typed by a user. */
- alternateJid?: LinkedIdentityAlternateJid;
- /** Untrusted display name. */
- displayName?: LinkedIdentityDisplayName;
- /** Phone-number or LID account JID. */
- jid: string;
-}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedIdentityAlternateJid.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedIdentityAlternateJid.ts
deleted file mode 100644
index 17f430197a..0000000000
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedIdentityAlternateJid.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * document_storage_service
- * OpenAPI spec version: 0.1.0
- */
-
-/**
- * Verified alternate identity, never inferred from a name or phone typed by a user.
- */
-export type LinkedIdentityAlternateJid = string | null;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedMessageAttachments.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedMessageAttachments.ts
index cbfa42e6f9..2a82c44ef5 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedMessageAttachments.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedMessageAttachments.ts
@@ -11,7 +11,7 @@ import type { LinkedAttachment } from './linkedAttachment';
*/
export interface LinkedMessageAttachments {
/** Its attachments in order; deleted ones are omitted. */
- linked_attachments: LinkedAttachment[];
+ linkedAttachments: LinkedAttachment[];
/** Group message. */
- message_id: string;
+ messageId: string;
}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedPairing.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedPairing.ts
index 62abc0f3fb..a0b81c8b8e 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedPairing.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedPairing.ts
@@ -11,9 +11,9 @@ import type { LinkedPairingState } from './linkedPairingState';
*/
export interface LinkedPairing {
/** Account being connected. */
- account_id: string;
+ accountId: string;
/** Database-assigned deadline. */
- expires_at: string;
+ expiresAt: string;
/** One-use transaction id. */
id: string;
/** Current state. */
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedParticipant.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedParticipant.ts
deleted file mode 100644
index 50f5332bbd..0000000000
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedParticipant.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * document_storage_service
- * OpenAPI spec version: 0.1.0
- */
-import type { LinkedIdentity } from './linkedIdentity';
-import type { LinkedParticipantAllOf } from './linkedParticipantAllOf';
-
-/**
- * Current remote participant; Macro access is a separate grant.
- */
-export type LinkedParticipant = LinkedIdentity & LinkedParticipantAllOf;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedParticipantAllOf.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedParticipantAllOf.ts
deleted file mode 100644
index 1dc78da42c..0000000000
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedParticipantAllOf.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * document_storage_service
- * OpenAPI spec version: 0.1.0
- */
-
-export type LinkedParticipantAllOf = {
- /** Group admin; only admins post in announcement groups. */
- admin: boolean;
-};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedReplyContentOneOfSix.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedReplyContentOneOfSix.ts
index 0bab43c612..04af63bf9a 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedReplyContentOneOfSix.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedReplyContentOneOfSix.ts
@@ -13,7 +13,7 @@ import type { LinkedReplyContentOneOfSixType } from './linkedReplyContentOneOfSi
*/
export type LinkedReplyContentOneOfSix = {
/** Existing group message, resolved to its WhatsApp source by the server. */
- message_id: string;
+ messageId: string;
/** Explicit operation. */
operation: LinkedMutation;
/** Replacement text or emoji; absent for delete, empty to remove a reaction. */
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedReplyContentOneOfThree.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedReplyContentOneOfThree.ts
index a93577a825..7f6b620b91 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedReplyContentOneOfThree.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedReplyContentOneOfThree.ts
@@ -15,5 +15,5 @@ export type LinkedReplyContentOneOfThree = {
caption?: LinkedReplyContentOneOfThreeCaption;
type: LinkedReplyContentOneOfThreeType;
/** The staged upload, which becomes the message's private document. */
- upload_id: string;
+ uploadId: string;
};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedSendProgress.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedSendProgress.ts
index 8e3e038eae..ca582f2a09 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedSendProgress.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedSendProgress.ts
@@ -15,19 +15,19 @@ import type { LinkedSendReply } from './linkedSendReply';
*/
export interface LinkedSendProgress {
/** Intent creation time. */
- created_at: string;
+ createdAt: string;
/** Sanitized failure code. */
- error_code?: LinkedSendProgressErrorCode;
+ errorCode?: LinkedSendProgressErrorCode;
/** Group entity. */
- group_id: string;
+ groupId: string;
/** Stable intent id. */
id: string;
/** Group message, once WhatsApp accepted it. */
- message_id?: LinkedSendProgressMessageId;
+ messageId?: LinkedSendProgressMessageId;
/** The original request, so a failed draft can be recovered. */
payload: LinkedSendReply;
/** Current state. */
state: LinkedDeliveryState;
/** Person who submitted it. */
- user_id: string;
+ userId: string;
}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedSendReply.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedSendReply.ts
index 3885f4212a..b0a3c6892d 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedSendReply.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedSendReply.ts
@@ -12,9 +12,9 @@ import type { LinkedSendReplyReplyTo } from './linkedSendReplyReplyTo';
*/
export interface LinkedSendReply {
/** Stable client intent key. A changed payload with this key is a conflict. */
- idempotency_key: string;
+ idempotencyKey: string;
/** Content. */
message: LinkedReplyContent;
/** Group message being quoted, within this group. */
- reply_to?: LinkedSendReplyReplyTo;
+ replyTo?: LinkedSendReplyReplyTo;
}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedUploadedAttachment.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedUploadedAttachment.ts
index 19919548f6..3359ba0e21 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedUploadedAttachment.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedUploadedAttachment.ts
@@ -15,5 +15,5 @@ export interface LinkedUploadedAttachment {
/** Category. */
kind: LinkedMediaKind;
/** Use as `upload_id` in a media send; also the future document id. */
- upload_id: string;
+ uploadId: string;
}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/markRead.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/markRead.ts
index a2e62b8966..5b51b829f5 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/markRead.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/markRead.ts
@@ -10,5 +10,5 @@
*/
export interface MarkRead {
/** Message in the addressed group. */
- message_id: string;
+ messageId: string;
}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupDetailAllOf.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupDetailAllOf.ts
index 52417dbd1f..0a8ca22523 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupDetailAllOf.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupDetailAllOf.ts
@@ -7,26 +7,24 @@
import type { AccessLevel } from './accessLevel';
import type { LinkedCapabilities } from './linkedCapabilities';
import type { SharePermissionV2 } from './sharePermissionV2';
-import type { WhatsAppGroupDetailAllOfCommunity } from './whatsAppGroupDetailAllOfCommunity';
import type { WhatsAppGroupDetailAllOfDisappearingSeconds } from './whatsAppGroupDetailAllOfDisappearingSeconds';
import type { WhatsAppGroupDetailAllOfRoster } from './whatsAppGroupDetailAllOfRoster';
import type { WhatsAppGroupDetailAllOfSendingIdentity } from './whatsAppGroupDetailAllOfSendingIdentity';
export type WhatsAppGroupDetailAllOf = {
/** Caller's effective permission. */
- access_level: AccessLevel;
- community?: WhatsAppGroupDetailAllOfCommunity;
+ accessLevel: AccessLevel;
/**
* WhatsApp's disappearing-messages timer in seconds while it is on;
Macro keeps the messages anyway. `null` when off or unknown.
* @minimum 0
*/
- disappearing_seconds?: WhatsAppGroupDetailAllOfDisappearingSeconds;
+ disappearingSeconds?: WhatsAppGroupDetailAllOfDisappearingSeconds;
/** Size and mutation limits. */
limits: LinkedCapabilities;
roster?: WhatsAppGroupDetailAllOfRoster;
/** Caller's own phone identity, never another account's identity. */
- sending_identity?: WhatsAppGroupDetailAllOfSendingIdentity;
+ sendingIdentity?: WhatsAppGroupDetailAllOfSendingIdentity;
/** Owner-controlled standard sharing configuration. */
- share_permission: SharePermissionV2;
+ sharePermission: SharePermissionV2;
};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupDetailAllOfRoster.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupDetailAllOfRoster.ts
index 2a181e694f..4ff94ebc65 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupDetailAllOfRoster.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupDetailAllOfRoster.ts
@@ -4,6 +4,6 @@
* document_storage_service
* OpenAPI spec version: 0.1.0
*/
-import type { LinkedGroupInfo } from './linkedGroupInfo';
+import type { WhatsAppRoster } from './whatsAppRoster';
-export type WhatsAppGroupDetailAllOfRoster = null | LinkedGroupInfo;
+export type WhatsAppGroupDetailAllOfRoster = null | WhatsAppRoster;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupMessage.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupMessage.ts
index efba0f7ad7..0ea9ad5e61 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupMessage.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupMessage.ts
@@ -24,9 +24,9 @@ export interface WhatsAppGroupMessage {
body: string;
/** Deleted for everyone. */
deleted: boolean;
- delivery_state?: WhatsAppGroupMessageDeliveryState;
+ deliveryState?: WhatsAppGroupMessageDeliveryState;
/** Last edit timestamp. */
- edited_at?: WhatsAppGroupMessageEditedAt;
+ editedAt?: WhatsAppGroupMessageEditedAt;
/** Forwarded from another chat. */
forwarded: boolean;
/** Stable message id. */
@@ -38,14 +38,14 @@ export interface WhatsAppGroupMessage {
/** Reactions grouped by emoji. */
reactions: WhatsAppGroupReaction[];
/** Timestamp first received by Macro. */
- received_at: string;
+ receivedAt: string;
/** Message quoted by this one. */
- reply_to?: WhatsAppGroupMessageReplyTo;
+ replyTo?: WhatsAppGroupMessageReplyTo;
rich?: WhatsAppGroupMessageRich;
/** Sender. */
sender: WhatsAppGroupSender;
/** Timestamp assigned by WhatsApp. */
- sent_at: string;
+ sentAt: string;
/** Sent as view-once in WhatsApp; Macro shows it like any media. */
- view_once: boolean;
+ viewOnce: boolean;
}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupMessages.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupMessages.ts
index 73ee866e55..74bea2f8b8 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupMessages.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupMessages.ts
@@ -14,5 +14,5 @@ export interface WhatsAppGroupMessages {
/** Messages in descending sent_at, id order. */
messages: WhatsAppGroupMessage[];
/** Cursor for older messages. */
- next_cursor?: WhatsAppGroupMessagesNextCursor;
+ nextCursor?: WhatsAppGroupMessagesNextCursor;
}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupSender.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupSender.ts
index f8e4aee062..522f932d78 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupSender.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupSender.ts
@@ -13,7 +13,7 @@ export interface WhatsAppGroupSender {
/** Display name, never authentication evidence. */
name: string;
/** External person identity. */
- person_id: string;
+ personId: string;
/** Verified Macro user association, if present. */
- user_id?: WhatsAppGroupSenderUserId;
+ userId?: WhatsAppGroupSenderUserId;
}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupSummary.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupSummary.ts
index f00b7fbb10..8099f0ad5d 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupSummary.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupSummary.ts
@@ -7,6 +7,7 @@
import type { LinkedChatKind } from './linkedChatKind';
import type { WhatsAppGroupSummaryBackfill } from './whatsAppGroupSummaryBackfill';
+import type { WhatsAppGroupSummaryCommunity } from './whatsAppGroupSummaryCommunity';
import type { WhatsAppGroupSummaryLastMessageAt } from './whatsAppGroupSummaryLastMessageAt';
import type { WhatsAppGroupSummarySendReason } from './whatsAppGroupSummarySendReason';
@@ -16,18 +17,20 @@ import type { WhatsAppGroupSummarySendReason } from './whatsAppGroupSummarySendR
export interface WhatsAppGroupSummary {
backfill?: WhatsAppGroupSummaryBackfill;
/** Caller may currently send from their own account. */
- can_send: boolean;
+ canSend: boolean;
+ community?: WhatsAppGroupSummaryCommunity;
/** Entity identifier. */
id: string;
/** A group, or a direct chat with one person (only its owner sends). */
kind: LinkedChatKind;
/** Latest message timestamp. */
- last_message_at?: WhatsAppGroupSummaryLastMessageAt;
+ lastMessageAt?: WhatsAppGroupSummaryLastMessageAt;
/** Display name: the group's, or a direct chat's other person. */
name: string;
- send_reason?: WhatsAppGroupSummarySendReason;
- /** Unread live messages for this viewer. */
- unread_count: number;
+ sendReason?: WhatsAppGroupSummarySendReason;
+ /** Unread live messages for this viewer, counted up to
+[`UNREAD_COUNT_CAP`]. */
+ unreadCount: number;
/** Actual entity owner. */
- user_id: string;
+ userId: string;
}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupDetailAllOfCommunity.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupSummaryCommunity.ts
similarity index 71%
rename from apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupDetailAllOfCommunity.ts
rename to apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupSummaryCommunity.ts
index 465e5ea72c..6506ed782b 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupDetailAllOfCommunity.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppGroupSummaryCommunity.ts
@@ -6,4 +6,4 @@
*/
import type { LinkedCommunityReference } from './linkedCommunityReference';
-export type WhatsAppGroupDetailAllOfCommunity = null | LinkedCommunityReference;
+export type WhatsAppGroupSummaryCommunity = null | LinkedCommunityReference;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppParticipant.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppParticipant.ts
new file mode 100644
index 0000000000..d9d62baf49
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppParticipant.ts
@@ -0,0 +1,22 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { WhatsAppParticipantAlternateJid } from './whatsAppParticipantAlternateJid';
+import type { WhatsAppParticipantDisplayName } from './whatsAppParticipantDisplayName';
+
+/**
+ * Someone in a WhatsApp chat; Macro access is a separate grant.
+ */
+export interface WhatsAppParticipant {
+ /** Group admin. */
+ admin: boolean;
+ /** The other address WhatsApp verified for them. */
+ alternateJid?: WhatsAppParticipantAlternateJid;
+ /** Their WhatsApp name, untrusted. */
+ displayName?: WhatsAppParticipantDisplayName;
+ /** Phone-number or LID JID. */
+ jid: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedGroupInfoCommunityJid.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppParticipantAlternateJid.ts
similarity index 51%
rename from apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedGroupInfoCommunityJid.ts
rename to apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppParticipantAlternateJid.ts
index 38d4efe096..021a8fdb32 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedGroupInfoCommunityJid.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppParticipantAlternateJid.ts
@@ -6,6 +6,6 @@
*/
/**
- * The community a linked subgroup or announcement group belongs to.
+ * The other address WhatsApp verified for them.
*/
-export type LinkedGroupInfoCommunityJid = string | null;
+export type WhatsAppParticipantAlternateJid = string | null;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedIdentityDisplayName.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppParticipantDisplayName.ts
similarity index 58%
rename from apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedIdentityDisplayName.ts
rename to apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppParticipantDisplayName.ts
index ca75ba0c67..27ef09ab09 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedIdentityDisplayName.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppParticipantDisplayName.ts
@@ -6,6 +6,6 @@
*/
/**
- * Untrusted display name.
+ * Their WhatsApp name, untrusted.
*/
-export type LinkedIdentityDisplayName = string | null;
+export type WhatsAppParticipantDisplayName = string | null;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppRoster.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppRoster.ts
new file mode 100644
index 0000000000..5bc0c30c14
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsAppRoster.ts
@@ -0,0 +1,21 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { WhatsAppParticipant } from './whatsAppParticipant';
+
+/**
+ * A chat's WhatsApp metadata as the caller's account last read it.
+ */
+export interface WhatsAppRoster {
+ /** Only admins may post. */
+ announce: boolean;
+ /** WhatsApp subject. */
+ name: string;
+ /** When this was read from WhatsApp. */
+ observedAt: string;
+ /** Everyone in the chat. */
+ participants: WhatsAppParticipant[];
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsappGroupMessagesParams.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsappGroupMessagesParams.ts
index 11c4cac94f..e9748190af 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsappGroupMessagesParams.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/whatsappGroupMessagesParams.ts
@@ -11,7 +11,7 @@ export type WhatsappGroupMessagesParams = {
*/
before?: string | null;
/**
- * Page size, 1 through 100.
+ * Page size, up to [`PAGE_LIMIT`]; [`DEFAULT_PAGE`] when absent.
*/
limit?: number | null;
};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
index f1f33ff6dc..8caeb78e26 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
@@ -49204,13 +49204,13 @@ export const linkedAccountResponse = zod
zod.null(),
zod
.object({
- authorization_generation: zod
+ authorizationGeneration: zod
.number()
.describe(
'Explicit consent generation; reconnecting a socket never changes it.'
),
id: zod.uuid().describe('Stable account identity.'),
- identity_jid: zod
+ identityJid: zod
.string()
.nullish()
.describe(
@@ -49221,7 +49221,7 @@ export const linkedAccountResponse = zod
.describe(
'Account lifecycle. Transport outages are not stored: a connected account\nstays connected while its session service reconnects.'
),
- user_id: zod.string().describe('Authenticated owner.'),
+ userId: zod.string().describe('Authenticated owner.'),
})
.describe("One person's account, never owned by a workspace."),
])
@@ -49373,8 +49373,8 @@ export const linkedConnectBody = zod
export const linkedConnectResponse = zod
.object({
- account_id: zod.uuid().describe('Account being connected.'),
- expires_at: zod.iso.datetime({}).describe('Database-assigned deadline.'),
+ accountId: zod.uuid().describe('Account being connected.'),
+ expiresAt: zod.iso.datetime({}).describe('Database-assigned deadline.'),
id: zod.uuid().describe('One-use transaction id.'),
state: zod
.enum([
@@ -49395,7 +49395,7 @@ export const linkedConnectResponse = zod
*/
export const linkedDisconnectBody = zod
.object({
- authorization_generation: zod
+ authorizationGeneration: zod
.number()
.describe('Fences retries against a later reconnect or replacement.'),
})
@@ -49403,7 +49403,7 @@ export const linkedDisconnectBody = zod
export const linkedDisconnectResponse = zod
.object({
- remote_unlink_requested: zod
+ remoteUnlinkRequested: zod
.boolean()
.describe(
"The session service was asked to log the device out of WhatsApp. It\nunlinks asynchronously; WhatsApp's Linked devices list is authoritative."
@@ -49416,7 +49416,7 @@ export const linkedDisconnectResponse = zod
*/
export const linkedAdoptBody = zod
.object({
- group_jid: zod
+ groupJid: zod
.string()
.describe(
"A group the requester's account has joined, or a direct chat from\ntheir chat list (the other person's JID, as the list names it)."
@@ -49428,7 +49428,7 @@ export const linkedAdoptBody = zod
export const linkedAdoptResponse = zod
.object({
- group_id: zod.uuid().describe('Shareable entity identifier.'),
+ groupId: zod.uuid().describe('Shareable entity identifier.'),
})
.describe('Adoption response.');
@@ -49514,6 +49514,7 @@ export const whatsappGroupsResponseItem = zod
),
state: zod
.enum([
+ 'waiting_for_message',
'pending',
'running',
'waiting_for_phone',
@@ -49525,21 +49526,35 @@ export const whatsappGroupsResponseItem = zod
.describe('Earlier messages imported after adding a group.'),
])
.optional(),
- can_send: zod
+ canSend: zod
.boolean()
.describe('Caller may currently send from their own account.'),
+ community: zod
+ .union([
+ zod.null(),
+ zod
+ .object({
+ announcements: zod
+ .boolean()
+ .describe("This group is the community's announcement group."),
+ id: zod.string().describe("The community's WhatsApp JID."),
+ name: zod.string().describe("The community's name."),
+ })
+ .describe('The WhatsApp community a group belongs to.'),
+ ])
+ .optional(),
id: zod.uuid().describe('Entity identifier.'),
kind: zod
.enum(['group', 'direct'])
.describe('Whether a WhatsApp chat is a group or a one-to-one chat.'),
- last_message_at: zod.iso
+ lastMessageAt: zod.iso
.datetime({})
.nullish()
.describe('Latest message timestamp.'),
name: zod
.string()
.describe("Display name: the group's, or a direct chat's other person."),
- send_reason: zod
+ sendReason: zod
.union([
zod.null(),
zod
@@ -49554,10 +49569,12 @@ export const whatsappGroupsResponseItem = zod
.describe('Why the viewer cannot send now.'),
])
.optional(),
- unread_count: zod
+ unreadCount: zod
.number()
- .describe('Unread live messages for this viewer.'),
- user_id: zod.string().describe('Actual entity owner.'),
+ .describe(
+ 'Unread live messages for this viewer, counted up to\n[`UNREAD_COUNT_CAP`].'
+ ),
+ userId: zod.string().describe('Actual entity owner.'),
})
.describe('Adopted group visible through ordinary entity sharing.');
export const whatsappGroupsResponse = zod.array(whatsappGroupsResponseItem);
@@ -49581,8 +49598,6 @@ export const whatsappGroupResponseLimitsMutationWindowSecondsMin = 0;
export const whatsappGroupResponseLimitsTextLimitBytesMin = 0;
-export const whatsappGroupResponseRosterDisappearingSecondsMin = 0;
-
export const whatsappGroupResponse = zod
.object({
backfill: zod
@@ -49598,6 +49613,7 @@ export const whatsappGroupResponse = zod
),
state: zod
.enum([
+ 'waiting_for_message',
'pending',
'running',
'waiting_for_phone',
@@ -49609,21 +49625,35 @@ export const whatsappGroupResponse = zod
.describe('Earlier messages imported after adding a group.'),
])
.optional(),
- can_send: zod
+ canSend: zod
.boolean()
.describe('Caller may currently send from their own account.'),
+ community: zod
+ .union([
+ zod.null(),
+ zod
+ .object({
+ announcements: zod
+ .boolean()
+ .describe("This group is the community's announcement group."),
+ id: zod.string().describe("The community's WhatsApp JID."),
+ name: zod.string().describe("The community's name."),
+ })
+ .describe('The WhatsApp community a group belongs to.'),
+ ])
+ .optional(),
id: zod.uuid().describe('Entity identifier.'),
kind: zod
.enum(['group', 'direct'])
.describe('Whether a WhatsApp chat is a group or a one-to-one chat.'),
- last_message_at: zod.iso
+ lastMessageAt: zod.iso
.datetime({})
.nullish()
.describe('Latest message timestamp.'),
name: zod
.string()
.describe("Display name: the group's, or a direct chat's other person."),
- send_reason: zod
+ sendReason: zod
.union([
zod.null(),
zod
@@ -49638,32 +49668,20 @@ export const whatsappGroupResponse = zod
.describe('Why the viewer cannot send now.'),
])
.optional(),
- unread_count: zod
+ unreadCount: zod
.number()
- .describe('Unread live messages for this viewer.'),
- user_id: zod.string().describe('Actual entity owner.'),
+ .describe(
+ 'Unread live messages for this viewer, counted up to\n[`UNREAD_COUNT_CAP`].'
+ ),
+ userId: zod.string().describe('Actual entity owner.'),
})
.describe('Adopted group visible through ordinary entity sharing.')
.and(
zod.object({
- access_level: zod
+ accessLevel: zod
.enum(['view', 'comment', 'edit', 'owner'])
.describe('Ordered from least to most access top -> bottom'),
- community: zod
- .union([
- zod.null(),
- zod
- .object({
- announcements: zod
- .boolean()
- .describe("This group is the community's announcement group."),
- id: zod.string().describe("The community's WhatsApp JID."),
- name: zod.string().describe("The community's name."),
- })
- .describe('The WhatsApp community a group belongs to.'),
- ])
- .optional(),
- disappearing_seconds: zod
+ disappearingSeconds: zod
.number()
.min(whatsappGroupResponseDisappearingSecondsMin)
.nullish()
@@ -49672,18 +49690,18 @@ export const whatsappGroupResponse = zod
),
limits: zod
.object({
- attachment_limit_bytes: zod
+ attachmentLimitBytes: zod
.number()
.min(whatsappGroupResponseLimitsAttachmentLimitBytesMin)
.describe('Largest attachment in bytes.'),
- attachment_types: zod
+ attachmentTypes: zod
.array(zod.string())
.describe('Supported attachment MIME types.'),
- max_attachments: zod
+ maxAttachments: zod
.number()
.min(whatsappGroupResponseLimitsMaxAttachmentsMin)
.describe('Attachments per send.'),
- mutation_window_seconds: zod
+ mutationWindowSeconds: zod
.number()
.min(whatsappGroupResponseLimitsMutationWindowSecondsMin)
.describe('Edits and deletes are offered this long after sending.'),
@@ -49696,7 +49714,7 @@ export const whatsappGroupResponse = zod
)
)
.describe('Supported message operations.'),
- text_limit_bytes: zod
+ textLimitBytes: zod
.number()
.min(whatsappGroupResponseLimitsTextLimitBytesMin)
.describe('Maximum UTF-8 bytes per text send.'),
@@ -49710,84 +49728,45 @@ export const whatsappGroupResponse = zod
zod
.object({
announce: zod.boolean().describe('Only admins may post.'),
- communityAnnouncements: zod
- .boolean()
- .optional()
- .describe(
- "The community's announcement group (everyone reads, admins post)."
- ),
- communityJid: zod
- .string()
- .nullish()
- .describe(
- 'The community a linked subgroup or announcement group belongs to.'
- ),
- communityParent: zod
- .boolean()
- .optional()
- .describe(
- "The community itself: it has no messages of its own and can't be added."
- ),
- disappearingSeconds: zod
- .number()
- .min(whatsappGroupResponseRosterDisappearingSecondsMin)
- .nullish()
- .describe(
- 'Disappearing-messages timer in seconds while it is on. Macro keeps the\nmessages; its sends carry the timer so phones treat them like their own.'
- ),
- jid: zod.string().describe('Remote group JID.'),
- name: zod.string().describe('Current subject.'),
+ name: zod.string().describe('WhatsApp subject.'),
observedAt: zod.iso
.datetime({})
- .describe('When the session service read this metadata.'),
+ .describe('When this was read from WhatsApp.'),
participants: zod
.array(
zod
.object({
+ admin: zod.boolean().describe('Group admin.'),
alternateJid: zod
.string()
.nullish()
.describe(
- 'Verified alternate identity, never inferred from a name or phone typed by a user.'
+ 'The other address WhatsApp verified for them.'
),
displayName: zod
.string()
.nullish()
- .describe('Untrusted display name.'),
- jid: zod
- .string()
- .describe('Phone-number or LID account JID.'),
+ .describe('Their WhatsApp name, untrusted.'),
+ jid: zod.string().describe('Phone-number or LID JID.'),
})
.describe(
- 'Verified sender aliases, supplied only by protocol metadata.'
- )
- .and(
- zod.object({
- admin: zod
- .boolean()
- .describe(
- 'Group admin; only admins post in announcement groups.'
- ),
- })
- )
- .describe(
- 'Current remote participant; Macro access is a separate grant.'
+ 'Someone in a WhatsApp chat; Macro access is a separate grant.'
)
)
- .describe('Full roster.'),
+ .describe('Everyone in the chat.'),
})
.describe(
- 'One full metadata read of a group, never an incomplete membership delta.'
+ "A chat's WhatsApp metadata as the caller's account last read it."
),
])
.optional(),
- sending_identity: zod
+ sendingIdentity: zod
.string()
.nullish()
.describe(
"Caller's own phone identity, never another account's identity."
),
- share_permission: zod.object({
+ sharePermission: zod.object({
channelSharePermissions: zod
.array(
zod
@@ -49835,7 +49814,7 @@ export const whatsappGroupResponse = zod
.describe('Full group detail and current viewer capabilities.');
/**
- * @summary Stop syncing the group, locally.
+ * @summary Stop syncing the group, locally. Owner only, in their own session.
*/
export const linkedDetachParams = zod.object({
group_id: zod.uuid(),
@@ -49862,7 +49841,7 @@ export const linkedUploadResponse = zod
kind: zod
.enum(['image', 'audio', 'video', 'document'])
.describe('Attachment categories WhatsApp distinguishes.'),
- upload_id: zod
+ uploadId: zod
.uuid()
.describe(
'Use as `upload_id` in a media send; also the future document id.'
@@ -49882,17 +49861,17 @@ export const linkedDeliveryBody = zod.array(linkedDeliveryBodyItem);
export const linkedDeliveryResponseItem = zod
.object({
- created_at: zod.iso.datetime({}).describe('Intent creation time.'),
- error_code: zod.string().nullish().describe('Sanitized failure code.'),
- group_id: zod.uuid().describe('Group entity.'),
+ createdAt: zod.iso.datetime({}).describe('Intent creation time.'),
+ errorCode: zod.string().nullish().describe('Sanitized failure code.'),
+ groupId: zod.uuid().describe('Group entity.'),
id: zod.uuid().describe('Stable intent id.'),
- message_id: zod
+ messageId: zod
.uuid()
.nullish()
.describe('Group message, once WhatsApp accepted it.'),
payload: zod
.object({
- idempotency_key: zod
+ idempotencyKey: zod
.uuid()
.describe(
'Stable client intent key. A changed payload with this key is a conflict.'
@@ -49920,7 +49899,7 @@ export const linkedDeliveryResponseItem = zod
.nullish()
.describe('Optional caption; audio has none.'),
type: zod.enum(['media']),
- upload_id: zod
+ uploadId: zod
.uuid()
.describe(
"The staged upload, which becomes the message's private document."
@@ -49929,7 +49908,7 @@ export const linkedDeliveryResponseItem = zod
.describe('One attachment staged through the attachments route.'),
zod
.object({
- message_id: zod
+ messageId: zod
.uuid()
.describe(
'Existing group message, resolved to its WhatsApp source by the server.'
@@ -49950,7 +49929,7 @@ export const linkedDeliveryResponseItem = zod
.describe('An operation on an existing message in this group.'),
])
.describe('Content of a deliberate send.'),
- reply_to: zod
+ replyTo: zod
.uuid()
.nullish()
.describe('Group message being quoted, within this group.'),
@@ -49959,20 +49938,11 @@ export const linkedDeliveryResponseItem = zod
'Explicit send action from a person. Only deliberate sends reach WhatsApp.'
),
state: zod
- .enum([
- 'pending',
- 'sending',
- 'unknown',
- 'accepted',
- 'sent',
- 'delivered',
- 'read',
- 'failed',
- ])
+ .enum(['pending', 'sending', 'unknown', 'accepted', 'failed'])
.describe(
'Observed send state. `unknown` means the request may have reached WhatsApp;\nit is never sent again automatically.'
),
- user_id: zod.string().describe('Person who submitted it.'),
+ userId: zod.string().describe('Person who submitted it.'),
})
.describe('Durable result of a deliberate send.');
export const linkedDeliveryResponse = zod.array(linkedDeliveryResponseItem);
@@ -49989,7 +49959,10 @@ export const whatsappGroupMessagesQueryParams = zod.object({
.uuid()
.nullish()
.describe('Last message id in the previous page.'),
- limit: zod.number().nullish().describe('Page size, 1 through 100.'),
+ limit: zod
+ .number()
+ .nullish()
+ .describe('Page size, up to [`PAGE_LIMIT`]; [`DEFAULT_PAGE`] when absent.'),
});
export const whatsappGroupMessagesResponseMessagesItemAttachmentsItemDurationSecondsMin = 0;
@@ -50014,11 +49987,11 @@ export const whatsappGroupMessagesResponse = zod
.array(
zod
.object({
- document_id: zod
+ documentId: zod
.uuid()
.nullish()
.describe('The private document, once ready.'),
- duration_seconds: zod
+ durationSeconds: zod
.number()
.min(
whatsappGroupMessagesResponseMessagesItemAttachmentsItemDurationSecondsMin
@@ -50027,7 +50000,7 @@ export const whatsappGroupMessagesResponse = zod
.describe(
'Length of audio or video in whole seconds, when declared.'
),
- file_name: zod.string().describe('Display filename.'),
+ fileName: zod.string().describe('Display filename.'),
height: zod
.number()
.min(
@@ -50075,26 +50048,17 @@ export const whatsappGroupMessagesResponse = zod
.describe('Imported or pending attachments.'),
body: zod.string().describe('Plain WhatsApp text.'),
deleted: zod.boolean().describe('Deleted for everyone.'),
- delivery_state: zod
+ deliveryState: zod
.union([
zod.null(),
zod
- .enum([
- 'pending',
- 'sending',
- 'unknown',
- 'accepted',
- 'sent',
- 'delivered',
- 'read',
- 'failed',
- ])
+ .enum(['pending', 'sending', 'unknown', 'accepted', 'failed'])
.describe(
'Observed send state. `unknown` means the request may have reached WhatsApp;\nit is never sent again automatically.'
),
])
.optional(),
- edited_at: zod.iso
+ editedAt: zod.iso
.datetime({})
.nullish()
.describe('Last edit timestamp.'),
@@ -50141,10 +50105,10 @@ export const whatsappGroupMessagesResponse = zod
.describe('Grouped reactions.')
)
.describe('Reactions grouped by emoji.'),
- received_at: zod.iso
+ receivedAt: zod.iso
.datetime({})
.describe('Timestamp first received by Macro.'),
- reply_to: zod
+ replyTo: zod
.uuid()
.nullish()
.describe('Message quoted by this one.'),
@@ -50413,8 +50377,8 @@ export const whatsappGroupMessagesResponse = zod
name: zod
.string()
.describe('Display name, never authentication evidence.'),
- person_id: zod.uuid().describe('External person identity.'),
- user_id: zod
+ personId: zod.uuid().describe('External person identity.'),
+ userId: zod
.string()
.nullish()
.describe('Verified Macro user association, if present.'),
@@ -50422,10 +50386,10 @@ export const whatsappGroupMessagesResponse = zod
.describe(
'Message sender from protocol-verified identity evidence.'
),
- sent_at: zod.iso
+ sentAt: zod.iso
.datetime({})
.describe('Timestamp assigned by WhatsApp.'),
- view_once: zod
+ viewOnce: zod
.boolean()
.describe(
'Sent as view-once in WhatsApp; Macro shows it like any media.'
@@ -50434,7 +50398,7 @@ export const whatsappGroupMessagesResponse = zod
.describe('One message in an adopted group.')
)
.describe('Messages in descending sent_at, id order.'),
- next_cursor: zod.uuid().nullish().describe('Cursor for older messages.'),
+ nextCursor: zod.uuid().nullish().describe('Cursor for older messages.'),
})
.describe(
'Newest-first timeline page; `before` is the last returned message id.'
@@ -50462,15 +50426,15 @@ export const linkedMessageAttachmentsResponseLinkedAttachmentsItemWidthMin = 0;
export const linkedMessageAttachmentsResponseItem = zod
.object({
- linked_attachments: zod
+ linkedAttachments: zod
.array(
zod
.object({
- document_id: zod
+ documentId: zod
.uuid()
.nullish()
.describe('The private document, once ready.'),
- duration_seconds: zod
+ durationSeconds: zod
.number()
.min(
linkedMessageAttachmentsResponseLinkedAttachmentsItemDurationSecondsMin
@@ -50479,7 +50443,7 @@ export const linkedMessageAttachmentsResponseItem = zod
.describe(
'Length of audio or video in whole seconds, when declared.'
),
- file_name: zod.string().describe('Display filename.'),
+ fileName: zod.string().describe('Display filename.'),
height: zod
.number()
.min(
@@ -50519,13 +50483,396 @@ export const linkedMessageAttachmentsResponseItem = zod
.describe('One attachment of a linked message.')
)
.describe('Its attachments in order; deleted ones are omitted.'),
- message_id: zod.uuid().describe('Group message.'),
+ messageId: zod.uuid().describe('Group message.'),
})
.describe('The attachments of one linked group message.');
export const linkedMessageAttachmentsResponse = zod.array(
linkedMessageAttachmentsResponseItem
);
+/**
+ * @summary One message of the timeline, as the timeline shows it.
+ */
+export const whatsappGroupMessageParams = zod.object({
+ group_id: zod.uuid(),
+ message_id: zod.uuid(),
+});
+
+export const whatsappGroupMessageResponseAttachmentsItemDurationSecondsMin = 0;
+
+export const whatsappGroupMessageResponseAttachmentsItemHeightMin = 0;
+
+export const whatsappGroupMessageResponseAttachmentsItemSizeMin = 0;
+
+export const whatsappGroupMessageResponseAttachmentsItemWidthMin = 0;
+
+export const whatsappGroupMessageResponseRichSelectableCountMin = 0;
+
+export const whatsappGroupMessageResponseRichCallDurationSecondsMin = 0;
+
+export const whatsappGroupMessageResponse = zod
+ .object({
+ attachments: zod
+ .array(
+ zod
+ .object({
+ documentId: zod
+ .uuid()
+ .nullish()
+ .describe('The private document, once ready.'),
+ durationSeconds: zod
+ .number()
+ .min(
+ whatsappGroupMessageResponseAttachmentsItemDurationSecondsMin
+ )
+ .nullish()
+ .describe(
+ 'Length of audio or video in whole seconds, when declared.'
+ ),
+ fileName: zod.string().describe('Display filename.'),
+ height: zod
+ .number()
+ .min(whatsappGroupMessageResponseAttachmentsItemHeightMin)
+ .nullish()
+ .describe('Pixel height, when declared.'),
+ mime: zod.string().describe('Declared MIME type.'),
+ ordinal: zod.number().describe('Position within the message.'),
+ presentation: zod
+ .union([
+ zod.null(),
+ zod
+ .enum(['sticker', 'gif', 'voice_note'])
+ .describe(
+ 'How WhatsApp shows an attachment, when not as a plain file of its kind.'
+ ),
+ ])
+ .optional(),
+ size: zod
+ .number()
+ .min(whatsappGroupMessageResponseAttachmentsItemSizeMin)
+ .describe('Declared size in bytes.'),
+ state: zod
+ .enum(['loading', 'ready', 'unavailable', 'unsupported'])
+ .describe('Where an attachment of a linked message stands.'),
+ width: zod
+ .number()
+ .min(whatsappGroupMessageResponseAttachmentsItemWidthMin)
+ .nullish()
+ .describe(
+ 'Pixel width of an image, sticker or video, when WhatsApp declared it.'
+ ),
+ })
+ .describe('One attachment of a linked message.')
+ )
+ .describe('Imported or pending attachments.'),
+ body: zod.string().describe('Plain WhatsApp text.'),
+ deleted: zod.boolean().describe('Deleted for everyone.'),
+ deliveryState: zod
+ .union([
+ zod.null(),
+ zod
+ .enum(['pending', 'sending', 'unknown', 'accepted', 'failed'])
+ .describe(
+ 'Observed send state. `unknown` means the request may have reached WhatsApp;\nit is never sent again automatically.'
+ ),
+ ])
+ .optional(),
+ editedAt: zod.iso.datetime({}).nullish().describe('Last edit timestamp.'),
+ forwarded: zod.boolean().describe('Forwarded from another chat.'),
+ id: zod.uuid().describe('Stable message id.'),
+ kind: zod.enum(['message', 'system']).describe('What a timeline entry is.'),
+ mentions: zod
+ .array(
+ zod
+ .object({
+ name: zod
+ .string()
+ .describe('Display name, never authentication evidence.'),
+ userId: zod
+ .string()
+ .nullish()
+ .describe('Verified Macro user, if any.'),
+ })
+ .describe(
+ 'A person named in a message: a Macro user when verified, else their\nWhatsApp name, else their phone number.'
+ )
+ .and(
+ zod.object({
+ token: zod
+ .string()
+ .describe(
+ "What follows the `@` in the body (the digits of the person's WhatsApp\nid); replace `@<token>` with the name."
+ ),
+ })
+ )
+ .describe('An @-mention in a message body.')
+ )
+ .describe('People the body @-mentions.'),
+ reactions: zod
+ .array(
+ zod
+ .object({
+ count: zod.number().describe('Number of reacting people.'),
+ emoji: zod.string().describe('Emoji.'),
+ mine: zod.boolean().describe('Caller has this reaction.'),
+ })
+ .describe('Grouped reactions.')
+ )
+ .describe('Reactions grouped by emoji.'),
+ receivedAt: zod.iso
+ .datetime({})
+ .describe('Timestamp first received by Macro.'),
+ replyTo: zod.uuid().nullish().describe('Message quoted by this one.'),
+ rich: zod
+ .union([
+ zod.null(),
+ zod
+ .union([
+ zod
+ .object({
+ options: zod
+ .array(
+ zod
+ .object({
+ mine: zod.boolean().describe('The caller chose it.'),
+ name: zod.string().describe('Option text.'),
+ voters: zod
+ .array(
+ zod
+ .object({
+ name: zod
+ .string()
+ .describe(
+ 'Display name, never authentication evidence.'
+ ),
+ userId: zod
+ .string()
+ .nullish()
+ .describe('Verified Macro user, if any.'),
+ })
+ .describe(
+ 'A person named in a message: a Macro user when verified, else their\nWhatsApp name, else their phone number.'
+ )
+ )
+ .describe('Who chose it.'),
+ votes: zod.number().describe('People who chose it.'),
+ })
+ .describe('One option of a poll with its votes.')
+ )
+ .describe('Options in order, with tallies.'),
+ question: zod.string().describe('The question.'),
+ selectableCount: zod
+ .number()
+ .min(whatsappGroupMessageResponseRichSelectableCountMin)
+ .describe(
+ 'How many options one person may choose; 0 means any number.'
+ ),
+ voters: zod.number().describe('People who voted for anything.'),
+ })
+ .describe('A poll, read-only in Macro.')
+ .and(
+ zod.object({
+ type: zod.enum(['poll']),
+ })
+ )
+ .describe('A poll with current votes.'),
+ zod
+ .object({
+ address: zod.string().nullish().describe('Street address.'),
+ comment: zod.string().nullish().describe('Caption or comment.'),
+ latitude: zod.number().describe('Degrees.'),
+ live: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Shared as a live location (this is where it started).'
+ ),
+ longitude: zod.number().describe('Degrees.'),
+ name: zod.string().nullish().describe('Place name.'),
+ url: zod
+ .string()
+ .nullish()
+ .describe('Link the sender attached.'),
+ })
+ .describe('A shared place.')
+ .and(
+ zod.object({
+ type: zod.enum(['location']),
+ })
+ )
+ .describe(
+ 'A place (or the start of a live location); link to a maps URL.'
+ ),
+ zod
+ .object({
+ contacts: zod
+ .array(
+ zod
+ .object({
+ name: zod.string().describe('Display name.'),
+ phones: zod
+ .array(zod.string())
+ .describe('Phone numbers as written on the card.'),
+ })
+ .describe('One contact card, from its vCard.')
+ )
+ .describe('The cards, in order.'),
+ })
+ .describe('Contact cards.')
+ .and(
+ zod.object({
+ type: zod.enum(['contacts']),
+ })
+ )
+ .describe('Contact cards.'),
+ zod
+ .object({
+ canceled: zod
+ .boolean()
+ .optional()
+ .describe('Canceled by its organizer.'),
+ description: zod.string().nullish().describe('Description.'),
+ endAt: zod.iso.datetime({}).nullish().describe('End.'),
+ joinLink: zod
+ .string()
+ .nullish()
+ .describe('Call link for an online event.'),
+ location: zod
+ .string()
+ .nullish()
+ .describe('Place name or address.'),
+ name: zod.string().describe('Title.'),
+ startAt: zod.iso.datetime({}).nullish().describe('Start.'),
+ })
+ .describe('A WhatsApp event.')
+ .and(
+ zod.object({
+ type: zod.enum(['event']),
+ })
+ )
+ .describe('A WhatsApp event.'),
+ zod
+ .object({
+ action: zod
+ .enum([
+ 'group_created',
+ 'participants_added',
+ 'participants_removed',
+ 'participants_left',
+ 'participants_joined',
+ 'participants_promoted',
+ 'participants_demoted',
+ 'subject_changed',
+ 'icon_changed',
+ 'description_changed',
+ 'disappearing_changed',
+ 'message_pinned',
+ 'message_unpinned',
+ 'call',
+ ])
+ .describe('Kinds of system lines.'),
+ actor: zod
+ .union([
+ zod.null(),
+ zod
+ .object({
+ name: zod
+ .string()
+ .describe(
+ 'Display name, never authentication evidence.'
+ ),
+ userId: zod
+ .string()
+ .nullish()
+ .describe('Verified Macro user, if any.'),
+ })
+ .describe(
+ 'A person named in a message: a Macro user when verified, else their\nWhatsApp name, else their phone number.'
+ ),
+ ])
+ .optional(),
+ call: zod
+ .union([
+ zod.null(),
+ zod
+ .object({
+ durationSeconds: zod
+ .number()
+ .min(
+ whatsappGroupMessageResponseRichCallDurationSecondsMin
+ )
+ .nullish()
+ .describe('Length, when it connected.'),
+ outcome: zod
+ .enum(['answered', 'missed', 'rejected', 'other'])
+ .describe('How a call went.'),
+ video: zod
+ .boolean()
+ .describe('Video rather than voice.'),
+ })
+ .describe('A call in the group.'),
+ ])
+ .optional(),
+ participants: zod
+ .array(
+ zod
+ .object({
+ name: zod
+ .string()
+ .describe(
+ 'Display name, never authentication evidence.'
+ ),
+ userId: zod
+ .string()
+ .nullish()
+ .describe('Verified Macro user, if any.'),
+ })
+ .describe(
+ 'A person named in a message: a Macro user when verified, else their\nWhatsApp name, else their phone number.'
+ )
+ )
+ .describe(
+ 'Who it happened to (added, removed, promoted, …).'
+ ),
+ value: zod
+ .string()
+ .nullish()
+ .describe(
+ 'New subject or description; disappearing-messages timer in seconds\n(`\"0\"` is off).'
+ ),
+ })
+ .describe('Something that happened in the group.')
+ .and(
+ zod.object({
+ type: zod.enum(['system']),
+ })
+ )
+ .describe('A system line.'),
+ ])
+ .describe('Structured content of a message besides its body.'),
+ ])
+ .optional(),
+ sender: zod
+ .object({
+ name: zod
+ .string()
+ .describe('Display name, never authentication evidence.'),
+ personId: zod.uuid().describe('External person identity.'),
+ userId: zod
+ .string()
+ .nullish()
+ .describe('Verified Macro user association, if present.'),
+ })
+ .describe('Message sender from protocol-verified identity evidence.'),
+ sentAt: zod.iso.datetime({}).describe('Timestamp assigned by WhatsApp.'),
+ viewOnce: zod
+ .boolean()
+ .describe(
+ 'Sent as view-once in WhatsApp; Macro shows it like any media.'
+ ),
+ })
+ .describe('One message in an adopted group.');
+
/**
* @summary Generic Share dialog policy.
*/
@@ -50635,7 +50982,7 @@ export const whatsappGroupReadParams = zod.object({
export const whatsappGroupReadBody = zod
.object({
- message_id: zod.uuid().describe('Message in the addressed group.'),
+ messageId: zod.uuid().describe('Message in the addressed group.'),
})
.describe('Mark messages through this message read.');
@@ -50648,17 +50995,17 @@ export const whatsappGroupSendsParams = zod.object({
export const whatsappGroupSendsResponseItem = zod
.object({
- created_at: zod.iso.datetime({}).describe('Intent creation time.'),
- error_code: zod.string().nullish().describe('Sanitized failure code.'),
- group_id: zod.uuid().describe('Group entity.'),
+ createdAt: zod.iso.datetime({}).describe('Intent creation time.'),
+ errorCode: zod.string().nullish().describe('Sanitized failure code.'),
+ groupId: zod.uuid().describe('Group entity.'),
id: zod.uuid().describe('Stable intent id.'),
- message_id: zod
+ messageId: zod
.uuid()
.nullish()
.describe('Group message, once WhatsApp accepted it.'),
payload: zod
.object({
- idempotency_key: zod
+ idempotencyKey: zod
.uuid()
.describe(
'Stable client intent key. A changed payload with this key is a conflict.'
@@ -50686,7 +51033,7 @@ export const whatsappGroupSendsResponseItem = zod
.nullish()
.describe('Optional caption; audio has none.'),
type: zod.enum(['media']),
- upload_id: zod
+ uploadId: zod
.uuid()
.describe(
"The staged upload, which becomes the message's private document."
@@ -50695,7 +51042,7 @@ export const whatsappGroupSendsResponseItem = zod
.describe('One attachment staged through the attachments route.'),
zod
.object({
- message_id: zod
+ messageId: zod
.uuid()
.describe(
'Existing group message, resolved to its WhatsApp source by the server.'
@@ -50716,7 +51063,7 @@ export const whatsappGroupSendsResponseItem = zod
.describe('An operation on an existing message in this group.'),
])
.describe('Content of a deliberate send.'),
- reply_to: zod
+ replyTo: zod
.uuid()
.nullish()
.describe('Group message being quoted, within this group.'),
@@ -50725,20 +51072,11 @@ export const whatsappGroupSendsResponseItem = zod
'Explicit send action from a person. Only deliberate sends reach WhatsApp.'
),
state: zod
- .enum([
- 'pending',
- 'sending',
- 'unknown',
- 'accepted',
- 'sent',
- 'delivered',
- 'read',
- 'failed',
- ])
+ .enum(['pending', 'sending', 'unknown', 'accepted', 'failed'])
.describe(
'Observed send state. `unknown` means the request may have reached WhatsApp;\nit is never sent again automatically.'
),
- user_id: zod.string().describe('Person who submitted it.'),
+ userId: zod.string().describe('Person who submitted it.'),
})
.describe('Durable result of a deliberate send.');
export const whatsappGroupSendsResponse = zod.array(
@@ -50754,7 +51092,7 @@ export const linkedReplyParams = zod.object({
export const linkedReplyBody = zod
.object({
- idempotency_key: zod
+ idempotencyKey: zod
.uuid()
.describe(
'Stable client intent key. A changed payload with this key is a conflict.'
@@ -50782,7 +51120,7 @@ export const linkedReplyBody = zod
.nullish()
.describe('Optional caption; audio has none.'),
type: zod.enum(['media']),
- upload_id: zod
+ uploadId: zod
.uuid()
.describe(
"The staged upload, which becomes the message's private document."
@@ -50791,7 +51129,7 @@ export const linkedReplyBody = zod
.describe('One attachment staged through the attachments route.'),
zod
.object({
- message_id: zod
+ messageId: zod
.uuid()
.describe(
'Existing group message, resolved to its WhatsApp source by the server.'
@@ -50812,7 +51150,7 @@ export const linkedReplyBody = zod
.describe('An operation on an existing message in this group.'),
])
.describe('Content of a deliberate send.'),
- reply_to: zod
+ replyTo: zod
.uuid()
.nullish()
.describe('Group message being quoted, within this group.'),
@@ -50823,17 +51161,17 @@ export const linkedReplyBody = zod
export const linkedReplyResponse = zod
.object({
- created_at: zod.iso.datetime({}).describe('Intent creation time.'),
- error_code: zod.string().nullish().describe('Sanitized failure code.'),
- group_id: zod.uuid().describe('Group entity.'),
+ createdAt: zod.iso.datetime({}).describe('Intent creation time.'),
+ errorCode: zod.string().nullish().describe('Sanitized failure code.'),
+ groupId: zod.uuid().describe('Group entity.'),
id: zod.uuid().describe('Stable intent id.'),
- message_id: zod
+ messageId: zod
.uuid()
.nullish()
.describe('Group message, once WhatsApp accepted it.'),
payload: zod
.object({
- idempotency_key: zod
+ idempotencyKey: zod
.uuid()
.describe(
'Stable client intent key. A changed payload with this key is a conflict.'
@@ -50861,7 +51199,7 @@ export const linkedReplyResponse = zod
.nullish()
.describe('Optional caption; audio has none.'),
type: zod.enum(['media']),
- upload_id: zod
+ uploadId: zod
.uuid()
.describe(
"The staged upload, which becomes the message's private document."
@@ -50870,7 +51208,7 @@ export const linkedReplyResponse = zod
.describe('One attachment staged through the attachments route.'),
zod
.object({
- message_id: zod
+ messageId: zod
.uuid()
.describe(
'Existing group message, resolved to its WhatsApp source by the server.'
@@ -50891,7 +51229,7 @@ export const linkedReplyResponse = zod
.describe('An operation on an existing message in this group.'),
])
.describe('Content of a deliberate send.'),
- reply_to: zod
+ replyTo: zod
.uuid()
.nullish()
.describe('Group message being quoted, within this group.'),
@@ -50900,20 +51238,11 @@ export const linkedReplyResponse = zod
'Explicit send action from a person. Only deliberate sends reach WhatsApp.'
),
state: zod
- .enum([
- 'pending',
- 'sending',
- 'unknown',
- 'accepted',
- 'sent',
- 'delivered',
- 'read',
- 'failed',
- ])
+ .enum(['pending', 'sending', 'unknown', 'accepted', 'failed'])
.describe(
'Observed send state. `unknown` means the request may have reached WhatsApp;\nit is never sent again automatically.'
),
- user_id: zod.string().describe('Person who submitted it.'),
+ userId: zod.string().describe('Person who submitted it.'),
})
.describe('Durable result of a deliberate send.');
diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.json
index 5228f51a53..fe0eda5791 100644
--- a/apps/web/src/lib/service-clients/service-storage/openapi.json
+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json
@@ -16309,7 +16309,7 @@
},
"delete": {
"tags": ["whatsapp_linked::inbound::router"],
- "summary": "Stop syncing the group, locally.",
+ "summary": "Stop syncing the group, locally. Owner only, in their own session.",
"operationId": "linked_detach",
"parameters": [
{
@@ -16444,7 +16444,7 @@
{
"name": "limit",
"in": "query",
- "description": "Page size, 1 through 100.",
+ "description": "Page size, up to [`PAGE_LIMIT`]; [`DEFAULT_PAGE`] when absent.",
"required": false,
"schema": {
"type": ["integer", "null"],
@@ -16513,6 +16513,45 @@
}
}
},
+ "/meta/linked/whatsapp-groups/{group_id}/messages/{message_id}": {
+ "get": {
+ "tags": ["whatsapp_linked::inbound::router"],
+ "summary": "One message of the timeline, as the timeline shows it.",
+ "operationId": "whatsapp_group_message",
+ "parameters": [
+ {
+ "name": "group_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ },
+ {
+ "name": "message_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/WhatsAppGroupMessage"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/meta/linked/whatsapp-groups/{group_id}/permissions": {
"get": {
"tags": ["whatsapp_linked::inbound::router"],
@@ -19799,9 +19838,9 @@
"AdoptedGroup": {
"type": "object",
"description": "Adoption response.",
- "required": ["group_id"],
+ "required": ["groupId"],
"properties": {
- "group_id": {
+ "groupId": {
"type": "string",
"format": "uuid",
"description": "Shareable entity identifier."
@@ -33288,9 +33327,9 @@
"LinkedAccount": {
"type": "object",
"description": "One person's account, never owned by a workspace.",
- "required": ["id", "user_id", "state", "authorization_generation"],
+ "required": ["id", "userId", "state", "authorizationGeneration"],
"properties": {
- "authorization_generation": {
+ "authorizationGeneration": {
"type": "integer",
"format": "int64",
"description": "Explicit consent generation; reconnecting a socket never changes it."
@@ -33300,7 +33339,7 @@
"format": "uuid",
"description": "Stable account identity."
},
- "identity_jid": {
+ "identityJid": {
"type": ["string", "null"],
"description": "WhatsApp-verified identity, absent until the first pairing succeeds."
},
@@ -33308,7 +33347,7 @@
"$ref": "#/components/schemas/LinkedAccountState",
"description": "Lifecycle."
},
- "user_id": {
+ "userId": {
"type": "string",
"description": "Authenticated owner."
}
@@ -33339,9 +33378,9 @@
"LinkedAdoptGroup": {
"type": "object",
"description": "Explicit adoption request; the account is selected server-side. The\ngroup's name always follows WhatsApp.",
- "required": ["group_jid"],
+ "required": ["groupJid"],
"properties": {
- "group_jid": {
+ "groupJid": {
"type": "string",
"description": "A group the requester's account has joined, or a direct chat from\ntheir chat list (the other person's JID, as the list names it)."
}
@@ -33350,20 +33389,20 @@
"LinkedAttachment": {
"type": "object",
"description": "One attachment of a linked message.",
- "required": ["ordinal", "state", "file_name", "mime", "size"],
+ "required": ["ordinal", "state", "fileName", "mime", "size"],
"properties": {
- "document_id": {
+ "documentId": {
"type": ["string", "null"],
"format": "uuid",
"description": "The private document, once ready."
},
- "duration_seconds": {
+ "durationSeconds": {
"type": ["integer", "null"],
"format": "int32",
"description": "Length of audio or video in whole seconds, when declared.",
"minimum": 0
},
- "file_name": {
+ "fileName": {
"type": "string",
"description": "Display filename."
},
@@ -33436,7 +33475,14 @@
"LinkedBackfillState": {
"type": "string",
"description": "Where importing a group's earlier messages stands.",
- "enum": ["pending", "running", "waiting_for_phone", "done", "partial"]
+ "enum": [
+ "waiting_for_message",
+ "pending",
+ "running",
+ "waiting_for_phone",
+ "done",
+ "partial"
+ ]
},
"LinkedCannotAdd": {
"type": "string",
@@ -33447,34 +33493,34 @@
"type": "object",
"description": "Operations implemented for linked groups, independent of current permission.",
"required": [
- "text_limit_bytes",
+ "textLimitBytes",
"mutations",
- "mutation_window_seconds",
- "max_attachments",
- "attachment_limit_bytes",
- "attachment_types"
+ "mutationWindowSeconds",
+ "maxAttachments",
+ "attachmentLimitBytes",
+ "attachmentTypes"
],
"properties": {
- "attachment_limit_bytes": {
+ "attachmentLimitBytes": {
"type": "integer",
"format": "int32",
"description": "Largest attachment in bytes.",
"minimum": 0
},
- "attachment_types": {
+ "attachmentTypes": {
"type": "array",
"items": {
"type": "string"
},
"description": "Supported attachment MIME types."
},
- "max_attachments": {
+ "maxAttachments": {
"type": "integer",
"format": "int32",
"description": "Attachments per send.",
"minimum": 0
},
- "mutation_window_seconds": {
+ "mutationWindowSeconds": {
"type": "integer",
"format": "int32",
"description": "Edits and deletes are offered this long after sending.",
@@ -33487,7 +33533,7 @@
},
"description": "Supported message operations."
},
- "text_limit_bytes": {
+ "textLimitBytes": {
"type": "integer",
"format": "int32",
"description": "Maximum UTF-8 bytes per text send.",
@@ -33626,23 +33672,14 @@
"LinkedDeliveryState": {
"type": "string",
"description": "Observed send state. `unknown` means the request may have reached WhatsApp;\nit is never sent again automatically.",
- "enum": [
- "pending",
- "sending",
- "unknown",
- "accepted",
- "sent",
- "delivered",
- "read",
- "failed"
- ]
+ "enum": ["pending", "sending", "unknown", "accepted", "failed"]
},
"LinkedDisconnect": {
"type": "object",
"description": "Result of disconnecting an account.",
- "required": ["remote_unlink_requested"],
+ "required": ["remoteUnlinkRequested"],
"properties": {
- "remote_unlink_requested": {
+ "remoteUnlinkRequested": {
"type": "boolean",
"description": "The session service was asked to log the device out of WhatsApp. It\nunlinks asynchronously; WhatsApp's Linked devices list is authoritative."
}
@@ -33651,9 +33688,9 @@
"LinkedDisconnectRequest": {
"type": "object",
"description": "The consent generation the owner deliberately disconnects.",
- "required": ["authorization_generation"],
+ "required": ["authorizationGeneration"],
"properties": {
- "authorization_generation": {
+ "authorizationGeneration": {
"type": "integer",
"format": "int64",
"description": "Fences retries against a later reconnect or replacement."
@@ -33679,55 +33716,6 @@
}
}
},
- "LinkedGroupInfo": {
- "type": "object",
- "description": "One full metadata read of a group, never an incomplete membership delta.",
- "required": ["jid", "name", "participants", "announce", "observedAt"],
- "properties": {
- "announce": {
- "type": "boolean",
- "description": "Only admins may post."
- },
- "communityAnnouncements": {
- "type": "boolean",
- "description": "The community's announcement group (everyone reads, admins post)."
- },
- "communityJid": {
- "type": ["string", "null"],
- "description": "The community a linked subgroup or announcement group belongs to."
- },
- "communityParent": {
- "type": "boolean",
- "description": "The community itself: it has no messages of its own and can't be added."
- },
- "disappearingSeconds": {
- "type": ["integer", "null"],
- "format": "int32",
- "description": "Disappearing-messages timer in seconds while it is on. Macro keeps the\nmessages; its sends carry the timer so phones treat them like their own.",
- "minimum": 0
- },
- "jid": {
- "type": "string",
- "description": "Remote group JID."
- },
- "name": {
- "type": "string",
- "description": "Current subject."
- },
- "observedAt": {
- "type": "string",
- "format": "date-time",
- "description": "When the session service read this metadata."
- },
- "participants": {
- "type": "array",
- "items": {
- "$ref": "#/components/schemas/LinkedParticipant"
- },
- "description": "Full roster."
- }
- }
- },
"LinkedGroupReference": {
"type": "object",
"description": "A group entity bound to a remote group.",
@@ -33744,25 +33732,6 @@
}
}
},
- "LinkedIdentity": {
- "type": "object",
- "description": "Verified sender aliases, supplied only by protocol metadata.",
- "required": ["jid"],
- "properties": {
- "alternateJid": {
- "type": ["string", "null"],
- "description": "Verified alternate identity, never inferred from a name or phone typed by a user."
- },
- "displayName": {
- "type": ["string", "null"],
- "description": "Untrusted display name."
- },
- "jid": {
- "type": "string",
- "description": "Phone-number or LID account JID."
- }
- }
- },
"LinkedMediaKind": {
"type": "string",
"description": "Attachment categories WhatsApp distinguishes.",
@@ -33776,16 +33745,16 @@
"LinkedMessageAttachments": {
"type": "object",
"description": "The attachments of one linked group message.",
- "required": ["message_id", "linked_attachments"],
+ "required": ["messageId", "linkedAttachments"],
"properties": {
- "linked_attachments": {
+ "linkedAttachments": {
"type": "array",
"items": {
"$ref": "#/components/schemas/LinkedAttachment"
},
"description": "Its attachments in order; deleted ones are omitted."
},
- "message_id": {
+ "messageId": {
"type": "string",
"format": "uuid",
"description": "Group message."
@@ -33832,14 +33801,14 @@
"LinkedPairing": {
"type": "object",
"description": "Owner-bound pairing transaction, without its QR or pairing code.",
- "required": ["id", "account_id", "state", "expires_at"],
+ "required": ["id", "accountId", "state", "expiresAt"],
"properties": {
- "account_id": {
+ "accountId": {
"type": "string",
"format": "uuid",
"description": "Account being connected."
},
- "expires_at": {
+ "expiresAt": {
"type": "string",
"format": "date-time",
"description": "Database-assigned deadline."
@@ -33868,25 +33837,6 @@
"failed"
]
},
- "LinkedParticipant": {
- "allOf": [
- {
- "$ref": "#/components/schemas/LinkedIdentity",
- "description": "Identity evidence."
- },
- {
- "type": "object",
- "required": ["admin"],
- "properties": {
- "admin": {
- "type": "boolean",
- "description": "Group admin; only admins post in announcement groups."
- }
- }
- }
- ],
- "description": "Current remote participant; Macro access is a separate grant."
- },
"LinkedReplyBlock": {
"type": "string",
"description": "Why the viewer cannot send now.",
@@ -33926,7 +33876,7 @@
{
"type": "object",
"description": "One attachment staged through the attachments route.",
- "required": ["upload_id", "type"],
+ "required": ["uploadId", "type"],
"properties": {
"caption": {
"type": ["string", "null"],
@@ -33936,7 +33886,7 @@
"type": "string",
"enum": ["media"]
},
- "upload_id": {
+ "uploadId": {
"type": "string",
"format": "uuid",
"description": "The staged upload, which becomes the message's private document."
@@ -33946,9 +33896,9 @@
{
"type": "object",
"description": "An operation on an existing message in this group.",
- "required": ["message_id", "operation", "type"],
+ "required": ["messageId", "operation", "type"],
"properties": {
- "message_id": {
+ "messageId": {
"type": "string",
"format": "uuid",
"description": "Existing group message, resolved to its WhatsApp source by the server."
@@ -33975,23 +33925,23 @@
"description": "Durable result of a deliberate send.",
"required": [
"id",
- "user_id",
- "group_id",
+ "userId",
+ "groupId",
"payload",
"state",
- "created_at"
+ "createdAt"
],
"properties": {
- "created_at": {
+ "createdAt": {
"type": "string",
"format": "date-time",
"description": "Intent creation time."
},
- "error_code": {
+ "errorCode": {
"type": ["string", "null"],
"description": "Sanitized failure code."
},
- "group_id": {
+ "groupId": {
"type": "string",
"format": "uuid",
"description": "Group entity."
@@ -34001,7 +33951,7 @@
"format": "uuid",
"description": "Stable intent id."
},
- "message_id": {
+ "messageId": {
"type": ["string", "null"],
"format": "uuid",
"description": "Group message, once WhatsApp accepted it."
@@ -34014,7 +33964,7 @@
"$ref": "#/components/schemas/LinkedDeliveryState",
"description": "Current state."
},
- "user_id": {
+ "userId": {
"type": "string",
"description": "Person who submitted it."
}
@@ -34023,9 +33973,9 @@
"LinkedSendReply": {
"type": "object",
"description": "Explicit send action from a person. Only deliberate sends reach WhatsApp.",
- "required": ["idempotency_key", "message"],
+ "required": ["idempotencyKey", "message"],
"properties": {
- "idempotency_key": {
+ "idempotencyKey": {
"type": "string",
"format": "uuid",
"description": "Stable client intent key. A changed payload with this key is a conflict."
@@ -34034,7 +33984,7 @@
"$ref": "#/components/schemas/LinkedReplyContent",
"description": "Content."
},
- "reply_to": {
+ "replyTo": {
"type": ["string", "null"],
"format": "uuid",
"description": "Group message being quoted, within this group."
@@ -34076,7 +34026,7 @@
"LinkedUploadedAttachment": {
"type": "object",
"description": "A staged attachment, sent only by a later deliberate send.",
- "required": ["upload_id", "filename", "kind"],
+ "required": ["uploadId", "filename", "kind"],
"properties": {
"filename": {
"type": "string",
@@ -34086,7 +34036,7 @@
"$ref": "#/components/schemas/LinkedMediaKind",
"description": "Category."
},
- "upload_id": {
+ "uploadId": {
"type": "string",
"format": "uuid",
"description": "Use as `upload_id` in a media send; also the future document id."
@@ -34266,9 +34216,9 @@
"MarkRead": {
"type": "object",
"description": "Mark messages through this message read.",
- "required": ["message_id"],
+ "required": ["messageId"],
"properties": {
- "message_id": {
+ "messageId": {
"type": "string",
"format": "uuid",
"description": "Message in the addressed group."
@@ -44684,24 +44634,13 @@
},
{
"type": "object",
- "required": ["share_permission", "access_level", "limits"],
+ "required": ["sharePermission", "accessLevel", "limits"],
"properties": {
- "access_level": {
+ "accessLevel": {
"$ref": "#/components/schemas/AccessLevel",
"description": "Caller's effective permission."
},
- "community": {
- "oneOf": [
- {
- "type": "null"
- },
- {
- "$ref": "#/components/schemas/LinkedCommunityReference",
- "description": "The WhatsApp community this group belongs to, if any."
- }
- ]
- },
- "disappearing_seconds": {
+ "disappearingSeconds": {
"type": ["integer", "null"],
"format": "int32",
"description": "WhatsApp's disappearing-messages timer in seconds while it is on;\nMacro keeps the messages anyway. `null` when off or unknown.",
@@ -44717,16 +44656,16 @@
"type": "null"
},
{
- "$ref": "#/components/schemas/LinkedGroupInfo",
+ "$ref": "#/components/schemas/WhatsAppRoster",
"description": "Latest remote metadata, absent when no observer is connected."
}
]
},
- "sending_identity": {
+ "sendingIdentity": {
"type": ["string", "null"],
"description": "Caller's own phone identity, never another account's identity."
},
- "share_permission": {
+ "sharePermission": {
"$ref": "#/components/schemas/SharePermissionV2",
"description": "Owner-controlled standard sharing configuration."
}
@@ -44742,14 +44681,14 @@
"id",
"sender",
"body",
- "sent_at",
- "received_at",
+ "sentAt",
+ "receivedAt",
"deleted",
"reactions",
"attachments",
"kind",
"forwarded",
- "view_once",
+ "viewOnce",
"mentions"
],
"properties": {
@@ -44768,7 +44707,7 @@
"type": "boolean",
"description": "Deleted for everyone."
},
- "delivery_state": {
+ "deliveryState": {
"oneOf": [
{
"type": "null"
@@ -44779,7 +44718,7 @@
}
]
},
- "edited_at": {
+ "editedAt": {
"type": ["string", "null"],
"format": "date-time",
"description": "Last edit timestamp."
@@ -44811,12 +44750,12 @@
},
"description": "Reactions grouped by emoji."
},
- "received_at": {
+ "receivedAt": {
"type": "string",
"format": "date-time",
"description": "Timestamp first received by Macro."
},
- "reply_to": {
+ "replyTo": {
"type": ["string", "null"],
"format": "uuid",
"description": "Message quoted by this one."
@@ -44836,12 +44775,12 @@
"$ref": "#/components/schemas/WhatsAppGroupSender",
"description": "Sender."
},
- "sent_at": {
+ "sentAt": {
"type": "string",
"format": "date-time",
"description": "Timestamp assigned by WhatsApp."
},
- "view_once": {
+ "viewOnce": {
"type": "boolean",
"description": "Sent as view-once in WhatsApp; Macro shows it like any media."
}
@@ -44859,7 +44798,7 @@
},
"description": "Messages in descending sent_at, id order."
},
- "next_cursor": {
+ "nextCursor": {
"type": ["string", "null"],
"format": "uuid",
"description": "Cursor for older messages."
@@ -44889,18 +44828,18 @@
"WhatsAppGroupSender": {
"type": "object",
"description": "Message sender from protocol-verified identity evidence.",
- "required": ["person_id", "name"],
+ "required": ["personId", "name"],
"properties": {
"name": {
"type": "string",
"description": "Display name, never authentication evidence."
},
- "person_id": {
+ "personId": {
"type": "string",
"format": "uuid",
"description": "External person identity."
},
- "user_id": {
+ "userId": {
"type": ["string", "null"],
"description": "Verified Macro user association, if present."
}
@@ -44909,14 +44848,7 @@
"WhatsAppGroupSummary": {
"type": "object",
"description": "Adopted group visible through ordinary entity sharing.",
- "required": [
- "id",
- "name",
- "kind",
- "user_id",
- "unread_count",
- "can_send"
- ],
+ "required": ["id", "name", "kind", "userId", "unreadCount", "canSend"],
"properties": {
"backfill": {
"oneOf": [
@@ -44925,14 +44857,25 @@
},
{
"$ref": "#/components/schemas/LinkedBackfill",
- "description": "Importing earlier messages after the group was added; `null` for\ngroups added before this existed."
+ "description": "Importing earlier messages after the chat was added; `null` when\nthere is nothing to import."
}
]
},
- "can_send": {
+ "canSend": {
"type": "boolean",
"description": "Caller may currently send from their own account."
},
+ "community": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/LinkedCommunityReference",
+ "description": "The WhatsApp community this group belongs to, if any."
+ }
+ ]
+ },
"id": {
"type": "string",
"format": "uuid",
@@ -44942,7 +44885,7 @@
"$ref": "#/components/schemas/LinkedChatKind",
"description": "A group, or a direct chat with one person (only its owner sends)."
},
- "last_message_at": {
+ "lastMessageAt": {
"type": ["string", "null"],
"format": "date-time",
"description": "Latest message timestamp."
@@ -44951,7 +44894,7 @@
"type": "string",
"description": "Display name: the group's, or a direct chat's other person."
},
- "send_reason": {
+ "sendReason": {
"oneOf": [
{
"type": "null"
@@ -44962,12 +44905,12 @@
}
]
},
- "unread_count": {
+ "unreadCount": {
"type": "integer",
"format": "int64",
- "description": "Unread live messages for this viewer."
+ "description": "Unread live messages for this viewer, counted up to\n[`UNREAD_COUNT_CAP`]."
},
- "user_id": {
+ "userId": {
"type": "string",
"description": "Actual entity owner."
}
@@ -45034,6 +44977,29 @@
"description": "What a timeline entry is.",
"enum": ["message", "system"]
},
+ "WhatsAppParticipant": {
+ "type": "object",
+ "description": "Someone in a WhatsApp chat; Macro access is a separate grant.",
+ "required": ["jid", "admin"],
+ "properties": {
+ "admin": {
+ "type": "boolean",
+ "description": "Group admin."
+ },
+ "alternateJid": {
+ "type": ["string", "null"],
+ "description": "The other address WhatsApp verified for them."
+ },
+ "displayName": {
+ "type": ["string", "null"],
+ "description": "Their WhatsApp name, untrusted."
+ },
+ "jid": {
+ "type": "string",
+ "description": "Phone-number or LID JID."
+ }
+ }
+ },
"WhatsAppPersonRef": {
"type": "object",
"description": "A person named in a message: a Macro user when verified, else their\nWhatsApp name, else their phone number.",
@@ -45205,6 +45171,33 @@
],
"description": "Structured content of a message besides its body."
},
+ "WhatsAppRoster": {
+ "type": "object",
+ "description": "A chat's WhatsApp metadata as the caller's account last read it.",
+ "required": ["name", "participants", "announce", "observedAt"],
+ "properties": {
+ "announce": {
+ "type": "boolean",
+ "description": "Only admins may post."
+ },
+ "name": {
+ "type": "string",
+ "description": "WhatsApp subject."
+ },
+ "observedAt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "When this was read from WhatsApp."
+ },
+ "participants": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/WhatsAppParticipant"
+ },
+ "description": "Everyone in the chat."
+ }
+ }
+ },
"WhatsAppSystemAction": {
"type": "string",
"description": "Kinds of system lines.",
diff --git a/apps/web/src/lib/service-clients/service-storage/whatsapp-errors.ts b/apps/web/src/lib/service-clients/service-storage/whatsapp-errors.ts
index 44896dca5d..2ed773c712 100644
--- a/apps/web/src/lib/service-clients/service-storage/whatsapp-errors.ts
+++ b/apps/web/src/lib/service-clients/service-storage/whatsapp-errors.ts
@@ -5,16 +5,21 @@ import { z } from 'zod';
/** `LinkedError::code()` in `crates/whatsapp_linked`; DSS answers `{ code, message }`. */
export const whatsappErrorCodes = [
'invalid_input',
+ 'cannot_add_not_in_group',
+ 'cannot_add_community',
+ 'cannot_add_own_chat',
+ 'cannot_add_not_in_chat_list',
'configuration_required',
'not_found',
'forbidden',
'conflict',
'disconnected',
- 'identity_conflict',
'send_expired',
'lease_fenced',
'rate_limited',
'temporarily_unavailable',
+ 'backlogged',
+ 'internal_error',
] as const;
export type WhatsAppErrorCode = (typeof whatsappErrorCodes)[number];
diff --git a/apps/web/src/lib/service-clients/service-storage/whatsapp-groups.ts b/apps/web/src/lib/service-clients/service-storage/whatsapp-groups.ts
index 3bc43ef0fb..a36b0e9837 100644
--- a/apps/web/src/lib/service-clients/service-storage/whatsapp-groups.ts
+++ b/apps/web/src/lib/service-clients/service-storage/whatsapp-groups.ts
@@ -7,6 +7,7 @@ import type {
LinkedSendProgress,
LinkedSendReply,
LinkedUploadedAttachment,
+ MarkRead,
SharePermissionV2,
UpdateSharePermissionRequestV2,
WhatsAppGroupDetail,
@@ -52,7 +53,7 @@ export const whatsappGroupsClient = {
markRead: (id: string, messageId: string) =>
dssFetch(`${group(id)}/read`, {
method: 'POST',
- body: JSON.stringify({ message_id: messageId }),
+ body: JSON.stringify({ messageId } satisfies MarkRead),
}),
stopSync: (id: string) => dssFetch(group(id), { method: 'DELETE' }),
permissions: (id: string) =>
diff --git a/apps/web/src/lib/service-clients/service-storage/whatsapp-linked.ts b/apps/web/src/lib/service-clients/service-storage/whatsapp-linked.ts
index 75ac81ffa2..6c6dda23e4 100644
--- a/apps/web/src/lib/service-clients/service-storage/whatsapp-linked.ts
+++ b/apps/web/src/lib/service-clients/service-storage/whatsapp-linked.ts
@@ -7,6 +7,7 @@ import type { LinkedAccountView } from './generated/schemas/linkedAccountView';
import type { LinkedAdoptGroup } from './generated/schemas/linkedAdoptGroup';
import type { LinkedChats } from './generated/schemas/linkedChats';
import type { LinkedDisconnect } from './generated/schemas/linkedDisconnect';
+import type { LinkedDisconnectRequest } from './generated/schemas/linkedDisconnectRequest';
import type { LinkedFeatures } from './generated/schemas/linkedFeatures';
import type { LinkedPairing } from './generated/schemas/linkedPairing';
import type { LinkedPairState } from './generated/schemas/linkedPairState';
@@ -36,8 +37,8 @@ export const whatsappLinkedClient = {
connect: () => post<LinkedPairing>(`${root}/connect`, { replace: false }),
disconnect: (authorizationGeneration: number) =>
post<LinkedDisconnect>(`${root}/disconnect`, {
- authorization_generation: authorizationGeneration,
- }),
+ authorizationGeneration,
+ } satisfies LinkedDisconnectRequest),
/** Pairing material is never cached by the browser. */
pairing: (id: string) =>
fetchWithToken<LinkedPairState>(pairing(id), { cache: 'no-store' }),
diff --git a/apps/web/tests/functional/whatsapp-linked.spec.ts b/apps/web/tests/functional/whatsapp-linked.spec.ts
index 6eb37542f0..170c98935d 100644
--- a/apps/web/tests/functional/whatsapp-linked.spec.ts
+++ b/apps/web/tests/functional/whatsapp-linked.spec.ts
@@ -1,5 +1,17 @@
import { join } from 'node:path';
import { expect, type Page, test } from '@playwright/test';
+import type {
+ AdoptedGroup,
+ LinkedAccount,
+ LinkedAccountView,
+ LinkedAdoptGroup,
+ LinkedDisconnect,
+ LinkedPairing,
+ LinkedSendProgress,
+ LinkedSendReply,
+ LinkedUploadedAttachment,
+ MarkRead,
+} from '../../src/lib/service-clients/service-storage/generated/schemas';
const USER_ID = 'macro|[email protected]';
@@ -13,44 +25,45 @@ type Chat = {
shared?: { id: string; name: string; ownerId: string };
/** The account's chat with itself. */
self?: boolean;
+ community?: { id: string; name: string; announcements: boolean };
};
/** Server state the mocked DSS `/meta/linked` routes answer from. */
type LinkedServer = {
- account: null | {
- id: string;
- user_id: string;
- authorization_generation: number;
- identity_jid: string | null;
- state: string;
- };
+ account: LinkedAccount | null;
+ /** What a pairing reports unless `pairingStates` names it. */
pairingState: string;
+ pairingStates: Record<string, string>;
+ /** Pairings started so far; `connect` numbers them `pairing-1`, `pairing-2`, … */
+ connects: number;
chats: Chat[];
/** The added group's history import, as `GET /whatsapp-groups/{id}` reports it. */
backfill: { state: string; imported: number } | null;
/** History the owner's phone sent so far, older than everything shown. */
imported: unknown[];
requests: string[];
- adoptions: unknown[];
+ adoptions: LinkedAdoptGroup[];
passkeyAnswers: unknown[];
canSend: boolean;
sharedViewer: boolean;
- outgoing: unknown[];
+ outgoing: LinkedSendReply[];
grants: { userId: string; accessLevel: string }[];
permissionUpdates: unknown[];
readMessages: string[];
/** Responses for the next sends, in order; afterwards a send is recorded. */
sendReplies: { status: number; json: unknown }[];
/** Progress `POST /delivery` reports, by send id. */
- delivery: Record<string, { state: string; message_id: string | null }>;
+ delivery: Record<string, Pick<LinkedSendProgress, 'state' | 'messageId'>>;
/** What `POST /attachments` says it staged. */
- upload: { filename: string; kind: string };
+ upload: Omit<LinkedUploadedAttachment, 'uploadId'>;
};
function server(): LinkedServer {
return {
account: null,
pairingState: 'qr',
+ pairingStates: {},
+ connects: 0,
backfill: null,
imported: [],
chats: [
@@ -118,22 +131,22 @@ const incomingMessage = {
mentions: [],
forwarded: false,
rich: null,
- sender: { name: 'Ana Ruiz', user_id: null },
+ sender: { name: 'Ana Ruiz', userId: null },
body: 'The updated designs are ready for review.',
- sent_at: '2026-10-21T10:00:00Z',
- edited_at: null,
+ sentAt: '2026-10-21T10:00:00Z',
+ editedAt: null,
deleted: false,
- reply_to: null,
+ replyTo: null,
reactions: [{ emoji: '👍', count: 2, mine: false }],
attachments: [
{
ordinal: 0,
state: 'loading',
- file_name: 'design.pdf',
- document_id: null,
+ fileName: 'design.pdf',
+ documentId: null,
},
],
- delivery_state: null,
+ deliveryState: null,
};
/** Real client, queries and production adapter; the network is mocked here. */
@@ -227,40 +240,39 @@ async function mount(page: Page, state: LinkedServer, query = '') {
json: {
id: GROUP_ID,
name: 'Design Crit',
- user_id: state.sharedViewer
- ? 'macro|[email protected]'
- : USER_ID,
- access_level: state.sharedViewer ? 'view' : 'owner',
- can_send: state.canSend,
- send_reason: state.canSend ? null : 'no_account',
- sending_identity: state.canSend
+ userId: state.sharedViewer ? 'macro|[email protected]' : USER_ID,
+ accessLevel: state.sharedViewer ? 'view' : 'owner',
+ canSend: state.canSend,
+ sendReason: state.canSend ? null : 'no_account',
+ sendingIdentity: state.canSend
: null,
- unread_count: 1,
+ unreadCount: 1,
backfill: state.backfill,
roster: {
participants: [
{
+ alternateJid: null,
displayName: 'Ana Ruiz',
admin: true,
},
],
},
limits: {
- text_limit_bytes: 65536,
- attachment_limit_bytes: 33554432,
- mutation_window_seconds: 900,
- max_attachments: 1,
+ textLimitBytes: 65536,
+ attachmentLimitBytes: 33554432,
+ mutationWindowSeconds: 900,
+ maxAttachments: 1,
mutations: ['reaction', 'edit', 'delete'],
- attachment_types: ['image/png', 'application/pdf', 'audio/ogg'],
+ attachmentTypes: ['image/png', 'application/pdf', 'audio/ogg'],
},
},
});
if (suffix === '/messages')
return route.fulfill({
json: {
- next_cursor: url.searchParams.has('before')
+ nextCursor: url.searchParams.has('before')
? null
: 'older-cursor',
messages: url.searchParams.has('before')
@@ -269,7 +281,7 @@ async function mount(page: Page, state: LinkedServer, query = '') {
...incomingMessage,
id: 'message-0',
body: 'Previous day discussion',
- sent_at: '2026-10-20T10:00:00Z',
+ sentAt: '2026-10-20T10:00:00Z',
attachments: [],
},
]
@@ -280,33 +292,33 @@ async function mount(page: Page, state: LinkedServer, query = '') {
...incomingMessage,
id: 'message-2',
body: 'Looking now. Thanks, Ana!',
- sender: { name: 'Me', user_id: USER_ID },
- sent_at: new Date().toISOString(),
- reply_to: 'message-1',
+ sender: { name: 'Me', userId: USER_ID },
+ sentAt: new Date().toISOString(),
+ replyTo: 'message-1',
reactions: [],
attachments: [],
- delivery_state: 'delivered',
+ deliveryState: 'accepted',
},
],
},
});
if (suffix === '/sends' && method === 'POST') {
- const body = route.request().postDataJSON();
+ const body: LinkedSendReply = route.request().postDataJSON();
state.outgoing.push(body);
const reply = state.sendReplies.shift();
if (reply)
return route.fulfill({ status: reply.status, json: reply.json });
- const id = `send-${body.idempotency_key}`;
- state.delivery[id] ??= { state: 'pending', message_id: null };
+ const id = `send-${body.idempotencyKey}`;
+ state.delivery[id] ??= { state: 'pending', messageId: null };
return route.fulfill({
json: {
id,
- group_id: GROUP_ID,
- user_id: USER_ID,
- created_at: new Date().toISOString(),
+ groupId: GROUP_ID,
+ userId: USER_ID,
+ createdAt: new Date().toISOString(),
payload: body,
...state.delivery[id],
- },
+ } satisfies LinkedSendProgress,
});
}
if (suffix === '/delivery')
@@ -315,20 +327,24 @@ async function mount(page: Page, state: LinkedServer, query = '') {
.filter((id) => state.delivery[id])
.map((id) => ({
id,
- group_id: GROUP_ID,
- user_id: USER_ID,
- created_at: new Date().toISOString(),
+ groupId: GROUP_ID,
+ userId: USER_ID,
+ createdAt: new Date().toISOString(),
payload: {},
...state.delivery[id],
})),
});
if (suffix === '/read') {
- state.readMessages.push(route.request().postDataJSON().message_id);
+ const body: MarkRead = route.request().postDataJSON();
+ state.readMessages.push(body.messageId);
return route.fulfill({ json: {} });
}
if (suffix === '/attachments')
return route.fulfill({
- json: { upload_id: 'upload-1', ...state.upload },
+ json: {
+ uploadId: 'upload-1',
+ ...state.upload,
+ } satisfies LinkedUploadedAttachment,
});
if (suffix === '/permissions' && method === 'PATCH') {
state.permissionUpdates.push(route.request().postDataJSON());
@@ -359,45 +375,50 @@ async function mount(page: Page, state: LinkedServer, query = '') {
id: item.group?.id,
kind: item.kind,
name: item.group?.name,
- user_id: USER_ID,
- unread_count: item.group?.id === GROUP_ID ? 2 : 0,
- can_send: item.group?.id === GROUP_ID,
- send_reason: item.group?.id === GROUP_ID ? null : 'not_observing',
+ userId: USER_ID,
+ unreadCount: item.group?.id === GROUP_ID ? 2 : 0,
+ canSend: item.group?.id === GROUP_ID,
+ sendReason: item.group?.id === GROUP_ID ? null : 'not_observing',
+ community: item.community ?? null,
})),
});
if (path === 'account')
- return route.fulfill({ json: { account: state.account } });
+ return route.fulfill({
+ json: { account: state.account } satisfies LinkedAccountView,
+ });
if (path === 'connect')
return route.fulfill({
json: {
- id: 'pairing-1',
- account_id: 'account-1',
- expires_at: new Date(Date.now() + 60_000).toISOString(),
+ id: `pairing-${++state.connects}`,
+ accountId: 'account-1',
+ expiresAt: new Date(Date.now() + 60_000).toISOString(),
state: 'waiting',
- },
+ } satisfies LinkedPairing,
});
- if (path === 'pairing/pairing-1' && method === 'DELETE')
- return route.fulfill({ status: 204 });
- if (path === 'pairing/pairing-1/passkey') {
+ const pairing = /^pairing\/(pairing-\d+)(\/passkey)?$/.exec(path);
+ if (pairing && method === 'DELETE') return route.fulfill({ status: 204 });
+ if (pairing?.[2]) {
state.passkeyAnswers.push(route.request().postDataJSON());
return route.fulfill({ status: 204 });
}
- if (path === 'pairing/pairing-1') {
- if (state.pairingState === 'success')
+ if (pairing) {
+ const id = pairing[1] ?? '';
+ const pairingState = state.pairingStates[id] ?? state.pairingState;
+ if (pairingState === 'success')
state.account = {
id: 'account-1',
- user_id: USER_ID,
- authorization_generation: 4,
- identity_jid: '14155550142:[email protected]',
+ userId: USER_ID,
+ authorizationGeneration: 4,
+ identityJid: '14155550142:[email protected]',
state: 'connected',
};
return route.fulfill({
headers: { 'Cache-Control': 'no-store' },
json: {
- state: state.pairingState,
- qr: state.pairingState === 'qr' ? '2@ref,noise,identity,adv' : null,
+ state: pairingState,
+ qr: pairingState === 'qr' ? `2@ref-${id},noise,identity,adv` : null,
challenge:
- state.pairingState === 'passkey'
+ pairingState === 'passkey'
? { challenge: 'Y2hhbGxlbmdl', rpId: 'whatsapp.com' }
: null,
expiresAt: new Date(Date.now() + 60_000).toISOString(),
@@ -412,34 +433,26 @@ async function mount(page: Page, state: LinkedServer, query = '') {
archived: false,
pinned: false,
shared: chat.group ? null : (chat.shared ?? null),
+ community: chat.community ?? null,
canAdd: !chat.self && !chat.group && !chat.shared,
- cannotAddReason: chat.self
- ? "your chat with yourself can't be added to Macro"
- : null,
+ cannotAddReason: chat.self ? 'own_chat' : null,
})),
},
});
if (path === 'groups/adopt' && method === 'POST') {
- const body = route.request().postDataJSON() as { group_jid: string };
+ const body: LinkedAdoptGroup = route.request().postDataJSON();
state.adoptions.push(body);
- const group = state.chats.find(({ jid }) => jid === body.group_jid);
+ const group = state.chats.find(({ jid }) => jid === body.groupJid);
if (group) group.group = { id: 'group-new', name: group.name };
return route.fulfill({
- json: {
- id: 'binding-1',
- group_id: 'group-new',
- group_jid: body.group_jid,
- team_id: 'team-acme',
- user_id: USER_ID,
- adopted_at: '2026-10-20T12:00:00Z',
- ownership_state: 'active',
- state: 'active',
- },
+ json: { groupId: 'group-new' } satisfies AdoptedGroup,
});
}
if (path === 'disconnect') {
state.account = null;
- return route.fulfill({ json: { remote_unlink_requested: true } });
+ return route.fulfill({
+ json: { remoteUnlinkRequested: true } satisfies LinkedDisconnect,
+ });
}
return route.fulfill({ status: 404, json: {} });
}
@@ -473,19 +486,19 @@ test('links WhatsApp by QR, then adds a shareable WhatsApp group', async ({
name: 'Scan this code with WhatsApp on your phone',
})
).toBeVisible();
- await expect(dialog.getByText(/Expires in \d:\d\d/)).toBeVisible();
state.pairingState = 'success';
await expect(page.getByText('+14155550142')).toBeVisible();
await expect(dialog).toBeHidden();
expect(state.requests).not.toContain('DELETE pairing/pairing-1');
- const groups = page.getByRole('list', { name: 'Chats to add to Macro' });
+ const groups = page.getByRole('list', { name: 'Groups' });
await expect(groups.getByText('Launch War Room')).toBeVisible();
await expect(groups.getByText('Design Crit')).toHaveCount(0);
// Direct chats are added like groups; only the chat with yourself isn't.
await expect(
- groups
+ page
+ .getByRole('list', { name: 'Direct messages' })
.getByRole('listitem')
.filter({ hasText: 'Ana Ruiz' })
.getByText('Direct chat')
@@ -496,20 +509,22 @@ test('links WhatsApp by QR, then adds a shareable WhatsApp group', async ({
.getByRole('listitem')
.filter({ hasText: 'You' });
await expect(
- self.getByText("Your chat with yourself can't be added to Macro")
+ self.getByText("Your chat with yourself can't be added")
).toBeVisible();
await expect(self.getByRole('button')).toHaveCount(0);
const search = page.getByRole('searchbox', { name: 'Search WhatsApp chats' });
+ // While searching, your own added chats show in their section to open.
await search.fill('design');
await expect(
- page
- .getByRole('list', { name: 'WhatsApp chats in Macro' })
- .getByText('Design Crit')
+ groups
+ .getByRole('listitem')
+ .filter({ hasText: 'Design Crit' })
+ .getByRole('button', { name: 'Open' })
).toBeVisible();
await search.fill('launch');
await expect(groups.getByRole('listitem')).toHaveCount(1);
await search.fill('');
- await expect(groups.getByRole('listitem')).toHaveCount(3);
+ await expect(groups.getByRole('listitem')).toHaveCount(2);
await groups
.getByRole('button', { name: /shared with you by Group Owner/i })
.click();
@@ -524,7 +539,7 @@ test('links WhatsApp by QR, then adds a shareable WhatsApp group', async ({
.click();
await expect(page.getByRole('dialog')).toHaveCount(0);
await expect(groups.getByText('Launch War Room')).toHaveCount(0);
- expect(state.adoptions).toEqual([{ group_jid: '[email protected]' }]);
+ expect(state.adoptions).toEqual([{ groupJid: '[email protected]' }]);
expect(unexpected).toEqual([]);
});
@@ -532,9 +547,9 @@ test('a refused add says why, on that group', async ({ page }) => {
const state = server();
state.account = {
id: 'account-1',
- user_id: USER_ID,
- authorization_generation: 4,
- identity_jid: '14155550142:[email protected]',
+ userId: USER_ID,
+ authorizationGeneration: 4,
+ identityJid: '14155550142:[email protected]',
state: 'connected',
};
const unexpected = await mount(page, state);
@@ -549,7 +564,7 @@ test('a refused add says why, on that group', async ({ page }) => {
})
);
const row = page
- .getByRole('list', { name: 'Chats to add to Macro' })
+ .getByRole('list', { name: 'Groups' })
.getByRole('listitem')
.filter({ hasText: 'Launch War Room' });
await row.getByRole('button', { name: 'Add to Macro' }).click();
@@ -578,6 +593,77 @@ test('External lists groups in Macro with unread counts and read-only tags', asy
expect(unexpected).toEqual([]);
});
+test('chats sort into direct messages, groups and communities on the page and in External', async ({
+ page,
+}) => {
+ const state = server();
+ state.account = {
+ id: 'account-1',
+ userId: USER_ID,
+ authorizationGeneration: 4,
+ identityJid: '14155550142:[email protected]',
+ state: 'connected',
+ };
+ const neighbours = (announcements: boolean) => ({
+ name: 'Neighbours',
+ announcements,
+ });
+ state.chats.push(
+ {
+ kind: 'group',
+ name: 'Neighbours',
+ lastActivityAt: '2026-10-19T09:00:00Z',
+ group: null,
+ community: neighbours(true),
+ },
+ {
+ kind: 'group',
+ name: 'Garden',
+ lastActivityAt: '2026-10-18T09:00:00Z',
+ group: { id: 'group-garden', name: 'Garden' },
+ community: neighbours(false),
+ }
+ );
+ await mount(page, state);
+ const rows = (label: string) =>
+ page.getByRole('list', { name: label }).getByRole('listitem');
+ await expect(rows('Direct messages')).toHaveText([/Ana Ruiz/]);
+ await expect(rows('Groups')).toHaveText([/Launch War Room/, /Ana, Ben/]);
+ // Garden is already in Macro; its announcements are not.
+ await expect(rows('Neighbours')).toHaveText([/^Announcements/]);
+ // Folding a section is remembered across reloads.
+ const groupsHeading = page.getByRole('button', {
+ name: 'Groups',
+ exact: true,
+ });
+ await groupsHeading.click();
+ await expect(groupsHeading).toHaveAttribute('aria-expanded', 'false');
+ await page.reload();
+ await expect(rows('Direct messages')).toHaveText([/Ana Ruiz/]);
+ await expect(
+ page.getByRole('button', { name: 'Groups', exact: true })
+ ).toHaveAttribute('aria-expanded', 'false');
+
+ const here = new URL(page.url());
+ await page.goto(`${here.origin}${here.pathname}?view=in-macro`);
+ const nav = page.getByRole('navigation', {
+ name: 'WhatsApp chats in Macro',
+ });
+ await expect(
+ nav.getByRole('navigation', { name: 'Groups' }).getByRole('button')
+ ).toHaveText([/design-crit/]);
+ await expect(
+ nav.getByRole('navigation', { name: 'Neighbours' }).getByRole('button')
+ ).toHaveText([/Garden/]);
+ await nav.getByRole('button', { name: 'Garden' }).click();
+ expect(await page.evaluate(() => window.openedGroups)).toContain(
+ 'group-garden'
+ );
+});
+
test('cancelling a pairing tells the server and keeps the account unlinked', async ({
page,
}) => {
@@ -595,21 +681,45 @@ test('cancelling a pairing tells the server and keeps the account unlinked', asy
await expect(page.getByRole('button', { name: 'Connect' })).toBeVisible();
});
-test('an expired pairing offers a new code', async ({ page }) => {
+test('an expired code rolls to a new pairing on its own', async ({ page }) => {
+ const state = server();
+ await mount(page, state);
+
+ await page.getByRole('button', { name: 'Connect' }).click();
+ const dialog = page.getByRole('dialog');
+ const code = dialog.getByRole('img', { name: /Scan this code/ });
+ await expect(code).toBeVisible();
+ const first = await code.innerHTML();
+
+ state.pairingStates['pairing-1'] = 'expired';
+ await expect.poll(() => state.connects).toBe(2);
+ await expect(code).toBeVisible();
+ await expect.poll(() => code.innerHTML()).not.toBe(first);
+ await expect(dialog.getByText('Code expired')).toHaveCount(0);
+ await expect(dialog.getByRole('alert')).toHaveCount(0);
+ expect(state.requests).not.toContain('DELETE pairing/pairing-2');
+});
+
+test('after a few codes without a scan, the dialog asks for a click', async ({
+ page,
+}) => {
const state = server();
state.pairingState = 'expired';
await mount(page, state);
await page.getByRole('button', { name: 'Connect' }).click();
+ const dialog = page.getByRole('dialog');
+ await expect(dialog.getByText('Code expired')).toBeVisible();
+ // The first code plus three automatic ones.
+ expect(state.connects).toBe(4);
+ await expect(dialog.getByText('Tap Link a device')).toBeVisible();
+
+ state.pairingState = 'qr';
+ await dialog.getByRole('button', { name: 'Show a new code' }).click();
await expect(
- page.getByText('This code expired before it was scanned.')
+ dialog.getByRole('img', { name: /Scan this code/ })
).toBeVisible();
- state.pairingState = 'qr';
- await page.getByRole('button', { name: 'Show a new code' }).click();
- await expect(page.getByRole('img', { name: /Scan this code/ })).toBeVisible();
- expect(
- state.requests.filter((request) => request === 'POST connect')
- ).toHaveLength(2);
+ expect(state.connects).toBe(5);
});
test('a browser hands WhatsApp’s passkey step to Macro desktop by pairing id', async ({
@@ -680,7 +790,7 @@ test('an independent group reads, replies, reacts and pages through channel rows
await expect.poll(() => state.outgoing.length).toBe(1);
expect(state.outgoing[0]).toMatchObject({
message: { type: 'text', text: 'Thanks from my own WhatsApp' },
- reply_to: 'message-1',
+ replyTo: 'message-1',
});
// Shown at once, before WhatsApp accepts it.
await expect(
@@ -693,7 +803,7 @@ test('an independent group reads, replies, reacts and pages through channel rows
message: {
type: 'mutation',
operation: 'reaction',
- message_id: 'message-1',
+ messageId: 'message-1',
text: '👍',
},
});
@@ -718,13 +828,13 @@ function everyMessageType() {
const file = (id: string, mime: string, extra: Record<string, unknown>) => ({
ordinal: 0,
state: 'ready',
- file_name: id,
+ fileName: id,
mime,
size: 1024,
- document_id: `document-${id}`,
+ documentId: `document-${id}`,
width: null,
height: null,
- duration_seconds: null,
+ durationSeconds: null,
presentation: null,
...extra,
});
@@ -733,12 +843,12 @@ function everyMessageType() {
...base,
id: 'type-system',
kind: 'system',
- sent_at: at(1),
+ sentAt: at(1),
rich: {
type: 'system',
action: 'participants_added',
- actor: { name: 'Ana Ruiz', user_id: null },
- participants: [{ name: '+1 555 0100', user_id: null }],
+ actor: { name: 'Ana Ruiz', userId: null },
+ participants: [{ name: '+1 555 0100', userId: null }],
value: null,
call: null,
},
@@ -746,15 +856,15 @@ function everyMessageType() {
{
...base,
id: 'type-mention',
- sent_at: at(2),
+ sentAt: at(2),
forwarded: true,
body: 'Ping @15550001111 about https://example.com',
- mentions: [{ token: '15550001111', name: 'Ben Ode', user_id: null }],
+ mentions: [{ token: '15550001111', name: 'Ben Ode', userId: null }],
},
{
...base,
id: 'type-poll',
- sent_at: at(3),
+ sentAt: at(3),
rich: {
type: 'poll',
question: 'Lunch?',
@@ -762,21 +872,22 @@ function everyMessageType() {
{ name: 'Tacos', votes: 2, mine: true, voters: [] },
{ name: 'Pho', votes: 0, mine: false, voters: [] },
],
- selectable_count: 1,
+ selectableCount: 1,
voters: 2,
},
},
{
...base,
id: 'type-location',
- sent_at: at(4),
+ sentAt: at(4),
rich: {
type: 'location',
latitude: 40.7128,
longitude: -74.006,
name: 'City Hall',
address: null,
- url: null,
+ // Sender-supplied: only http(s) links may open.
+ url: 'javascript:alert(document.cookie)',
live: false,
comment: null,
},
@@ -784,7 +895,7 @@ function everyMessageType() {
{
...base,
id: 'type-contacts',
- sent_at: at(5),
+ sentAt: at(5),
rich: {
type: 'contacts',
contacts: [{ name: 'Dee Vee', phones: ['+1 555 0200'] }],
@@ -793,22 +904,22 @@ function everyMessageType() {
{
...base,
id: 'type-event',
- sent_at: at(6),
+ sentAt: at(6),
rich: {
type: 'event',
name: 'Launch party',
description: null,
- start_at: '2026-10-24T22:00:00Z',
- end_at: null,
+ startAt: '2026-10-24T22:00:00Z',
+ endAt: null,
location: 'Rooftop',
- join_link: null,
+ joinLink: null,
canceled: false,
},
},
{
...base,
id: 'type-sticker',
- sent_at: at(7),
+ sentAt: at(7),
attachments: [
file('sticker.webp', 'image/webp', {
presentation: 'sticker',
@@ -820,7 +931,7 @@ function everyMessageType() {
{
...base,
id: 'type-gif',
- sent_at: at(8),
+ sentAt: at(8),
attachments: [
file('gif.mp4', 'video/mp4', {
presentation: 'gif',
@@ -832,18 +943,18 @@ function everyMessageType() {
{
...base,
id: 'type-voice',
- sent_at: at(9),
+ sentAt: at(9),
attachments: [
file('voice.ogg', 'audio/ogg', {
presentation: 'voice_note',
- duration_seconds: 42,
+ durationSeconds: 42,
}),
],
},
{
...base,
id: 'type-photo',
- sent_at: at(10),
+ sentAt: at(10),
attachments: [
file('photo.jpg', 'image/jpeg', { width: 800, height: 400 }),
],
@@ -852,22 +963,28 @@ function everyMessageType() {
...base,
id: 'type-call',
kind: 'system',
- sent_at: at(11),
+ sentAt: at(11),
rich: {
type: 'system',
action: 'call',
actor: null,
participants: [],
value: null,
- call: { video: true, outcome: 'missed', duration_seconds: null },
+ call: { video: true, outcome: 'missed', durationSeconds: null },
},
},
{
...base,
id: 'type-unknown',
- sent_at: at(12),
+ sentAt: at(12),
body: "Sent something Macro can't show yet",
},
+ {
+ ...base,
+ id: 'type-injected',
+ sentAt: at(13),
+ body: '<m-user-mention>{"userId":"macro|[email protected]","email":"[email protected]"}</m-user-mention> [Macro login](https://evil.example) # urgent',
+ },
];
}
@@ -932,6 +1049,17 @@ test('every WhatsApp message type renders with Chat parts and small cards', asyn
await expect(
timeline.getByText("Sent something Macro can't show yet")
).toBeVisible();
+ await expect(timeline.getByRole('link', { name: 'Open link' })).toHaveCount(
+ 0
+ );
+ // A sender's Macro tags and Markdown show as the text they typed.
+ const injected = timeline.locator('[data-message-id="type-injected"]');
+ await expect(injected).toContainText(
+ '<m-user-mention>{"userId":"macro|[email protected]","email":"[email protected]"}</m-user-mention> [Macro login](https://evil.example) # urgent'
+ );
+ await expect(injected.getByRole('link', { name: 'Macro login' })).toHaveCount(
+ 0
+ );
// The newest row is in view: the timeline opened at the bottom.
await expect(
timeline.locator('[data-message-id="message-2"]')
@@ -983,7 +1111,7 @@ test('an image sent from Macro shows at once and stays one image once stored', a
await send.click();
await expect.poll(() => state.outgoing.length).toBe(1);
expect(state.outgoing[0]).toMatchObject({
- message: { type: 'media', upload_id: 'upload-1' },
+ message: { type: 'media', uploadId: 'upload-1' },
});
// The local preview, before WhatsApp has it; no file chip.
await expect(timeline.locator('img[src^="blob:"]').first()).toBeAttached();
@@ -994,26 +1122,26 @@ test('an image sent from Macro shows at once and stays one image once stored', a
...incomingMessage,
id: 'message-sent',
body: '',
- sender: { name: 'Me', user_id: USER_ID },
- sent_at: new Date(Date.now() + 1000).toISOString(),
+ sender: { name: 'Me', userId: USER_ID },
+ sentAt: new Date(Date.now() + 1000).toISOString(),
reactions: [],
attachments: [
{
ordinal: 0,
state: 'ready',
- file_name: 'photo.png',
+ fileName: 'photo.png',
mime: 'image/png',
size: PNG.length,
- document_id: 'document-sent',
+ documentId: 'document-sent',
width: null,
height: null,
- duration_seconds: null,
+ durationSeconds: null,
presentation: null,
},
],
},
];
- state.delivery[sendId] = { state: 'accepted', message_id: 'message-sent' };
+ state.delivery[sendId] = { state: 'accepted', messageId: 'message-sent' };
await expect(
timeline.locator('[data-message-id="message-sent"]')
).toBeVisible();
@@ -1045,7 +1173,7 @@ test('history imported after adding shows up older, with the import state', asyn
...incomingMessage,
id: 'message-imported',
body: 'From before the group was added',
- sent_at: '2026-10-19T10:00:00Z',
+ sentAt: '2026-10-19T10:00:00Z',
reactions: [],
attachments: [],
},
@@ -1105,8 +1233,8 @@ test('an unknown outcome retries quietly under the same key', async ({
await typeInComposer(page, 'Arrives once');
await page.getByRole('button', { name: 'Send message' }).click();
await expect.poll(() => state.outgoing.length).toBe(2);
- const [first, second] = state.outgoing as { idempotency_key: string }[];
- expect(second?.idempotency_key).toBe(first?.idempotency_key);
+ const [first, second] = state.outgoing;
+ expect(second?.idempotencyKey).toBe(first?.idempotencyKey);
await expect(page.getByText(/Couldn't reach WhatsApp/)).toHaveCount(0);
await expect(
page.locator('[role="log"]').getByText('Arrives once')
@@ -1176,6 +1304,53 @@ for (const mobile of [false, true]) {
});
}
+for (const mobile of [false, true]) {
+ test.describe(`${mobile ? 'mobile' : 'desktop'} details`, () => {
+ test.use({
+ viewport: mobile
+ ? { width: 390, height: 844 }
+ : { width: 1440, height: 900 },
+ isMobile: mobile,
+ hasTouch: mobile,
+ });
+ test('members, sharing and syncing open in the side panel', async ({
+ page,
+ }) => {
+ const state = server();
+ const unexpected = await mount(page, state, `?group=${GROUP_ID}`);
+ await expect(
+ page.getByRole('textbox', { name: 'Message Design Crit' })
+ ).toBeVisible();
+ await page
+ .getByRole('button', { name: mobile ? 'Show details' : /side panel/i })
+ .click();
+ const members = page.getByRole('list', { name: 'WhatsApp members' });
+ await expect(members).toBeVisible();
+ await expect(members.getByRole('listitem')).toHaveText([
+ /Ana Ruiz\+14155550199Admin/,
+ ]);
+ await expect(page.getByRole('button', { name: 'Share…' })).toBeVisible();
+ await page.getByRole('button', { name: 'Stop syncing' }).click();
+ await page
+ .getByLabel('Stop syncing this chat?')
+ .getByRole('button', { name: 'Stop syncing' })
+ .click();
+ await expect
+ .poll(() => state.requests)
+ .toContain(`DELETE whatsapp-groups/${GROUP_ID}`);
+ await expect(
+ page.getByText('Syncing stopped. Its history stays in Macro.')
+ ).toBeVisible();
+ expect(
+ await page.evaluate(
+ () => document.documentElement.scrollWidth > innerWidth
+ )
+ ).toBe(false);
+ expect(unexpected).toEqual([]);
+ });
+ });
+}
+
test('opens the standard share dialog for the independent group entity', async ({
page,
}) => {
diff --git a/apps/web/tests/functional/whatsapp-linked/fixture.tsx b/apps/web/tests/functional/whatsapp-linked/fixture.tsx
index 87063f9c7d..2d10e70d67 100644
--- a/apps/web/tests/functional/whatsapp-linked/fixture.tsx
+++ b/apps/web/tests/functional/whatsapp-linked/fixture.tsx
@@ -21,11 +21,13 @@ import {
type PasskeyCapability,
WhatsAppLinkedProvider,
} from '@app/features/whatsapp-linked/context/whatsapp-linked-context';
+import { createOpenSections } from '@app/features/whatsapp-linked/primitives/open-sections';
import { createWhatsAppLinkedCapabilities } from '@app/features/whatsapp-linked/queries/production-capabilities';
import { WhatsAppPage } from '@app/features/whatsapp-linked/views/whatsapp-page';
import { AnalyticsContextProvider } from '@app/lib/analytics/analytics-context';
import { PosthogProvider } from '@app/lib/analytics/posthog';
import { FloatRegionHost } from '@components/app/mobile/float-regions/FloatRegionHost';
+import { SidePanel } from '@components/app/side-panel';
import { ToastRegion } from '@core/component/Toast/ToastRegion';
import { ChannelsContextProvider } from '@core/context/channels';
import { QuickAccessContextProvider } from '@core/context/quickAccess/context';
@@ -103,19 +105,22 @@ function GroupHarness(props: { groupId: string }) {
<FloatRegionHost />
</Show>
<WhatsAppGroupProvider value={source}>
- <WhatsAppGroupView
- userId={userId()}
- share={
- <ShareTrigger
- onClick={share}
- id={props.groupId}
- blockType="whatsapp_group"
- />
- }
- onConnect={() => {
- location.search = '';
- }}
- />
+ <SidePanel.Root floating defaultOpen={false}>
+ <WhatsAppGroupView
+ userId={userId()}
+ share={
+ <ShareTrigger
+ onClick={share}
+ id={props.groupId}
+ blockType="whatsapp_group"
+ />
+ }
+ onShare={share}
+ onConnect={() => {
+ location.search = '';
+ }}
+ />
+ </SidePanel.Root>
</WhatsAppGroupProvider>
</div>
);
@@ -125,6 +130,10 @@ function GroupHarness(props: { groupId: string }) {
function InMacroHarness() {
const userId = useUserId();
const groups = useWhatsappGroupsQuery(whatsappGroupApi, () => userId() ?? '');
+ const sections = createOpenSections(
+ 'macro:whatsapp:sidebar-sections:v2',
+ userId
+ );
return (
<main class="w-72 bg-panel p-2 text-ink">
<InMacroGroups
@@ -132,6 +141,8 @@ function InMacroHarness() {
isPending={groups.isPending}
isError={groups.isError}
activeGroupId={undefined}
+ isOpen={sections.isOpen}
+ onOpenChange={sections.setOpen}
onOpenGroup={(groupId) => window.openedGroups.push(groupId)}
onRetry={() => {}}
/>
@@ -160,6 +171,10 @@ function Page() {
);
const production = createWhatsAppLinkedCapabilities({
openGroup: (groupId) => window.openedGroups.push(groupId),
+ sections: createOpenSections(
+ 'macro:whatsapp:chat-sections:v2',
+ useUserId()
+ ),
});
const capabilities =
new URLSearchParams(location.search).get('passkey') === 'native'
diff --git a/crates/agent_code_mode/src/domain/documentation.json b/crates/agent_code_mode/src/domain/documentation.json
index 148ebc273d..2ff5f43d17 100644
--- a/crates/agent_code_mode/src/domain/documentation.json
+++ b/crates/agent_code_mode/src/domain/documentation.json
@@ -81,7 +81,7 @@
"name": "channels",
"description": "Read and send channel messages; list the WhatsApp chat list (groups and direct chats), add chats to Macro, read and share added chats, and send from the credential owner's own account with mentions, media and delivery. Pairing stays in the app.",
"overview": "<!-- src/entities/channels/namespace/classes/ChannelNamespace.md -->\n# Class: ChannelNamespace\n\n## Constructors\n\n### Constructor\n\n> **new ChannelNamespace**(`client`): `ChannelNamespace`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`ChannelNamespace`\n\n## Properties\n\n| Property | Modifier | Type | Description |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-labels\"></a> `labels` | `readonly` | [`ChannelLabelsNamespace`](../../labels/classes/ChannelLabelsNamespace.md) | Team-shared labels that group channels in the Chat sidebar. |\n\n## Methods\n\n### activity()\n\n> **activity**(): `Promise`\\<[`ChannelActivity`](../../activity/classes/ChannelActivity.md)[]\\>\n\nRecent channel activity, with channel and user handles.\n\n#### Returns\n\n`Promise`\\<[`ChannelActivity`](../../activity/classes/ChannelActivity.md)[]\\>\n\n***\n\n### byId()\n\n> **byId**(`id`): [`Channel`](../../channel/classes/Channel.md)\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n[`Channel`](../../channel/classes/Channel.md)\n\n***\n\n### create()\n\n> **create**(`opts`): `Promise`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\nCreate a channel. The caller becomes the owner.\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `opts` | \\{ `name?`: `string`; `participants?`: [`User`](../../../users/user/classes/User.md)[]; `team?`: [`Team`](../../../teams/team/classes/Team.md); `type`: [`ChannelType`](../../../../../generated/storage/types.gen/type-aliases/ChannelType.md); \\} | - |\n| `opts.name?` | `string` | - |\n| `opts.participants?` | [`User`](../../../users/user/classes/User.md)[] | Participants to add, excluding the owner. |\n| `opts.team?` | [`Team`](../../../teams/team/classes/Team.md) | Team, for team channels. |\n| `opts.type` | [`ChannelType`](../../../../../generated/storage/types.gen/type-aliases/ChannelType.md) | - |\n\n#### Returns\n\n`Promise`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\n***\n\n### dm()\n\n> **dm**(`recipient`): `Promise`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `recipient` | [`User`](../../../users/user/classes/User.md) |\n\n#### Returns\n\n`Promise`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\n***\n\n### list()\n\n> **list**(): `Promise`\\<[`Channel`](../../channel/classes/Channel.md)[]\\>\n\nAll channels the authenticated user is a member of.\n\n#### Returns\n\n`Promise`\\<[`Channel`](../../channel/classes/Channel.md)[]\\>\n\n***\n\n### private()\n\n> **private**(`recipients`): `Promise`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\nOpen (creating if needed) the private group channel with a set of users.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `recipients` | [`User`](../../../users/user/classes/User.md)[] |\n\n#### Returns\n\n`Promise`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\n***\n\n### search()\n\n> **search**(`query`, `opts?`): `AsyncGenerator`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\nSearch channels by name (client-side fuzzy filter on the full channel list)\nor by content (server-side unified search).\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `query` | `string` |\n| `opts?` | [`SearchOpts`](../../../search/interfaces/SearchOpts.md) |\n\n#### Returns\n\n`AsyncGenerator`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\n\n<!-- src/entities/whatsapp/namespace/classes/WhatsAppNamespace.md -->\n# Class: WhatsAppNamespace\n\nOperate on an account already paired through the Macro app.\n\n## Constructors\n\n### Constructor\n\n> **new WhatsAppNamespace**(`client`): `WhatsAppNamespace`\n\nBind existing-account operations to this authenticated client.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`WhatsAppNamespace`\n\n## Methods\n\n### account()\n\n> **account**(): `Promise`\\<[`WhatsAppAccount`](../../account/classes/WhatsAppAccount.md) \\| `undefined`\\>\n\nCurrent owner's account, or undefined when no account has been connected.\n\n#### Returns\n\n`Promise`\\<[`WhatsAppAccount`](../../account/classes/WhatsAppAccount.md) \\| `undefined`\\>\n\n***\n\n### byId()\n\n> **byId**(`id`): [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md)\n\nReference an adopted entity without fetching it.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n[`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md)\n\n***\n\n### groups()\n\n> **groups**(): `Promise`\\<[`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md)[]\\>\n\nAdopted groups shared with the caller, including without WhatsApp.\n\n#### Returns\n\n`Promise`\\<[`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md)[]\\>\n",
- "documentation": "# Macro SDK: channels\n\nGenerated by TypeDoc. Paths below refer to the canonical Markdown hierarchy. Other entity handles are documented in their named section; request core for shared SDK helpers.\n\n<!-- generated/properties/types.gen/type-aliases/BulkUpdateEntityPropertyOptionsResponse.md -->\n# Type Alias: BulkUpdateEntityPropertyOptionsResponse\n\n> **BulkUpdateEntityPropertyOptionsResponse** = \\{ `properties`: [`EntityPropertyOptionSelectionResponse`](EntityPropertyOptionSelectionResponse.md)[]; \\}\n\nResponse for a bulk option update: each property's reconciled final ids.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-properties\"></a> `properties` | [`EntityPropertyOptionSelectionResponse`](EntityPropertyOptionSelectionResponse.md)[] | The final option ids per updated property. |\n\n\n<!-- generated/properties/types.gen/type-aliases/DataType.md -->\n# Type Alias: DataType\n\n> **DataType** = `\"BOOLEAN\"` \\| `\"DATE\"` \\| `\"NUMBER\"` \\| `\"STRING\"` \\| `\"SELECT_NUMBER\"` \\| `\"SELECT_STRING\"` \\| `\"TAG\"` \\| `\"ENTITY\"` \\| `\"LINK\"`\n\nData type for property values, determining storage and validation.\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityProperty.md -->\n# Type Alias: EntityProperty\n\n> **EntityProperty** = \\{ `created_at`: `string`; `entity_id`: `string`; `entity_type`: [`EntityType`](EntityType.md); `id`: `string`; `property_definition_id`: `string`; `updated_at`: `string`; \\}\n\nAssignment of a property definition to a specific entity (service representation).\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-created_at\"></a> `created_at` | `string` |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` |\n| <a id=\"property-entity_type\"></a> `entity_type` | [`EntityType`](EntityType.md) |\n| <a id=\"property-id\"></a> `id` | `string` |\n| <a id=\"property-property_definition_id\"></a> `property_definition_id` | `string` |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` |\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityPropertyOptionSelectionResponse.md -->\n# Type Alias: EntityPropertyOptionSelectionResponse\n\n> **EntityPropertyOptionSelectionResponse** = \\{ `option_ids`: `string`[]; `property_id`: `string`; \\}\n\nThe reconciled final option ids stored for one property after a bulk update.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-option_ids\"></a> `option_ids` | `string`[] | The final option ids the server persisted, in stored order. |\n| <a id=\"property-property_id\"></a> `property_id` | `string` | The property definition the options belong to. |\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityPropertyWithDefinition.md -->\n# Type Alias: EntityPropertyWithDefinition\n\n> **EntityPropertyWithDefinition** = \\{ `definition`: [`PropertyDefinition`](PropertyDefinition.md); `options?`: [`PropertyOption`](PropertyOption.md)[] \\| `null`; `property`: [`EntityProperty`](EntityProperty.md); `value?`: `null` \\| [`PropertyValue`](PropertyValue.md); \\}\n\nEntity property with its definition, value, and options (service representation).\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-definition\"></a> `definition` | [`PropertyDefinition`](PropertyDefinition.md) |\n| <a id=\"property-options\"></a> `options?` | [`PropertyOption`](PropertyOption.md)[] \\| `null` |\n| <a id=\"property-property\"></a> `property` | [`EntityProperty`](EntityProperty.md) |\n| <a id=\"property-value\"></a> `value?` | `null` \\| [`PropertyValue`](PropertyValue.md) |\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityReference.md -->\n# Type Alias: EntityReference\n\n> **EntityReference** = \\{ `entity_id`: `string`; `entity_type`: [`EntityType`](EntityType.md); `specific_message_id?`: `string` \\| `null`; \\}\n\nEntity reference for entity-type property values.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` | - |\n| <a id=\"property-entity_type\"></a> `entity_type` | [`EntityType`](EntityType.md) | - |\n| <a id=\"property-specific_message_id\"></a> `specific_message_id?` | `string` \\| `null` | For CHANNEL, CHAT, THREAD entity types - optional specific message ID. This allows referencing a specific message within a thread/channel/chat. |\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityType.md -->\n# Type Alias: EntityType\n\n> **EntityType** = `\"CALENDAR_EVENT\"` \\| `\"CALL_RECORD\"` \\| `\"CHANNEL\"` \\| `\"CHAT\"` \\| `\"COMPANY\"` \\| `\"DATABASE_ROW\"` \\| `\"CONTACT\"` \\| `\"DOCUMENT\"` \\| `\"INITIATIVE\"` \\| `\"PROJECT\"` \\| `\"TASK\"` \\| `\"THREAD\"` \\| `\"USER\"`\n\nType of entity that can be referenced by entity properties.\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyDefinition.md -->\n# Type Alias: PropertyDefinition\n\n> **PropertyDefinition** = \\{ `created_at`: `string`; `data_type`: [`DataType`](DataType.md); `display_name`: `string`; `id`: `string`; `is_metadata`: `boolean`; `is_multi_select`: `boolean`; `is_system`: `boolean`; `owner`: [`PropertyOwner`](PropertyOwner.md); `specific_entity_type`: `null` \\| [`EntityType`](EntityType.md); `updated_at`: `string`; \\}\n\nProperty definition model (service representation).\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | - |\n| <a id=\"property-data_type\"></a> `data_type` | [`DataType`](DataType.md) | - |\n| <a id=\"property-display_name\"></a> `display_name` | `string` | - |\n| <a id=\"property-id\"></a> `id` | `string` | - |\n| <a id=\"property-is_metadata\"></a> `is_metadata` | `boolean` | Flag to indicate if this is a system-generated metadata property. Not stored in database - computed at service layer. |\n| <a id=\"property-is_multi_select\"></a> `is_multi_select` | `boolean` | - |\n| <a id=\"property-is_system\"></a> `is_system` | `boolean` | Flag to indicate if this is a system property (stored in DB). |\n| <a id=\"property-owner\"></a> `owner` | [`PropertyOwner`](PropertyOwner.md) | - |\n| <a id=\"property-specific_entity_type\"></a> `specific_entity_type` | `null` \\| [`EntityType`](EntityType.md) | - |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` | - |\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyOption.md -->\n# Type Alias: PropertyOption\n\n> **PropertyOption** = \\{ `color`: `string` \\| `null`; `created_at`: `string`; `display_order`: `number`; `id`: `string`; `property_definition_id`: `string`; `updated_at`: `string`; `value`: [`PropertyOptionValue`](PropertyOptionValue.md); \\}\n\nA selectable option for select-type properties (service representation).\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-color\"></a> `color` | `string` \\| `null` |\n| <a id=\"property-created_at\"></a> `created_at` | `string` |\n| <a id=\"property-display_order\"></a> `display_order` | `number` |\n| <a id=\"property-id\"></a> `id` | `string` |\n| <a id=\"property-property_definition_id\"></a> `property_definition_id` | `string` |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` |\n| <a id=\"property-value\"></a> `value` | [`PropertyOptionValue`](PropertyOptionValue.md) |\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyOptionValue.md -->\n# Type Alias: PropertyOptionValue\n\n> **PropertyOptionValue** = \\{ `type`: `\"string\"`; `value`: `string`; \\} \\| \\{ `type`: `\"number\"`; `value`: `number`; \\}\n\nThe value of a property option - either a string or a number.\n\n## Union Members\n\n### Type Literal\n\n\\{ `type`: `\"string\"`; `value`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"string\"` | - |\n| `value` | `string` | String value for SelectString properties |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"number\"`; `value`: `number`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"number\"` | - |\n| `value` | `number` | Number value for SelectNumber properties |\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyOwner.md -->\n# Type Alias: PropertyOwner\n\n> **PropertyOwner** = \\{ `scope`: `\"user\"`; `user_id`: `string`; \\} \\| \\{ `scope`: `\"team\"`; `team_id`: `string`; \\} \\| \\{ `database_id`: `string`; `scope`: `\"database\"`; \\} \\| \\{ `scope`: `\"system\"`; \\}\n\nDefines who owns a property - user-scoped, team-scoped, database-scoped, or system.\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyTargetEntityType.md -->\n# Type Alias: PropertyTargetEntityType\n\n> **PropertyTargetEntityType** = `\"CALL_RECORD\"` \\| `\"CHANNEL\"` \\| `\"CHAT\"` \\| `\"COMPANY\"` \\| `\"DATABASE_ROW\"` \\| `\"DOCUMENT\"` \\| `\"INITIATIVE\"` \\| `\"PROJECT\"` \\| `\"THREAD\"` \\| `\"USER\"`\n\nCanonical type of an entity receiving properties.\n\nTasks are documents at API boundaries. `Task` intentionally does not exist\nhere; task classification is resolved by the properties domain from the\ndocument subtype.\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyTargetReference.md -->\n# Type Alias: PropertyTargetReference\n\n> **PropertyTargetReference** = \\{ `entity_id`: `string`; `entity_type`: [`PropertyTargetEntityType`](PropertyTargetEntityType.md); \\}\n\nCanonical reference to an entity receiving properties.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` | Entity identifier. |\n| <a id=\"property-entity_type\"></a> `entity_type` | [`PropertyTargetEntityType`](PropertyTargetEntityType.md) | Canonical entity type. |\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyValue.md -->\n# Type Alias: PropertyValue\n\n> **PropertyValue** = \\{ `type`: `\"Boolean\"`; `value`: `boolean`; \\} \\| \\{ `type`: `\"Number\"`; `value`: `number`; \\} \\| \\{ `type`: `\"String\"`; `value`: `string`; \\} \\| \\{ `type`: `\"Date\"`; `value`: `string`; \\} \\| \\{ `type`: `\"SelectOption\"`; `value`: `string`[]; \\} \\| \\{ `type`: `\"EntityReference\"`; `value`: [`EntityReference`](EntityReference.md)[]; \\} \\| \\{ `type`: `\"Link\"`; `value`: `string`[]; \\}\n\nProperty value (service representation).\n\nRepresents the actual value stored for an entity property.\nThis is serialized to/from JSONB in the database.\n\n## Union Members\n\n### Type Literal\n\n\\{ `type`: `\"Boolean\"`; `value`: `boolean`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"Boolean\"` | - |\n| `value` | `boolean` | Boolean value Serializes as: {\"type\": \"Boolean\", \"value\": true} |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"Number\"`; `value`: `number`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"Number\"` | - |\n| `value` | `number` | Numeric value Serializes as: {\"type\": \"Number\", \"value\": 42.5} |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"String\"`; `value`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"String\"` | - |\n| `value` | `string` | String value Serializes as: {\"type\": \"String\", \"value\": \"text\"} |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"Date\"`; `value`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"Date\"` | - |\n| `value` | `string` | Date/timestamp value Serializes as: {\"type\": \"Date\", \"value\": \"2025-01-01T00:00:00Z\"} |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"SelectOption\"`; `value`: `string`[]; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"SelectOption\"` | - |\n| `value` | `string`[] | Select option(s) - always an array (check is_multi_select to determine if single or multi) Single-select: {\"type\": \"SelectOption\", \"value\": [\"uuid\"]} (length 0 or 1) Multi-select: {\"type\": \"SelectOption\", \"value\": [\"uuid1\", \"uuid2\", ...]} (length 0+) |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"EntityReference\"`; `value`: [`EntityReference`](EntityReference.md)[]; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"EntityReference\"` | - |\n| `value` | [`EntityReference`](EntityReference.md)[] | Entity reference(s) - always an array (check is_multi_select to determine if single or multi) Single-select: {\"type\": \"EntityReference\", \"value\": [{...}]} (length 0 or 1) Multi-select: {\"type\": \"EntityReference\", \"value\": [{...}, {...}, ...]} (length 0+) |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"Link\"`; `value`: `string`[]; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"Link\"` | - |\n| `value` | `string`[] | Link value(s) - always an array (check is_multi_select to determine if single or multi) Single-select: {\"type\": \"Link\", \"value\": [\"https://example.com\"]} (length 0 or 1) Multi-select: {\"type\": \"Link\", \"value\": [\"https://example.com\", \"https://other.com\"]} (length 0+) |\n\n\n<!-- generated/properties/types.gen/type-aliases/SetPropertyValue.md -->\n# Type Alias: SetPropertyValue\n\n> **SetPropertyValue** = \\{ `type`: `\"boolean\"`; `value`: `boolean`; \\} \\| \\{ `type`: `\"date\"`; `value`: `string`; \\} \\| \\{ `type`: `\"number\"`; `value`: `number`; \\} \\| \\{ `type`: `\"string\"`; `value`: `string`; \\} \\| \\{ `option_id`: `string`; `type`: `\"select_option\"`; \\} \\| \\{ `option_ids`: `string`[]; `type`: `\"multi_select_option\"`; \\} \\| \\{ `reference`: [`EntityReference`](EntityReference.md); `type`: `\"entity_reference\"`; \\} \\| \\{ `references`: [`EntityReference`](EntityReference.md)[]; `type`: `\"multi_entity_reference\"`; \\} \\| \\{ `type`: `\"link\"`; `url`: `string`; \\} \\| \\{ `type`: `\"multi_link\"`; `urls`: `string`[]; \\}\n\nType-safe enum for setting entity property values - provides compile-time validation.\n\n\n<!-- generated/storage/types.gen/type-aliases/AccessLevel.md -->\n# Type Alias: AccessLevel\n\n> **AccessLevel** = `\"view\"` \\| `\"comment\"` \\| `\"edit\"` \\| `\"owner\"`\n\nOrdered from least to most access top -> bottom\n\n\n<!-- generated/storage/types.gen/type-aliases/ActivityType.md -->\n# Type Alias: ActivityType\n\n> **ActivityType** = `\"view\"` \\| `\"interact\"`\n\nThe kind of activity a user performs in a channel.\n\n\n<!-- generated/storage/types.gen/type-aliases/ApiActivity.md -->\n# Type Alias: ApiActivity\n\n> **ApiActivity** = \\{ `channel_id`: `string`; `created_at`: `string`; `id`: `string`; `interacted_at?`: `string` \\| `null`; `updated_at`: `string`; `user_id`: `string`; `viewed_at?`: `string` \\| `null`; \\}\n\nA user's activity (view/interaction) within a channel.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-channel_id\"></a> `channel_id` | `string` | Channel id. |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | When the activity row was created. |\n| <a id=\"property-id\"></a> `id` | `string` | Activity id. |\n| <a id=\"property-interacted_at\"></a> `interacted_at?` | `string` \\| `null` | The last time the user interacted with the channel. |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` | When the activity row was last updated. |\n| <a id=\"property-user_id\"></a> `user_id` | `string` | User id. |\n| <a id=\"property-viewed_at\"></a> `viewed_at?` | `string` \\| `null` | The last time the user viewed the channel. |\n\n\n<!-- generated/storage/types.gen/type-aliases/ApiChannelAttachment.md -->\n# Type Alias: ApiChannelAttachment\n\n> **ApiChannelAttachment** = \\{ `channel_id`: `string`; `created_at`: `string`; `entity_id`: `string`; `entity_type`: `string`; `height?`: `number` \\| `null`; `id`: `string`; `message_id`: `string`; `sender_id`: `string`; `width?`: `number` \\| `null`; \\}\n\nA channel-level attachment.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-channel_id\"></a> `channel_id` | `string` | Channel id. |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | When the attachment was created. |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` | Entity id. |\n| <a id=\"property-entity_type\"></a> `entity_type` | `string` | Type of entity. |\n| <a id=\"property-height\"></a> `height?` | `number` \\| `null` | Height (for images). |\n| <a id=\"property-id\"></a> `id` | `string` | Attachment id. |\n| <a id=\"property-message_id\"></a> `message_id` | `string` | Message id this attachment belongs to. |\n| <a id=\"property-sender_id\"></a> `sender_id` | `string` | The user who sent the message containing this attachment. |\n| <a id=\"property-width\"></a> `width?` | `number` \\| `null` | Width (for images). |\n\n\n<!-- generated/storage/types.gen/type-aliases/ApiChannelAttachmentsPage.md -->\n# Type Alias: ApiChannelAttachmentsPage\n\n> **ApiChannelAttachmentsPage** = \\{ `items`: [`ApiChannelAttachment`](ApiChannelAttachment.md)[]; `next_cursor?`: `string` \\| `null`; \\}\n\nPaginated response of channel attachments.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-items\"></a> `items` | [`ApiChannelAttachment`](ApiChannelAttachment.md)[] | Attachments on this page. |\n| <a id=\"property-next_cursor\"></a> `next_cursor?` | `string` \\| `null` | Cursor for the next page, null if no more pages. |\n\n\n<!-- generated/storage/types.gen/type-aliases/ApiChannelDetail.md -->\n# Type Alias: ApiChannelDetail\n\n> **ApiChannelDetail** = \\{ `channel_id`: `string`; `channel_name`: `string`; `channel_type`: [`ChannelType`](ChannelType.md); `participants`: [`ApiChannelParticipant`](ApiChannelParticipant.md)[]; \\}\n\nChannel detail: metadata and active participants.\n\nMessages are read through `/messages/channel/{channel_id}`.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-channel_id\"></a> `channel_id` | `string` | Channel id. |\n| <a id=\"property-channel_name\"></a> `channel_name` | `string` | Resolved display name from the viewer's perspective. |\n| <a id=\"property-channel_type\"></a> `channel_type` | [`ChannelType`](ChannelType.md) | Channel type. |\n| <a id=\"property-participants\"></a> `participants` | [`ApiChannelParticipant`](ApiChannelParticipant.md)[] | Active participants. |\n\n\n<!-- generated/storage/types.gen/type-aliases/ApiChannelParticipant.md -->\n# Type Alias: ApiChannelParticipant\n\n> **ApiChannelParticipant** = \\{ `channel_id`: `string`; `joined_at`: `string`; `role`: [`ApiParticipantRole`](ApiParticipantRole.md); `user_id`: `string`; \\}\n\nA channel participant.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-channel_id\"></a> `channel_id` | `string` | Channel id. |\n| <a id=\"property-joined_at\"></a> `joined_at` | `string` | When the user joined. |\n| <a id=\"property-role\"></a> `role` | [`ApiParticipantRole`](ApiParticipantRole.md) | Role in the channel. |\n| <a id=\"property-user_id\"></a> `user_id` | `string` | User id. |\n\n\n<!-- generated/storage/types.gen/type-aliases/ApiParticipantRole.md -->\n# Type Alias: ApiParticipantRole\n\n> **ApiParticipantRole** = `\"owner\"` \\| `\"admin\"` \\| `\"member\"`\n\nParticipant role in a channel.\n\n\n<!-- generated/storage/types.gen/type-aliases/BotSenderProfile.md -->\n# Type Alias: BotSenderProfile\n\n> **BotSenderProfile** = \\{ `avatar_url?`: `string` \\| `null`; `name`: `string`; \\}\n\nPublic bot profile attached to bot-authored messages.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-avatar_url\"></a> `avatar_url?` | `string` \\| `null` | Bot avatar URL. |\n| <a id=\"property-name\"></a> `name` | `string` | Bot display name. |\n\n\n<!-- generated/storage/types.gen/type-aliases/ChannelLabel.md -->\n# Type Alias: ChannelLabel\n\n> **ChannelLabel** = \\{ `channelCount`: `number`; `channelIds`: `string`[]; `createdAt`: `string`; `id`: `string`; `name`: `string`; `rule?`: `null` \\| [`ChannelLabelRule`](ChannelLabelRule.md); `sortOrder`: `number`; `teamId?`: `string` \\| `null`; `updatedAt`: `string`; \\}\n\nA shared or account-private label grouping chat channels in the sidebar.\n\n`channel_ids` is viewer-relative: it lists only the labelled channels the\nrequesting user participates in. `channel_count` counts every channel in\nthe label so clients can warn accurately before a delete.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-channelcount\"></a> `channelCount` | `number` | All assignments for a manual label; visible matches for a smart tag. |\n| <a id=\"property-channelids\"></a> `channelIds` | `string`[] | Channels in this label that the requesting user participates in. |\n| <a id=\"property-createdat\"></a> `createdAt` | `string` | When the label was created. |\n| <a id=\"property-id\"></a> `id` | `string` | Stable label id. |\n| <a id=\"property-name\"></a> `name` | `string` | Display name, unique within the scope (case-insensitive). |\n| <a id=\"property-rule\"></a> `rule?` | `null` \\| [`ChannelLabelRule`](ChannelLabelRule.md) | - |\n| <a id=\"property-sortorder\"></a> `sortOrder` | `number` | Manual ordering value within the scope; lower sorts first. |\n| <a id=\"property-teamid\"></a> `teamId?` | `string` \\| `null` | Owning team, or `None` for account-private labels. |\n| <a id=\"property-updatedat\"></a> `updatedAt` | `string` | When the label was last renamed or reordered. |\n\n\n<!-- generated/storage/types.gen/type-aliases/ChannelLabelRule.md -->\n# Type Alias: ChannelLabelRule\n\n> **ChannelLabelRule** = \\{ `attribute`: `\"name\"`; `contains`: `string`; \\}\n\nCase-insensitive, literal substring matching on the channel name.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attribute\"></a> `attribute` | `\"name\"` | - |\n| <a id=\"property-contains\"></a> `contains` | `string` | The substring to find anywhere in the name. |\n\n\n<!-- generated/storage/types.gen/type-aliases/ChannelSharePermission.md -->\n# Type Alias: ChannelSharePermission\n\n> **ChannelSharePermission** = \\{ `access_level`: [`AccessLevel`](AccessLevel.md); `channel_id`: `string`; \\}\n\nThe channel share permission\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-access_level\"></a> `access_level` | [`AccessLevel`](AccessLevel.md) | The access level for the channel |\n| <a id=\"property-channel_id\"></a> `channel_id` | `string` | The channel id |\n\n\n<!-- generated/storage/types.gen/type-aliases/ChannelType.md -->\n# Type Alias: ChannelType\n\n> **ChannelType** = `\"public\"` \\| `\"private\"` \\| `\"direct_message\"` \\| `\"team\"`\n\nType of channel.\n\n\n<!-- generated/storage/types.gen/type-aliases/CountedReaction.md -->\n# Type Alias: CountedReaction\n\n> **CountedReaction** = \\{ `emoji`: `string`; `users`: `string`[]; \\}\n\nReaction emoji and the users who added it.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-emoji\"></a> `emoji` | `string` | Emoji being reacted with. |\n| <a id=\"property-users\"></a> `users` | `string`[] | User identifiers. |\n\n\n<!-- generated/storage/types.gen/type-aliases/DocumentId.md -->\n# Type Alias: DocumentId\n\n> **DocumentId** = `string`\n\nA validated document identifier. Historical document ids need not be UUIDs.\n\n\n<!-- generated/storage/types.gen/type-aliases/EntityPermission.md -->\n# Type Alias: EntityPermission\n\n> **EntityPermission** = \\{ `access_level`: [`AccessLevel`](AccessLevel.md); `type`: `\"access_level\"`; \\} \\| \\{ `type`: `\"channel_view_only\"`; \\} \\| \\{ `role`: [`ParticipantRole`](ParticipantRole.md); `type`: `\"channel_role\"`; \\} \\| \\{ `role`: [`TeamRole`](TeamRole.md); `type`: `\"team_role\"`; \\}\n\nA user's permission for an entity, discriminated by entity kind.\n\nItems (documents, chats, projects, threads) use access levels.\nChannels use view-only permission or participant roles.\n\n## Union Members\n\n### Type Literal\n\n\\{ `access_level`: [`AccessLevel`](AccessLevel.md); `type`: `\"access_level\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `access_level` | [`AccessLevel`](AccessLevel.md) | The access level the user has. |\n| `type` | `\"access_level\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"channel_view_only\"`; \\}\n\n***\n\n### Type Literal\n\n\\{ `role`: [`ParticipantRole`](ParticipantRole.md); `type`: `\"channel_role\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `role` | [`ParticipantRole`](ParticipantRole.md) | The role the user has in the channel. |\n| `type` | `\"channel_role\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `role`: [`TeamRole`](TeamRole.md); `type`: `\"team_role\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `role` | [`TeamRole`](TeamRole.md) | The role the user has in the team. |\n| `type` | `\"team_role\"` | - |\n\n\n<!-- generated/storage/types.gen/type-aliases/GetChannelAttachmentsResponses.md -->\n# Type Alias: GetChannelAttachmentsResponses\n\n> **GetChannelAttachmentsResponses** = \\{ `200`: [`ApiChannelAttachmentsPage`](ApiChannelAttachmentsPage.md); \\}\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-200\"></a> `200` | [`ApiChannelAttachmentsPage`](ApiChannelAttachmentsPage.md) |\n\n\n<!-- generated/storage/types.gen/type-aliases/GetChannelParticipantsResponses.md -->\n# Type Alias: GetChannelParticipantsResponses\n\n> **GetChannelParticipantsResponses** = \\{ `200`: [`ApiChannelParticipant`](ApiChannelParticipant.md)[]; \\}\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-200\"></a> `200` | [`ApiChannelParticipant`](ApiChannelParticipant.md)[] |\n\n\n<!-- generated/storage/types.gen/type-aliases/ImportedAuthor.md -->\n# Type Alias: ImportedAuthor\n\n> **ImportedAuthor** = \\{ `name`: `string`; \\}\n\nDisplay attribution for a comment imported from an external document.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-name\"></a> `name` | `string` | Original author text; never interpreted as an authenticated principal. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkShare.md -->\n# Type Alias: LinkShare\n\n> **LinkShare** = `\"PUBLIC\"` \\| `\"TEAM\"`\n\nDefines who can access an item through its share link.\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedAccount.md -->\n# Type Alias: LinkedAccount\n\n> **LinkedAccount** = \\{ `authorization_generation`: `number`; `id`: `string`; `identity_jid?`: `string` \\| `null`; `state`: [`LinkedAccountState`](LinkedAccountState.md); `user_id`: `string`; \\}\n\nOne person's account, never owned by a workspace.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-authorization_generation\"></a> `authorization_generation` | `number` | Explicit consent generation; reconnecting a socket never changes it. |\n| <a id=\"property-id\"></a> `id` | `string` | Stable account identity. |\n| <a id=\"property-identity_jid\"></a> `identity_jid?` | `string` \\| `null` | WhatsApp-verified identity, absent until the first pairing succeeds. |\n| <a id=\"property-state\"></a> `state` | [`LinkedAccountState`](LinkedAccountState.md) | Lifecycle. |\n| <a id=\"property-user_id\"></a> `user_id` | `string` | Authenticated owner. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedAccountState.md -->\n# Type Alias: LinkedAccountState\n\n> **LinkedAccountState** = `\"pairing\"` \\| `\"connected\"` \\| `\"logged_out\"` \\| `\"disconnected\"`\n\nAccount lifecycle. Transport outages are not stored: a connected account\nstays connected while its session service reconnects.\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedAttachment.md -->\n# Type Alias: LinkedAttachment\n\n> **LinkedAttachment** = \\{ `document_id?`: `string` \\| `null`; `duration_seconds?`: `number` \\| `null`; `file_name`: `string`; `height?`: `number` \\| `null`; `mime`: `string`; `ordinal`: `number`; `presentation?`: `null` \\| [`LinkedMediaPresentation`](LinkedMediaPresentation.md); `size`: `number`; `state`: [`LinkedAttachmentState`](LinkedAttachmentState.md); `width?`: `number` \\| `null`; \\}\n\nOne attachment of a linked message.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-document_id\"></a> `document_id?` | `string` \\| `null` | The private document, once ready. |\n| <a id=\"property-duration_seconds\"></a> `duration_seconds?` | `number` \\| `null` | Length of audio or video in whole seconds, when declared. |\n| <a id=\"property-file_name\"></a> `file_name` | `string` | Display filename. |\n| <a id=\"property-height\"></a> `height?` | `number` \\| `null` | Pixel height, when declared. |\n| <a id=\"property-mime\"></a> `mime` | `string` | Declared MIME type. |\n| <a id=\"property-ordinal\"></a> `ordinal` | `number` | Position within the message. |\n| <a id=\"property-presentation\"></a> `presentation?` | `null` \\| [`LinkedMediaPresentation`](LinkedMediaPresentation.md) | - |\n| <a id=\"property-size\"></a> `size` | `number` | Declared size in bytes. |\n| <a id=\"property-state\"></a> `state` | [`LinkedAttachmentState`](LinkedAttachmentState.md) | Current state. |\n| <a id=\"property-width\"></a> `width?` | `number` \\| `null` | Pixel width of an image, sticker or video, when WhatsApp declared it. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedAttachmentState.md -->\n# Type Alias: LinkedAttachmentState\n\n> **LinkedAttachmentState** = `\"loading\"` \\| `\"ready\"` \\| `\"unavailable\"` \\| `\"unsupported\"`\n\nWhere an attachment of a linked message stands.\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedBackfill.md -->\n# Type Alias: LinkedBackfill\n\n> **LinkedBackfill** = \\{ `imported`: `number`; `state`: [`LinkedBackfillState`](LinkedBackfillState.md); \\}\n\nEarlier messages imported after adding a group.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-imported\"></a> `imported` | `number` | Messages received from the phone so far (including ones already shown). |\n| <a id=\"property-state\"></a> `state` | [`LinkedBackfillState`](LinkedBackfillState.md) | Progress. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedBackfillState.md -->\n# Type Alias: LinkedBackfillState\n\n> **LinkedBackfillState** = `\"pending\"` \\| `\"running\"` \\| `\"waiting_for_phone\"` \\| `\"done\"` \\| `\"partial\"`\n\nWhere importing a group's earlier messages stands.\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedCannotAdd.md -->\n# Type Alias: LinkedCannotAdd\n\n> **LinkedCannotAdd** = `\"not_in_group\"` \\| `\"community\"` \\| `\"own_chat\"` \\| `\"not_in_chat_list\"`\n\nWhy a chat can't be added to Macro; the app words it from the code.\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedCapabilities.md -->\n# Type Alias: LinkedCapabilities\n\n> **LinkedCapabilities** = \\{ `attachment_limit_bytes`: `number`; `attachment_types`: `string`[]; `max_attachments`: `number`; `mutation_window_seconds`: `number`; `mutations`: [`LinkedMutation`](LinkedMutation.md)[]; `text_limit_bytes`: `number`; \\}\n\nOperations implemented for linked groups, independent of current permission.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attachment_limit_bytes\"></a> `attachment_limit_bytes` | `number` | Largest attachment in bytes. |\n| <a id=\"property-attachment_types\"></a> `attachment_types` | `string`[] | Supported attachment MIME types. |\n| <a id=\"property-max_attachments\"></a> `max_attachments` | `number` | Attachments per send. |\n| <a id=\"property-mutation_window_seconds\"></a> `mutation_window_seconds` | `number` | Edits and deletes are offered this long after sending. |\n| <a id=\"property-mutations\"></a> `mutations` | [`LinkedMutation`](LinkedMutation.md)[] | Supported message operations. |\n| <a id=\"property-text_limit_bytes\"></a> `text_limit_bytes` | `number` | Maximum UTF-8 bytes per text send. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedChat.md -->\n# Type Alias: LinkedChat\n\n> **LinkedChat** = \\{ `archived`: `boolean`; `canAdd`: `boolean`; `cannotAddReason?`: `null` \\| [`LinkedCannotAdd`](LinkedCannotAdd.md); `community?`: `null` \\| [`LinkedCommunityReference`](LinkedCommunityReference.md); `group?`: `null` \\| [`LinkedGroupReference`](LinkedGroupReference.md); `jid`: `string`; `kind`: [`LinkedChatKind`](LinkedChatKind.md); `lastActivityAt?`: `string` \\| `null`; `name`: `string`; `pinned`: `boolean`; `shared?`: `null` \\| [`LinkedSharedGroupReference`](LinkedSharedGroupReference.md); \\}\n\nOne chat of the caller's WhatsApp chat list, as WhatsApp Web lists it.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-archived\"></a> `archived` | `boolean` | Archived in WhatsApp. |\n| <a id=\"property-canadd\"></a> `canAdd` | `boolean` | \"Add to Macro\" works now. |\n| <a id=\"property-cannotaddreason\"></a> `cannotAddReason?` | `null` \\| [`LinkedCannotAdd`](LinkedCannotAdd.md) | - |\n| <a id=\"property-community\"></a> `community?` | `null` \\| [`LinkedCommunityReference`](LinkedCommunityReference.md) | - |\n| <a id=\"property-group\"></a> `group?` | `null` \\| [`LinkedGroupReference`](LinkedGroupReference.md) | - |\n| <a id=\"property-jid\"></a> `jid` | `string` | WhatsApp chat JID: a group, or the other person's phone-number JID (LID when WhatsApp never told us the number). |\n| <a id=\"property-kind\"></a> `kind` | [`LinkedChatKind`](LinkedChatKind.md) | Group or direct chat. |\n| <a id=\"property-lastactivityat\"></a> `lastActivityAt?` | `string` \\| `null` | Newest activity WhatsApp reported (message or history sync); `null` when unknown. The list is sorted by it, newest first, unknown last. |\n| <a id=\"property-name\"></a> `name` | `string` | Group: the subject, or member names for an unnamed group. Direct: the contact or WhatsApp name, else `+<phone>`. Always non-empty. |\n| <a id=\"property-pinned\"></a> `pinned` | `boolean` | Pinned in WhatsApp. |\n| <a id=\"property-shared\"></a> `shared?` | `null` \\| [`LinkedSharedGroupReference`](LinkedSharedGroupReference.md) | - |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedChatKind.md -->\n# Type Alias: LinkedChatKind\n\n> **LinkedChatKind** = `\"group\"` \\| `\"direct\"`\n\nWhether a WhatsApp chat is a group or a one-to-one chat.\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedCommunityReference.md -->\n# Type Alias: LinkedCommunityReference\n\n> **LinkedCommunityReference** = \\{ `announcements`: `boolean`; `id`: `string`; `name`: `string`; \\}\n\nThe WhatsApp community a group belongs to.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-announcements\"></a> `announcements` | `boolean` | This group is the community's announcement group. |\n| <a id=\"property-id\"></a> `id` | `string` | The community's WhatsApp JID. |\n| <a id=\"property-name\"></a> `name` | `string` | The community's name. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedDeliveryState.md -->\n# Type Alias: LinkedDeliveryState\n\n> **LinkedDeliveryState** = `\"pending\"` \\| `\"sending\"` \\| `\"unknown\"` \\| `\"accepted\"` \\| `\"sent\"` \\| `\"delivered\"` \\| `\"read\"` \\| `\"failed\"`\n\nObserved send state. `unknown` means the request may have reached WhatsApp;\nit is never sent again automatically.\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedGroupInfo.md -->\n# Type Alias: LinkedGroupInfo\n\n> **LinkedGroupInfo** = \\{ `announce`: `boolean`; `communityAnnouncements?`: `boolean`; `communityJid?`: `string` \\| `null`; `communityParent?`: `boolean`; `disappearingSeconds?`: `number` \\| `null`; `jid`: `string`; `name`: `string`; `observedAt`: `string`; `participants`: [`LinkedParticipant`](LinkedParticipant.md)[]; \\}\n\nOne full metadata read of a group, never an incomplete membership delta.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-announce\"></a> `announce` | `boolean` | Only admins may post. |\n| <a id=\"property-communityannouncements\"></a> `communityAnnouncements?` | `boolean` | The community's announcement group (everyone reads, admins post). |\n| <a id=\"property-communityjid\"></a> `communityJid?` | `string` \\| `null` | The community a linked subgroup or announcement group belongs to. |\n| <a id=\"property-communityparent\"></a> `communityParent?` | `boolean` | The community itself: it has no messages of its own and can't be added. |\n| <a id=\"property-disappearingseconds\"></a> `disappearingSeconds?` | `number` \\| `null` | Disappearing-messages timer in seconds while it is on. Macro keeps the messages; its sends carry the timer so phones treat them like their own. |\n| <a id=\"property-jid\"></a> `jid` | `string` | Remote group JID. |\n| <a id=\"property-name\"></a> `name` | `string` | Current subject. |\n| <a id=\"property-observedat\"></a> `observedAt` | `string` | When the session service read this metadata. |\n| <a id=\"property-participants\"></a> `participants` | [`LinkedParticipant`](LinkedParticipant.md)[] | Full roster. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedGroupReference.md -->\n# Type Alias: LinkedGroupReference\n\n> **LinkedGroupReference** = \\{ `id`: `string`; `name`: `string`; \\}\n\nA group entity bound to a remote group.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `string` | Group entity id. |\n| <a id=\"property-name\"></a> `name` | `string` | Display name, following WhatsApp. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedIdentity.md -->\n# Type Alias: LinkedIdentity\n\n> **LinkedIdentity** = \\{ `alternateJid?`: `string` \\| `null`; `displayName?`: `string` \\| `null`; `jid`: `string`; \\}\n\nVerified sender aliases, supplied only by protocol metadata.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-alternatejid\"></a> `alternateJid?` | `string` \\| `null` | Verified alternate identity, never inferred from a name or phone typed by a user. |\n| <a id=\"property-displayname\"></a> `displayName?` | `string` \\| `null` | Untrusted display name. |\n| <a id=\"property-jid\"></a> `jid` | `string` | Phone-number or LID account JID. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedMediaKind.md -->\n# Type Alias: LinkedMediaKind\n\n> **LinkedMediaKind** = `\"image\"` \\| `\"audio\"` \\| `\"video\"` \\| `\"document\"`\n\nAttachment categories WhatsApp distinguishes.\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedMediaPresentation.md -->\n# Type Alias: LinkedMediaPresentation\n\n> **LinkedMediaPresentation** = `\"sticker\"` \\| `\"gif\"` \\| `\"voice_note\"`\n\nHow WhatsApp shows an attachment, when not as a plain file of its kind.\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedMutation.md -->\n# Type Alias: LinkedMutation\n\n> **LinkedMutation** = `\"reaction\"` \\| `\"edit\"` \\| `\"delete\"`\n\nDeliberate operations on an existing linked-group message.\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedParticipant.md -->\n# Type Alias: LinkedParticipant\n\n> **LinkedParticipant** = [`LinkedIdentity`](LinkedIdentity.md) & \\{ `admin`: `boolean`; \\}\n\nCurrent remote participant; Macro access is a separate grant.\n\n## Type Declaration\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `admin` | `boolean` | Group admin; only admins post in announcement groups. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedReplyBlock.md -->\n# Type Alias: LinkedReplyBlock\n\n> **LinkedReplyBlock** = `\"sending_disabled\"` \\| `\"no_account\"` \\| `\"disconnected\"` \\| `\"not_observing\"` \\| `\"not_allowed_in_group\"` \\| `\"group_unavailable\"`\n\nWhy the viewer cannot send now.\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedReplyContent.md -->\n# Type Alias: LinkedReplyContent\n\n> **LinkedReplyContent** = \\{ `mentions?`: `string`[]; `text`: `string`; `type`: `\"text\"`; \\} \\| \\{ `caption?`: `string` \\| `null`; `type`: `\"media\"`; `upload_id`: `string`; \\} \\| \\{ `message_id`: `string`; `operation`: [`LinkedMutation`](LinkedMutation.md); `text?`: `string` \\| `null`; `type`: `\"mutation\"`; \\}\n\nContent of a deliberate send.\n\n## Union Members\n\n### Type Literal\n\n\\{ `mentions?`: `string`[]; `text`: `string`; `type`: `\"text\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `mentions?` | `string`[] | Group participants the text @-mentions, by their WhatsApp id (`jid` of a roster participant); the text must contain `@<digits before the @ of the id>` for each. |\n| `text` | `string` | UTF-8 text, at most [`TEXT_LIMIT_BYTES`] bytes. |\n| `type` | `\"text\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `caption?`: `string` \\| `null`; `type`: `\"media\"`; `upload_id`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `caption?` | `string` \\| `null` | Optional caption; audio has none. |\n| `type` | `\"media\"` | - |\n| `upload_id` | `string` | The staged upload, which becomes the message's private document. |\n\n***\n\n### Type Literal\n\n\\{ `message_id`: `string`; `operation`: [`LinkedMutation`](LinkedMutation.md); `text?`: `string` \\| `null`; `type`: `\"mutation\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `message_id` | `string` | Existing group message, resolved to its WhatsApp source by the server. |\n| `operation` | [`LinkedMutation`](LinkedMutation.md) | Explicit operation. |\n| `text?` | `string` \\| `null` | Replacement text or emoji; absent for delete, empty to remove a reaction. |\n| `type` | `\"mutation\"` | - |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedSendProgress.md -->\n# Type Alias: LinkedSendProgress\n\n> **LinkedSendProgress** = \\{ `created_at`: `string`; `error_code?`: `string` \\| `null`; `group_id`: `string`; `id`: `string`; `message_id?`: `string` \\| `null`; `payload`: [`LinkedSendReply`](LinkedSendReply.md); `state`: [`LinkedDeliveryState`](LinkedDeliveryState.md); `user_id`: `string`; \\}\n\nDurable result of a deliberate send.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | Intent creation time. |\n| <a id=\"property-error_code\"></a> `error_code?` | `string` \\| `null` | Sanitized failure code. |\n| <a id=\"property-group_id\"></a> `group_id` | `string` | Group entity. |\n| <a id=\"property-id\"></a> `id` | `string` | Stable intent id. |\n| <a id=\"property-message_id\"></a> `message_id?` | `string` \\| `null` | Group message, once WhatsApp accepted it. |\n| <a id=\"property-payload\"></a> `payload` | [`LinkedSendReply`](LinkedSendReply.md) | The original request, so a failed draft can be recovered. |\n| <a id=\"property-state\"></a> `state` | [`LinkedDeliveryState`](LinkedDeliveryState.md) | Current state. |\n| <a id=\"property-user_id\"></a> `user_id` | `string` | Person who submitted it. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedSendReply.md -->\n# Type Alias: LinkedSendReply\n\n> **LinkedSendReply** = \\{ `idempotency_key`: `string`; `message`: [`LinkedReplyContent`](LinkedReplyContent.md); `reply_to?`: `string` \\| `null`; \\}\n\nExplicit send action from a person. Only deliberate sends reach WhatsApp.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-idempotency_key\"></a> `idempotency_key` | `string` | Stable client intent key. A changed payload with this key is a conflict. |\n| <a id=\"property-message\"></a> `message` | [`LinkedReplyContent`](LinkedReplyContent.md) | Content. |\n| <a id=\"property-reply_to\"></a> `reply_to?` | `string` \\| `null` | Group message being quoted, within this group. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedSharedGroupReference.md -->\n# Type Alias: LinkedSharedGroupReference\n\n> **LinkedSharedGroupReference** = \\{ `id`: `string`; `name`: `string`; `ownerId`: `string`; \\}\n\nAnother person's group entity the caller can view.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `string` | Group entity id. |\n| <a id=\"property-name\"></a> `name` | `string` | Display name, following WhatsApp. |\n| <a id=\"property-ownerid\"></a> `ownerId` | `string` | Macro user who added the group and shared it. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedUploadedAttachment.md -->\n# Type Alias: LinkedUploadedAttachment\n\n> **LinkedUploadedAttachment** = \\{ `filename`: `string`; `kind`: [`LinkedMediaKind`](LinkedMediaKind.md); `upload_id`: `string`; \\}\n\nA staged attachment, sent only by a later deliberate send.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-filename\"></a> `filename` | `string` | Display filename. |\n| <a id=\"property-kind\"></a> `kind` | [`LinkedMediaKind`](LinkedMediaKind.md) | Category. |\n| <a id=\"property-upload_id\"></a> `upload_id` | `string` | Use as `upload_id` in a media send; also the future document id. |\n\n\n<!-- generated/storage/types.gen/type-aliases/Message.md -->\n# Type Alias: Message\n\n> **Message** = \\{ `attachments`: [`MessageAttachment`](MessageAttachment.md)[]; `bot_profile?`: `null` \\| [`BotSenderProfile`](BotSenderProfile.md); `content`: `string`; `created_at`: `string`; `deleted_at?`: `string` \\| `null`; `edited_at?`: `string` \\| `null`; `guest_name?`: `string` \\| `null`; `id`: `string`; `imported_author?`: `null` \\| [`ImportedAuthor`](ImportedAuthor.md); `mentions`: [`SimpleMention`](SimpleMention.md)[]; `parent`: [`MessageParent`](MessageParent.md); `reactions`: [`CountedReaction`](CountedReaction.md)[]; `sender_id`: `string`; `thread_id?`: `string` \\| `null`; `triggered_by?`: `string` \\| `null`; `updated_at`: `string`; \\}\n\nShared message representation for channel timelines and entity discussions.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attachments\"></a> `attachments` | [`MessageAttachment`](MessageAttachment.md)[] | Attached entities. |\n| <a id=\"property-bot_profile\"></a> `bot_profile?` | `null` \\| [`BotSenderProfile`](BotSenderProfile.md) | - |\n| <a id=\"property-content\"></a> `content` | `string` | Macro Markdown body. |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | Creation time. |\n| <a id=\"property-deleted_at\"></a> `deleted_at?` | `string` \\| `null` | Message tombstone, independent of thread deletion. |\n| <a id=\"property-edited_at\"></a> `edited_at?` | `string` \\| `null` | Last content edit, if any. |\n| <a id=\"property-guest_name\"></a> `guest_name?` | `string` \\| `null` | Display name of a verified call guest, retained after the call ends. |\n| <a id=\"property-id\"></a> `id` | `string` | Message UUID. |\n| <a id=\"property-imported_author\"></a> `imported_author?` | `null` \\| [`ImportedAuthor`](ImportedAuthor.md) | - |\n| <a id=\"property-mentions\"></a> `mentions` | [`SimpleMention`](SimpleMention.md)[] | Tracked mentions, retained when a caller changes attachments only. |\n| <a id=\"property-parent\"></a> `parent` | [`MessageParent`](MessageParent.md) | Entity that owns this conversation. |\n| <a id=\"property-reactions\"></a> `reactions` | [`CountedReaction`](CountedReaction.md)[] | Aggregated reactions. |\n| <a id=\"property-sender_id\"></a> `sender_id` | `string` | Authenticated actor or owner of imported content. |\n| <a id=\"property-thread_id\"></a> `thread_id?` | `string` \\| `null` | Root message UUID for replies; absent on roots. |\n| <a id=\"property-triggered_by\"></a> `triggered_by?` | `string` \\| `null` | User who triggered a bot-authored message. |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` | Last persisted update. |\n\n\n<!-- generated/storage/types.gen/type-aliases/MessageAttachment.md -->\n# Type Alias: MessageAttachment\n\n> **MessageAttachment** = \\{ `created_at`: `string`; `entity_id`: `string`; `entity_type`: `string`; `height?`: `number` \\| `null`; `id`: `string`; `width?`: `number` \\| `null`; \\}\n\nAn entity attached to a message.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | When the attachment was added. |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` | Attached entity identifier. |\n| <a id=\"property-entity_type\"></a> `entity_type` | `string` | Attached entity type. |\n| <a id=\"property-height\"></a> `height?` | `number` \\| `null` | Optional media height. |\n| <a id=\"property-id\"></a> `id` | `string` | Attachment UUID. |\n| <a id=\"property-width\"></a> `width?` | `number` \\| `null` | Optional media width. |\n\n\n<!-- generated/storage/types.gen/type-aliases/MessageCursor.md -->\n# Type Alias: MessageCursor\n\n> **MessageCursor** = \\{ `created_at`: `string`; `id`: `string`; \\}\n\nCursor for a chronological parent timeline.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | Last message creation time or activity occurrence time. |\n| <a id=\"property-id\"></a> `id` | `string` | Last entry UUID, used to break timestamp ties across both sources. |\n\n\n<!-- generated/storage/types.gen/type-aliases/MessageParent.md -->\n# Type Alias: MessageParent\n\n> **MessageParent** = \\{ `id`: `string`; `type`: `\"channel\"`; \\} \\| \\{ `id`: [`DocumentId`](DocumentId.md); `type`: `\"document\"`; \\} \\| \\{ `id`: `string`; `type`: `\"initiative\"`; \\} \\| \\{ `id`: `string`; `type`: `\"crm_company\"`; \\} \\| \\{ `id`: `string`; `type`: `\"crm_contact\"`; \\} \\| \\{ `id`: `string`; `type`: `\"call\"`; \\}\n\nThe entity whose permissions and lifecycle govern a message.\n\n## Union Members\n\n### Type Literal\n\n\\{ `id`: `string`; `type`: `\"channel\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | A channel, including direct messages. |\n| `type` | `\"channel\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: [`DocumentId`](DocumentId.md); `type`: `\"document\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | [`DocumentId`](DocumentId.md) | A document, including tasks and PDFs. |\n| `type` | `\"document\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: `string`; `type`: `\"initiative\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | An initiative, presented as a project in the application. |\n| `type` | `\"initiative\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: `string`; `type`: `\"crm_company\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | A CRM company. |\n| `type` | `\"crm_company\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: `string`; `type`: `\"crm_contact\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | A CRM contact. |\n| `type` | `\"crm_contact\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: `string`; `type`: `\"call\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | A video call and its persistent chat thread. |\n| `type` | `\"call\"` | - |\n\n\n<!-- generated/storage/types.gen/type-aliases/ParticipantRole.md -->\n# Type Alias: ParticipantRole\n\n> **ParticipantRole** = `\"owner\"` \\| `\"admin\"` \\| `\"member\"`\n\nThe role a user has within a channel.\n\n\n<!-- generated/storage/types.gen/type-aliases/SharePermissionV2.md -->\n# Type Alias: SharePermissionV2\n\n> **SharePermissionV2** = \\{ `channelSharePermissions?`: [`ChannelSharePermission`](ChannelSharePermission.md)[] \\| `null`; `id`: `string`; `linkShare?`: `null` \\| [`LinkShare`](LinkShare.md); `linkShareAccessLevel?`: `null` \\| [`AccessLevel`](AccessLevel.md); `owner`: `string`; `teamShareAccessLevel?`: `null` \\| [`AccessLevel`](AccessLevel.md); \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-channelsharepermissions\"></a> `channelSharePermissions?` | [`ChannelSharePermission`](ChannelSharePermission.md)[] \\| `null` | The channel share permissions for the item |\n| <a id=\"property-id\"></a> `id` | `string` | The share permission id |\n| <a id=\"property-linkshare\"></a> `linkShare?` | `null` \\| [`LinkShare`](LinkShare.md) | - |\n| <a id=\"property-linkshareaccesslevel\"></a> `linkShareAccessLevel?` | `null` \\| [`AccessLevel`](AccessLevel.md) | - |\n| <a id=\"property-owner\"></a> `owner` | `string` | The owner of the item |\n| <a id=\"property-teamshareaccesslevel\"></a> `teamShareAccessLevel?` | `null` \\| [`AccessLevel`](AccessLevel.md) | - |\n\n\n<!-- generated/storage/types.gen/type-aliases/SimpleMention.md -->\n# Type Alias: SimpleMention\n\n> **SimpleMention** = \\{ `entity_id`: `string`; `entity_type`: `string`; \\}\n\nA mention tracked in a message body.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` | Mentioned entity identifier. |\n| <a id=\"property-entity_type\"></a> `entity_type` | `string` | Mentioned entity type. |\n\n\n<!-- generated/storage/types.gen/type-aliases/SmartTagChannelMatch.md -->\n# Type Alias: SmartTagChannelMatch\n\n> **SmartTagChannelMatch** = \\{ `id`: `string`; `name`: `string`; \\}\n\nA channel visible to the caller that matches a smart tag rule.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `string` | Channel id. |\n| <a id=\"property-name\"></a> `name` | `string` | Channel display name. |\n\n\n<!-- generated/storage/types.gen/type-aliases/SmartTagPreview.md -->\n# Type Alias: SmartTagPreview\n\n> **SmartTagPreview** = \\{ `channels`: [`SmartTagChannelMatch`](SmartTagChannelMatch.md)[]; `totalCount`: `number`; \\}\n\nA bounded preview and the total number of visible channels matching a rule.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-channels\"></a> `channels` | [`SmartTagChannelMatch`](SmartTagChannelMatch.md)[] | First matches, in alphabetical order. |\n| <a id=\"property-totalcount\"></a> `totalCount` | `number` | Number of matching channels the caller participates in, including overflow. |\n\n\n<!-- generated/storage/types.gen/type-aliases/TeamRole.md -->\n# Type Alias: TeamRole\n\n> **TeamRole** = `\"member\"` \\| `\"admin\"` \\| `\"owner\"`\n\nThe role a user has within a team.\n\nOrdered least to most privileged so comparisons reflect access strength.\n\n\n<!-- generated/storage/types.gen/type-aliases/UpdateChannelSharePermission.md -->\n# Type Alias: UpdateChannelSharePermission\n\n> **UpdateChannelSharePermission** = \\{ `accessLevel?`: `null` \\| [`AccessLevel`](AccessLevel.md); `channelId`: `string`; `operation`: [`UpdateOperation`](UpdateOperation.md); \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-accesslevel\"></a> `accessLevel?` | `null` \\| [`AccessLevel`](AccessLevel.md) | - |\n| <a id=\"property-channelid\"></a> `channelId` | `string` | The channel id |\n| <a id=\"property-operation\"></a> `operation` | [`UpdateOperation`](UpdateOperation.md) | The type of operation to be performed on the chanel share permission You can add, remove or replace and existing permission |\n\n\n<!-- generated/storage/types.gen/type-aliases/UpdateOperation.md -->\n# Type Alias: UpdateOperation\n\n> **UpdateOperation** = `\"add\"` \\| `\"remove\"` \\| `\"replace\"`\n\n\n<!-- generated/storage/types.gen/type-aliases/UpdateSharePermissionRequestV2.md -->\n# Type Alias: UpdateSharePermissionRequestV2\n\n> **UpdateSharePermissionRequestV2** = \\{ `channelSharePermissions?`: [`UpdateChannelSharePermission`](UpdateChannelSharePermission.md)[] \\| `null`; `linkShare?`: `null` \\| [`LinkShare`](LinkShare.md); `linkShareAccessLevel?`: `null` \\| [`AccessLevel`](AccessLevel.md); `teamShareAccessLevel?`: `null` \\| [`AccessLevel`](AccessLevel.md); \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-channelsharepermissions\"></a> `channelSharePermissions?` | [`UpdateChannelSharePermission`](UpdateChannelSharePermission.md)[] \\| `null` | Any channel share permissions to be created/updated/removed |\n| <a id=\"property-linkshare\"></a> `linkShare?` | `null` \\| [`LinkShare`](LinkShare.md) | - |\n| <a id=\"property-linkshareaccesslevel\"></a> `linkShareAccessLevel?` | `null` \\| [`AccessLevel`](AccessLevel.md) | - |\n| <a id=\"property-teamshareaccesslevel\"></a> `teamShareAccessLevel?` | `null` \\| [`AccessLevel`](AccessLevel.md) | - |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppCall.md -->\n# Type Alias: WhatsAppCall\n\n> **WhatsAppCall** = \\{ `durationSeconds?`: `number` \\| `null`; `outcome`: [`WhatsAppCallOutcome`](WhatsAppCallOutcome.md); `video`: `boolean`; \\}\n\nA call in the group.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-durationseconds\"></a> `durationSeconds?` | `number` \\| `null` | Length, when it connected. |\n| <a id=\"property-outcome\"></a> `outcome` | [`WhatsAppCallOutcome`](WhatsAppCallOutcome.md) | How it went for the account that saw it. |\n| <a id=\"property-video\"></a> `video` | `boolean` | Video rather than voice. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppCallOutcome.md -->\n# Type Alias: WhatsAppCallOutcome\n\n> **WhatsAppCallOutcome** = `\"answered\"` \\| `\"missed\"` \\| `\"rejected\"` \\| `\"other\"`\n\nHow a call went.\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppContactCard.md -->\n# Type Alias: WhatsAppContactCard\n\n> **WhatsAppContactCard** = \\{ `name`: `string`; `phones`: `string`[]; \\}\n\nOne contact card, from its vCard.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-name\"></a> `name` | `string` | Display name. |\n| <a id=\"property-phones\"></a> `phones` | `string`[] | Phone numbers as written on the card. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppContacts.md -->\n# Type Alias: WhatsAppContacts\n\n> **WhatsAppContacts** = \\{ `contacts`: [`WhatsAppContactCard`](WhatsAppContactCard.md)[]; \\}\n\nContact cards.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-contacts\"></a> `contacts` | [`WhatsAppContactCard`](WhatsAppContactCard.md)[] | The cards, in order. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppEvent.md -->\n# Type Alias: WhatsAppEvent\n\n> **WhatsAppEvent** = \\{ `canceled?`: `boolean`; `description?`: `string` \\| `null`; `endAt?`: `string` \\| `null`; `joinLink?`: `string` \\| `null`; `location?`: `string` \\| `null`; `name`: `string`; `startAt?`: `string` \\| `null`; \\}\n\nA WhatsApp event.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-canceled\"></a> `canceled?` | `boolean` | Canceled by its organizer. |\n| <a id=\"property-description\"></a> `description?` | `string` \\| `null` | Description. |\n| <a id=\"property-endat\"></a> `endAt?` | `string` \\| `null` | End. |\n| <a id=\"property-joinlink\"></a> `joinLink?` | `string` \\| `null` | Call link for an online event. |\n| <a id=\"property-location\"></a> `location?` | `string` \\| `null` | Place name or address. |\n| <a id=\"property-name\"></a> `name` | `string` | Title. |\n| <a id=\"property-startat\"></a> `startAt?` | `string` \\| `null` | Start. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppGroupDetail.md -->\n# Type Alias: WhatsAppGroupDetail\n\n> **WhatsAppGroupDetail** = [`WhatsAppGroupSummary`](WhatsAppGroupSummary.md) & \\{ `access_level`: [`AccessLevel`](AccessLevel.md); `community?`: `null` \\| [`LinkedCommunityReference`](LinkedCommunityReference.md); `disappearing_seconds?`: `number` \\| `null`; `limits`: [`LinkedCapabilities`](LinkedCapabilities.md); `roster?`: `null` \\| [`LinkedGroupInfo`](LinkedGroupInfo.md); `sending_identity?`: `string` \\| `null`; `share_permission`: [`SharePermissionV2`](SharePermissionV2.md); \\}\n\nFull group detail and current viewer capabilities.\n\n## Type Declaration\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `access_level` | [`AccessLevel`](AccessLevel.md) | Caller's effective permission. |\n| `community?` | `null` \\| [`LinkedCommunityReference`](LinkedCommunityReference.md) | - |\n| `disappearing_seconds?` | `number` \\| `null` | WhatsApp's disappearing-messages timer in seconds while it is on; Macro keeps the messages anyway. `null` when off or unknown. |\n| `limits` | [`LinkedCapabilities`](LinkedCapabilities.md) | Size and mutation limits. |\n| `roster?` | `null` \\| [`LinkedGroupInfo`](LinkedGroupInfo.md) | - |\n| `sending_identity?` | `string` \\| `null` | Caller's own phone identity, never another account's identity. |\n| `share_permission` | [`SharePermissionV2`](SharePermissionV2.md) | Owner-controlled standard sharing configuration. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppGroupMessage.md -->\n# Type Alias: WhatsAppGroupMessage\n\n> **WhatsAppGroupMessage** = \\{ `attachments`: [`LinkedAttachment`](LinkedAttachment.md)[]; `body`: `string`; `deleted`: `boolean`; `delivery_state?`: `null` \\| [`LinkedDeliveryState`](LinkedDeliveryState.md); `edited_at?`: `string` \\| `null`; `forwarded`: `boolean`; `id`: `string`; `kind`: [`WhatsAppMessageKind`](WhatsAppMessageKind.md); `mentions`: [`WhatsAppMention`](WhatsAppMention.md)[]; `reactions`: [`WhatsAppGroupReaction`](WhatsAppGroupReaction.md)[]; `received_at`: `string`; `reply_to?`: `string` \\| `null`; `rich?`: `null` \\| [`WhatsAppRichContent`](WhatsAppRichContent.md); `sender`: [`WhatsAppGroupSender`](WhatsAppGroupSender.md); `sent_at`: `string`; `view_once`: `boolean`; \\}\n\nOne message in an adopted group.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attachments\"></a> `attachments` | [`LinkedAttachment`](LinkedAttachment.md)[] | Imported or pending attachments. |\n| <a id=\"property-body\"></a> `body` | `string` | Plain WhatsApp text. |\n| <a id=\"property-deleted\"></a> `deleted` | `boolean` | Deleted for everyone. |\n| <a id=\"property-delivery_state\"></a> `delivery_state?` | `null` \\| [`LinkedDeliveryState`](LinkedDeliveryState.md) | - |\n| <a id=\"property-edited_at\"></a> `edited_at?` | `string` \\| `null` | Last edit timestamp. |\n| <a id=\"property-forwarded\"></a> `forwarded` | `boolean` | Forwarded from another chat. |\n| <a id=\"property-id\"></a> `id` | `string` | Stable message id. |\n| <a id=\"property-kind\"></a> `kind` | [`WhatsAppMessageKind`](WhatsAppMessageKind.md) | A message, or a system line. |\n| <a id=\"property-mentions\"></a> `mentions` | [`WhatsAppMention`](WhatsAppMention.md)[] | People the body @-mentions. |\n| <a id=\"property-reactions\"></a> `reactions` | [`WhatsAppGroupReaction`](WhatsAppGroupReaction.md)[] | Reactions grouped by emoji. |\n| <a id=\"property-received_at\"></a> `received_at` | `string` | Timestamp first received by Macro. |\n| <a id=\"property-reply_to\"></a> `reply_to?` | `string` \\| `null` | Message quoted by this one. |\n| <a id=\"property-rich\"></a> `rich?` | `null` \\| [`WhatsAppRichContent`](WhatsAppRichContent.md) | - |\n| <a id=\"property-sender\"></a> `sender` | [`WhatsAppGroupSender`](WhatsAppGroupSender.md) | Sender. |\n| <a id=\"property-sent_at\"></a> `sent_at` | `string` | Timestamp assigned by WhatsApp. |\n| <a id=\"property-view_once\"></a> `view_once` | `boolean` | Sent as view-once in WhatsApp; Macro shows it like any media. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppGroupReaction.md -->\n# Type Alias: WhatsAppGroupReaction\n\n> **WhatsAppGroupReaction** = \\{ `count`: `number`; `emoji`: `string`; `mine`: `boolean`; \\}\n\nGrouped reactions.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-count\"></a> `count` | `number` | Number of reacting people. |\n| <a id=\"property-emoji\"></a> `emoji` | `string` | Emoji. |\n| <a id=\"property-mine\"></a> `mine` | `boolean` | Caller has this reaction. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppGroupSender.md -->\n# Type Alias: WhatsAppGroupSender\n\n> **WhatsAppGroupSender** = \\{ `name`: `string`; `person_id`: `string`; `user_id?`: `string` \\| `null`; \\}\n\nMessage sender from protocol-verified identity evidence.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-name\"></a> `name` | `string` | Display name, never authentication evidence. |\n| <a id=\"property-person_id\"></a> `person_id` | `string` | External person identity. |\n| <a id=\"property-user_id\"></a> `user_id?` | `string` \\| `null` | Verified Macro user association, if present. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppGroupSummary.md -->\n# Type Alias: WhatsAppGroupSummary\n\n> **WhatsAppGroupSummary** = \\{ `backfill?`: `null` \\| [`LinkedBackfill`](LinkedBackfill.md); `can_send`: `boolean`; `id`: `string`; `kind`: [`LinkedChatKind`](LinkedChatKind.md); `last_message_at?`: `string` \\| `null`; `name`: `string`; `send_reason?`: `null` \\| [`LinkedReplyBlock`](LinkedReplyBlock.md); `unread_count`: `number`; `user_id`: `string`; \\}\n\nAdopted group visible through ordinary entity sharing.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-backfill\"></a> `backfill?` | `null` \\| [`LinkedBackfill`](LinkedBackfill.md) | - |\n| <a id=\"property-can_send\"></a> `can_send` | `boolean` | Caller may currently send from their own account. |\n| <a id=\"property-id\"></a> `id` | `string` | Entity identifier. |\n| <a id=\"property-kind\"></a> `kind` | [`LinkedChatKind`](LinkedChatKind.md) | A group, or a direct chat with one person (only its owner sends). |\n| <a id=\"property-last_message_at\"></a> `last_message_at?` | `string` \\| `null` | Latest message timestamp. |\n| <a id=\"property-name\"></a> `name` | `string` | Display name: the group's, or a direct chat's other person. |\n| <a id=\"property-send_reason\"></a> `send_reason?` | `null` \\| [`LinkedReplyBlock`](LinkedReplyBlock.md) | - |\n| <a id=\"property-unread_count\"></a> `unread_count` | `number` | Unread live messages for this viewer. |\n| <a id=\"property-user_id\"></a> `user_id` | `string` | Actual entity owner. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppLocation.md -->\n# Type Alias: WhatsAppLocation\n\n> **WhatsAppLocation** = \\{ `address?`: `string` \\| `null`; `comment?`: `string` \\| `null`; `latitude`: `number`; `live?`: `boolean`; `longitude`: `number`; `name?`: `string` \\| `null`; `url?`: `string` \\| `null`; \\}\n\nA shared place.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-address\"></a> `address?` | `string` \\| `null` | Street address. |\n| <a id=\"property-comment\"></a> `comment?` | `string` \\| `null` | Caption or comment. |\n| <a id=\"property-latitude\"></a> `latitude` | `number` | Degrees. |\n| <a id=\"property-live\"></a> `live?` | `boolean` | Shared as a live location (this is where it started). |\n| <a id=\"property-longitude\"></a> `longitude` | `number` | Degrees. |\n| <a id=\"property-name\"></a> `name?` | `string` \\| `null` | Place name. |\n| <a id=\"property-url\"></a> `url?` | `string` \\| `null` | Link the sender attached. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppMention.md -->\n# Type Alias: WhatsAppMention\n\n> **WhatsAppMention** = [`WhatsAppPersonRef`](WhatsAppPersonRef.md) & \\{ `token`: `string`; \\}\n\nAn @-mention in a message body.\n\n## Type Declaration\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `token` | `string` | What follows the `@` in the body (the digits of the person's WhatsApp id); replace `@<token>` with the name. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppMessageKind.md -->\n# Type Alias: WhatsAppMessageKind\n\n> **WhatsAppMessageKind** = `\"message\"` \\| `\"system\"`\n\nWhat a timeline entry is.\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppPersonRef.md -->\n# Type Alias: WhatsAppPersonRef\n\n> **WhatsAppPersonRef** = \\{ `name`: `string`; `userId?`: `string` \\| `null`; \\}\n\nA person named in a message: a Macro user when verified, else their\nWhatsApp name, else their phone number.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-name\"></a> `name` | `string` | Display name, never authentication evidence. |\n| <a id=\"property-userid\"></a> `userId?` | `string` \\| `null` | Verified Macro user, if any. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppPoll.md -->\n# Type Alias: WhatsAppPoll\n\n> **WhatsAppPoll** = \\{ `options`: [`WhatsAppPollOption`](WhatsAppPollOption.md)[]; `question`: `string`; `selectableCount`: `number`; `voters`: `number`; \\}\n\nA poll, read-only in Macro.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-options\"></a> `options` | [`WhatsAppPollOption`](WhatsAppPollOption.md)[] | Options in order, with tallies. |\n| <a id=\"property-question\"></a> `question` | `string` | The question. |\n| <a id=\"property-selectablecount\"></a> `selectableCount` | `number` | How many options one person may choose; 0 means any number. |\n| <a id=\"property-voters\"></a> `voters` | `number` | People who voted for anything. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppPollOption.md -->\n# Type Alias: WhatsAppPollOption\n\n> **WhatsAppPollOption** = \\{ `mine`: `boolean`; `name`: `string`; `voters`: [`WhatsAppPersonRef`](WhatsAppPersonRef.md)[]; `votes`: `number`; \\}\n\nOne option of a poll with its votes.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-mine\"></a> `mine` | `boolean` | The caller chose it. |\n| <a id=\"property-name\"></a> `name` | `string` | Option text. |\n| <a id=\"property-voters\"></a> `voters` | [`WhatsAppPersonRef`](WhatsAppPersonRef.md)[] | Who chose it. |\n| <a id=\"property-votes\"></a> `votes` | `number` | People who chose it. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppRichContent.md -->\n# Type Alias: WhatsAppRichContent\n\n> **WhatsAppRichContent** = [`WhatsAppPoll`](WhatsAppPoll.md) & \\{ `type`: `\"poll\"`; \\} \\| [`WhatsAppLocation`](WhatsAppLocation.md) & \\{ `type`: `\"location\"`; \\} \\| [`WhatsAppContacts`](WhatsAppContacts.md) & \\{ `type`: `\"contacts\"`; \\} \\| [`WhatsAppEvent`](WhatsAppEvent.md) & \\{ `type`: `\"event\"`; \\} \\| [`WhatsAppSystemLine`](WhatsAppSystemLine.md) & \\{ `type`: `\"system\"`; \\}\n\nStructured content of a message besides its body.\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppSystemAction.md -->\n# Type Alias: WhatsAppSystemAction\n\n> **WhatsAppSystemAction** = `\"group_created\"` \\| `\"participants_added\"` \\| `\"participants_removed\"` \\| `\"participants_left\"` \\| `\"participants_joined\"` \\| `\"participants_promoted\"` \\| `\"participants_demoted\"` \\| `\"subject_changed\"` \\| `\"icon_changed\"` \\| `\"description_changed\"` \\| `\"disappearing_changed\"` \\| `\"message_pinned\"` \\| `\"message_unpinned\"` \\| `\"call\"`\n\nKinds of system lines.\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppSystemLine.md -->\n# Type Alias: WhatsAppSystemLine\n\n> **WhatsAppSystemLine** = \\{ `action`: [`WhatsAppSystemAction`](WhatsAppSystemAction.md); `actor?`: `null` \\| [`WhatsAppPersonRef`](WhatsAppPersonRef.md); `call?`: `null` \\| [`WhatsAppCall`](WhatsAppCall.md); `participants`: [`WhatsAppPersonRef`](WhatsAppPersonRef.md)[]; `value?`: `string` \\| `null`; \\}\n\nSomething that happened in the group.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-action\"></a> `action` | [`WhatsAppSystemAction`](WhatsAppSystemAction.md) | What happened. |\n| <a id=\"property-actor\"></a> `actor?` | `null` \\| [`WhatsAppPersonRef`](WhatsAppPersonRef.md) | - |\n| <a id=\"property-call\"></a> `call?` | `null` \\| [`WhatsAppCall`](WhatsAppCall.md) | - |\n| <a id=\"property-participants\"></a> `participants` | [`WhatsAppPersonRef`](WhatsAppPersonRef.md)[] | Who it happened to (added, removed, promoted, …). |\n| <a id=\"property-value\"></a> `value?` | `string` \\| `null` | New subject or description; disappearing-messages timer in seconds (`\"0\"` is off). |\n\n\n<!-- src/entities/channels/activity/classes/ChannelActivity.md -->\n# Class: ChannelActivity\n\nA user's channel activity marker.\n\n## Constructors\n\n### Constructor\n\n> **new ChannelActivity**(`client`, `channel`, `record`): `ChannelActivity`\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `client` | `MacroClient` | - |\n| `channel` | [`Channel`](../../channel/classes/Channel.md) | Related channel. |\n| `record` | [`ApiActivity`](../../../../../generated/storage/types.gen/type-aliases/ApiActivity.md) | - |\n\n#### Returns\n\n`ChannelActivity`\n\n## Properties\n\n| Property | Modifier | Type | Description |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-channel\"></a> `channel` | `readonly` | [`Channel`](../../channel/classes/Channel.md) | Related channel. |\n\n## Accessors\n\n### id\n\n#### Get Signature\n\n> **get** **id**(): `string`\n\nActivity identity.\n\n##### Returns\n\n`string`\n\n## Methods\n\n### createdAt()\n\n> **createdAt**(): `string`\n\nCreation time.\n\n#### Returns\n\n`string`\n\n***\n\n### recordInteraction()\n\n> **recordInteraction**(`type`): `Promise`\\<`ChannelActivity`\\>\n\nRecord a view or interaction in this channel.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `type` | [`ActivityType`](../../../../../generated/storage/types.gen/type-aliases/ActivityType.md) |\n\n#### Returns\n\n`Promise`\\<`ChannelActivity`\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): [`ApiActivity`](../../../../../generated/storage/types.gen/type-aliases/ApiActivity.md)\n\nSerialize activity without credentials.\n\n#### Returns\n\n[`ApiActivity`](../../../../../generated/storage/types.gen/type-aliases/ApiActivity.md)\n\n***\n\n### user()\n\n> **user**(): [`User`](../../../users/user/classes/User.md)\n\nUser who interacted.\n\n#### Returns\n\n[`User`](../../../users/user/classes/User.md)\n\n\n<!-- src/entities/channels/channel/classes/Channel.md -->\n# Class: Channel\n\nA channel.\n\n## Extends\n\n- [`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md)\\<`ChannelDetail`\\>\n\n## Properties\n\n| Property | Modifier | Type | Default value | Description | Overrides | Inherited from |\n| ------ | ------ | ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-entitytype\"></a> `entityType` | `readonly` | `\"channel\"` | `'channel'` | Favorites identify channels as `channel`. | [`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`entityType`](../../../entity/classes/PropertiedEntity.md#property-entitytype) | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | `undefined` | - | - | [`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`id`](../../../entity/classes/PropertiedEntity.md#property-id) |\n| <a id=\"property-name\"></a> `name` | `readonly` | () => `Promise`\\<`string`\\> | `...` | The channel's display name, resolved from the viewer's perspective. | - | - |\n| <a id=\"property-type\"></a> `type` | `readonly` | () => `Promise`\\<[`ChannelType`](../../../../../generated/storage/types.gen/type-aliases/ChannelType.md)\\> | `...` | The channel's type (e.g. `public`, `dm`, `private`). | - | - |\n| <a id=\"property-search\"></a> `search` | `static` | (`client`, `query`, `searchOpts?`) => `AsyncGenerator`\\<`Channel`\\> | `...` | Search channels by content, most relevant first, auto-paginated. | - | - |\n\n## Methods\n\n### addParticipants()\n\n> **addParticipants**(`users`): `Promise`\\<`void`\\>\n\nAdd users to the channel.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `users` | [`User`](../../../users/user/classes/User.md)[] |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### agentConversations()\n\n> **agentConversations**(): `Promise`\\<[`AgentConversation`](../../../agent-sessions/conversation/classes/AgentConversation.md)[]\\>\n\nConversations maintained by agents in this channel.\n\n#### Returns\n\n`Promise`\\<[`AgentConversation`](../../../agent-sessions/conversation/classes/AgentConversation.md)[]\\>\n\n***\n\n### attachments()\n\n> **attachments**(`opts?`): `AsyncGenerator`\\<[`ApiChannelAttachment`](../../../../../generated/storage/types.gen/type-aliases/ApiChannelAttachment.md)\\>\n\nThe attachments posted in this channel, auto-paginated.\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `opts?` | \\{ `pageSize?`: `number`; `type?`: `string`; \\} | - |\n| `opts.pageSize?` | `number` | - |\n| `opts.type?` | `string` | Filter by type: `static` for images/videos, `dss` for documents. |\n\n#### Returns\n\n`AsyncGenerator`\\<[`ApiChannelAttachment`](../../../../../generated/storage/types.gen/type-aliases/ApiChannelAttachment.md)\\>\n\n***\n\n### delete()\n\n> **delete**(): `Promise`\\<`void`\\>\n\nDelete the channel. This is not reversible.\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### deleteProperty()\n\n> **deleteProperty**(`assignment`): `Promise`\\<`void`\\>\n\nRemove a property from this entity, given its [properties](#properties) entry.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `assignment` | [`EntityPropertyWithDefinition`](../../../../../generated/properties/types.gen/type-aliases/EntityPropertyWithDefinition.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`deleteProperty`](../../../entity/classes/PropertiedEntity.md#deleteproperty)\n\n***\n\n### favorite()\n\n> **favorite**(): `Promise`\\<`Channel`\\>\n\nAdd this entity to the user's favorites. Returns this handle for chaining.\nPlain unwrap: favoriting alters the user's favorites collection, not this\nentity's own detail, so there's nothing cached to invalidate.\n\n#### Returns\n\n`Promise`\\<`Channel`\\>\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`favorite`](../../../entity/classes/PropertiedEntity.md#favorite)\n\n***\n\n### join()\n\n> **join**(): `Promise`\\<`void`\\>\n\nJoin the channel as the current user.\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### joinCode()\n\n> **joinCode**(): `Promise`\\<`string`\\>\n\nA reusable code that lets a user join this channel.\n\n#### Returns\n\n`Promise`\\<`string`\\>\n\n***\n\n### leave()\n\n> **leave**(): `Promise`\\<`void`\\>\n\nLeave the channel as the current user.\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### message()\n\n> **message**(`id`): [`Message`](../../message/classes/Message.md)\n\nA handle to a message in this channel by id.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n[`Message`](../../message/classes/Message.md)\n\n***\n\n### messages()\n\n> **messages**(`opts?`): `AsyncGenerator`\\<[`Message`](../../message/classes/Message.md)\\>\n\nRoot messages in this channel, most recent first, auto-paginated.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts?` | \\{ `pageSize?`: `number`; \\} |\n| `opts.pageSize?` | `number` |\n\n#### Returns\n\n`AsyncGenerator`\\<[`Message`](../../message/classes/Message.md)\\>\n\n***\n\n### messagesAfter()\n\n> **messagesAfter**(`after`, `opts?`): `AsyncGenerator`\\<[`Message`](../../message/classes/Message.md)\\>\n\nRoot messages created or replied to at or after `after`, most recent\nfirst, auto-paginated. Use it to catch up after a disconnect.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `after` | `string` \\| `Date` |\n| `opts?` | \\{ `pageSize?`: `number`; \\} |\n| `opts.pageSize?` | `number` |\n\n#### Returns\n\n`AsyncGenerator`\\<[`Message`](../../message/classes/Message.md)\\>\n\n***\n\n### messageThreadById()\n\n> **messageThreadById**(`id`): [`MessageThread`](../../../messages/thread/classes/MessageThread.md)\n\nA shared message thread scoped to this resource.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n[`MessageThread`](../../../messages/thread/classes/MessageThread.md)\n\n***\n\n### participants()\n\n> **participants**(): `Promise`\\<[`ApiChannelParticipant`](../../../../../generated/storage/types.gen/type-aliases/ApiChannelParticipant.md)[]\\>\n\nThe channel's members, with their roles and join times.\n\n#### Returns\n\n`Promise`\\<[`ApiChannelParticipant`](../../../../../generated/storage/types.gen/type-aliases/ApiChannelParticipant.md)[]\\>\n\n***\n\n### permission()\n\n> **permission**(): `Promise`\\<\\{ `permission`: [`EntityPermission`](../../../../../generated/storage/types.gen/type-aliases/EntityPermission.md); `status`: `\"access\"`; \\} \\| \\{ `status`: `\"no_access\"`; \\}\\>\n\nRead the caller's effective permission on this entity.\n\n#### Returns\n\n`Promise`\\<\\{ `permission`: [`EntityPermission`](../../../../../generated/storage/types.gen/type-aliases/EntityPermission.md); `status`: `\"access\"`; \\} \\| \\{ `status`: `\"no_access\"`; \\}\\>\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`permission`](../../../entity/classes/PropertiedEntity.md#permission)\n\n***\n\n### properties()\n\n> **properties**(`opts?`): `Promise`\\<[`EntityPropertyWithDefinition`](../../../../../generated/properties/types.gen/type-aliases/EntityPropertyWithDefinition.md)[]\\>\n\nThe properties set on this entity, each with its definition, value, and options.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts?` | \\{ `includeMetadata?`: `boolean`; \\} |\n| `opts.includeMetadata?` | `boolean` |\n\n#### Returns\n\n`Promise`\\<[`EntityPropertyWithDefinition`](../../../../../generated/properties/types.gen/type-aliases/EntityPropertyWithDefinition.md)[]\\>\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`properties`](../../../entity/classes/PropertiedEntity.md#properties)\n\n***\n\n### propertyReference()\n\n> **propertyReference**(): [`PropertyTargetReference`](../../../../../generated/properties/types.gen/type-aliases/PropertyTargetReference.md)\n\nThis entity's reference for bulk property operations.\n\n#### Returns\n\n[`PropertyTargetReference`](../../../../../generated/properties/types.gen/type-aliases/PropertyTargetReference.md)\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`propertyReference`](../../../entity/classes/PropertiedEntity.md#propertyreference)\n\n***\n\n### recordActivity()\n\n> **recordActivity**(`type`): `Promise`\\<[`ChannelActivity`](../../activity/classes/ChannelActivity.md)\\>\n\nRecord a view or interaction in this channel.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `type` | [`ActivityType`](../../../../../generated/storage/types.gen/type-aliases/ActivityType.md) |\n\n#### Returns\n\n`Promise`\\<[`ChannelActivity`](../../activity/classes/ChannelActivity.md)\\>\n\n***\n\n### removeParticipants()\n\n> **removeParticipants**(`users`): `Promise`\\<`void`\\>\n\nRemove users from the channel.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `users` | [`User`](../../../users/user/classes/User.md)[] |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### rename()\n\n> **rename**(`name`): `Promise`\\<`void`\\>\n\nRename the channel.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `name` | `string` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### send()\n\n> **send**(`body`, `opts?`): `Promise`\\<[`Message`](../../message/classes/Message.md)\\>\n\nPost a message. Plain text, or a rich body composed with `msg`.\n\nWorks with a channel webhook token as well as a normal one — see\n[postToChannel](../../post/functions/postToChannel.md) for which endpoint that picks and what it costs.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `body` | `string` \\| [`RichMessage`](../../../../mentions/interfaces/RichMessage.md) |\n| `opts?` | \\{ `thread?`: [`Thread`](../../thread/classes/Thread.md); \\} |\n| `opts.thread?` | [`Thread`](../../thread/classes/Thread.md) |\n\n#### Returns\n\n`Promise`\\<[`Message`](../../message/classes/Message.md)\\>\n\n***\n\n### setPicture()\n\n> **setPicture**(`picture?`): `Promise`\\<`void`\\>\n\nSet an uploaded profile picture, or clear it.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `picture?` | [`ChannelPicture`](../../picture/classes/ChannelPicture.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### setProperty()\n\n> **setProperty**(`property`, `value?`): `Promise`\\<`void`\\>\n\nSet a property value on this entity, or attach the property without a\nvalue when `value` is omitted.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `property` | [`PropertyDefinition`](../../../properties/property-definition/classes/PropertyDefinition.md) |\n| `value?` | [`SetPropertyValue`](../../../../../generated/properties/types.gen/type-aliases/SetPropertyValue.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`setProperty`](../../../entity/classes/PropertiedEntity.md#setproperty)\n\n***\n\n### timelinePage()\n\n> **timelinePage**(`selection?`): `Promise`\\<\\{ `entries`: (\\{ `activity`: \\{ `action`: `string`; `actor`: [`User`](../../../users/user/classes/User.md); `actor_id`: `string`; `id`: `string`; `occurred_at`: `string`; `payload?`: `unknown`; \\}; `message?`: `undefined`; `type`: `\"activity\"`; \\} \\| \\{ `activity?`: `undefined`; `message`: [`Message`](../../message/classes/Message.md); `type`: `\"message\"`; \\})[]; `nextCursor`: [`MessageCursor`](../../../../../generated/storage/types.gen/type-aliases/MessageCursor.md) \\| `undefined`; `previousCursor`: [`MessageCursor`](../../../../../generated/storage/types.gen/type-aliases/MessageCursor.md) \\| `undefined`; \\}\\>\n\nA mixed message and activity timeline page.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `selection?` | [`TimelineOptions`](../../../messages/thread/interfaces/TimelineOptions.md)\\<[`Message`](../../message/classes/Message.md)\\> |\n\n#### Returns\n\n`Promise`\\<\\{ `entries`: (\\{ `activity`: \\{ `action`: `string`; `actor`: [`User`](../../../users/user/classes/User.md); `actor_id`: `string`; `id`: `string`; `occurred_at`: `string`; `payload?`: `unknown`; \\}; `message?`: `undefined`; `type`: `\"activity\"`; \\} \\| \\{ `activity?`: `undefined`; `message`: [`Message`](../../message/classes/Message.md); `type`: `\"message\"`; \\})[]; `nextCursor`: [`MessageCursor`](../../../../../generated/storage/types.gen/type-aliases/MessageCursor.md) \\| `undefined`; `previousCursor`: [`MessageCursor`](../../../../../generated/storage/types.gen/type-aliases/MessageCursor.md) \\| `undefined`; \\}\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`ApiChannelDetail`](../../../../../generated/storage/types.gen/type-aliases/ApiChannelDetail.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`ApiChannelDetail`](../../../../../generated/storage/types.gen/type-aliases/ApiChannelDetail.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`ApiChannelDetail`](../../../../../generated/storage/types.gen/type-aliases/ApiChannelDetail.md) |\n| `id` | `string` |\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`toJSON`](../../../entity/classes/PropertiedEntity.md#tojson)\n\n***\n\n### typing()\n\n> **typing**(`action`, `opts?`): `Promise`\\<`void`\\>\n\nBroadcast a typing indicator, optionally scoped to a thread.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `action` | `\"stop\"` \\| `\"start\"` |\n| `opts?` | \\{ `thread?`: [`Thread`](../../thread/classes/Thread.md); \\} |\n| `opts.thread?` | [`Thread`](../../thread/classes/Thread.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### unfavorite()\n\n> **unfavorite**(): `Promise`\\<`Channel`\\>\n\nRemove this entity from the user's favorites. Returns this handle for chaining.\n\n#### Returns\n\n`Promise`\\<`Channel`\\>\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`unfavorite`](../../../entity/classes/PropertiedEntity.md#unfavorite)\n\n***\n\n### updatePropertyOptions()\n\n> **updatePropertyOptions**(`changes`): `Promise`\\<[`BulkUpdateEntityPropertyOptionsResponse`](../../../../../generated/properties/types.gen/type-aliases/BulkUpdateEntityPropertyOptionsResponse.md)\\>\n\nApply multi-select option deltas atomically across this entity's properties.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `changes` | [`PropertyOptionDelta`](../../../entity/interfaces/PropertyOptionDelta.md)[] |\n\n#### Returns\n\n`Promise`\\<[`BulkUpdateEntityPropertyOptionsResponse`](../../../../../generated/properties/types.gen/type-aliases/BulkUpdateEntityPropertyOptionsResponse.md)\\>\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`updatePropertyOptions`](../../../entity/classes/PropertiedEntity.md#updatepropertyoptions)\n\n***\n\n### webUrl()\n\n> **webUrl**(): `string`\n\nThe channel's URL in the Macro web app.\n\n#### Returns\n\n`string`\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `id`): `Channel`\n\nA handle to a channel by id. Details load on first access.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `id` | `string` |\n\n#### Returns\n\n`Channel`\n\n***\n\n### create()\n\n> `static` **create**(`client`, `opts`): `Promise`\\<`Channel`\\>\n\nCreate a channel. The caller becomes the owner.\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `client` | `MacroClient` | - |\n| `opts` | \\{ `name?`: `string`; `participants?`: [`User`](../../../users/user/classes/User.md)[]; `team?`: [`Team`](../../../teams/team/classes/Team.md); `type`: [`ChannelType`](../../../../../generated/storage/types.gen/type-aliases/ChannelType.md); \\} | - |\n| `opts.name?` | `string` | - |\n| `opts.participants?` | [`User`](../../../users/user/classes/User.md)[] | Participants to add, excluding the owner. |\n| `opts.team?` | [`Team`](../../../teams/team/classes/Team.md) | Team, for team channels. |\n| `opts.type` | [`ChannelType`](../../../../../generated/storage/types.gen/type-aliases/ChannelType.md) | - |\n\n#### Returns\n\n`Promise`\\<`Channel`\\>\n\n***\n\n### dm()\n\n> `static` **dm**(`client`, `recipient`): `Promise`\\<`Channel`\\>\n\nOpen (creating if needed) the DM channel with a user.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `recipient` | [`User`](../../../users/user/classes/User.md) |\n\n#### Returns\n\n`Promise`\\<`Channel`\\>\n\n***\n\n### private()\n\n> `static` **private**(`client`, `recipients`): `Promise`\\<`Channel`\\>\n\nOpen (creating if needed) the private group channel with a set of users.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `recipients` | [`User`](../../../users/user/classes/User.md)[] |\n\n#### Returns\n\n`Promise`\\<`Channel`\\>\n\n\n<!-- src/entities/channels/channel/type-aliases/ChannelAttachment.md -->\n# Type Alias: ChannelAttachment\n\n> **ChannelAttachment** = [`GetChannelAttachmentsResponses`](../../../../../generated/storage/types.gen/type-aliases/GetChannelAttachmentsResponses.md)\\[`200`\\]\\[`\"items\"`\\]\\[`number`\\]\n\nA file or entity attached to a message in a channel.\n\n\n<!-- src/entities/channels/channel/type-aliases/ChannelParticipant.md -->\n# Type Alias: ChannelParticipant\n\n> **ChannelParticipant** = [`GetChannelParticipantsResponses`](../../../../../generated/storage/types.gen/type-aliases/GetChannelParticipantsResponses.md)\\[`200`\\]\\[`number`\\]\n\nA member of a channel, with their role and join time.\n\n\n<!-- src/entities/channels/labels/classes/ChannelLabelsNamespace.md -->\n# Class: ChannelLabelsNamespace\n\nShared or private channel labels: named groups of channels shown in the Chat\nsidebar. Every member of the team sees the same labels in the same order,\nand any member may create, rename, delete, or move channels between them;\neach change applies to the whole team. Users without a team have private\nlabels belonging to their account.\n\nA label's `channelIds` lists only the channels the authenticated user is a\nmember of. Manual labels count all assignments; smart tags count visible\nmatches. A channel can be in one manual label and any number of matching\nsmart tags per team or account. Direct messages cannot be grouped.\n\n## Constructors\n\n### Constructor\n\n> **new ChannelLabelsNamespace**(`client`): `ChannelLabelsNamespace`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`ChannelLabelsNamespace`\n\n## Methods\n\n### create()\n\n> **create**(`name`, `channels?`): `Promise`\\<[`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md)\\>\n\nCreate a label and atomically move `channels` into it. Names are unique\nwithin the team or account, case-insensitively.\n\n#### Parameters\n\n| Parameter | Type | Default value |\n| ------ | ------ | ------ |\n| `name` | `string` | `undefined` |\n| `channels?` | [`Channel`](../../channel/classes/Channel.md)[] | `[]` |\n\n#### Returns\n\n`Promise`\\<[`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md)\\>\n\n***\n\n### createSmartTag()\n\n> **createSmartTag**(`name`, `rule`): `Promise`\\<[`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md)\\>\n\nCreate a smart tag whose membership follows an attribute rule automatically.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `name` | `string` |\n| `rule` | [`ChannelLabelRule`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabelRule.md) |\n\n#### Returns\n\n`Promise`\\<[`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md)\\>\n\n***\n\n### delete()\n\n> **delete**(`label`): `Promise`\\<`void`\\>\n\nDelete a label for the whole team; its channels return to the plain list.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `label` | [`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### list()\n\n> **list**(): `Promise`\\<[`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md)[]\\>\n\nEvery label in the authenticated user's shared or private scope.\n\n#### Returns\n\n`Promise`\\<[`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md)[]\\>\n\n***\n\n### previewSmartTag()\n\n> **previewSmartTag**(`rule`): `Promise`\\<[`SmartTagPreview`](../../../../../generated/storage/types.gen/type-aliases/SmartTagPreview.md)\\>\n\nPreview the first matches and total visible count without creating a tag.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `rule` | [`ChannelLabelRule`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabelRule.md) |\n\n#### Returns\n\n`Promise`\\<[`SmartTagPreview`](../../../../../generated/storage/types.gen/type-aliases/SmartTagPreview.md)\\>\n\n***\n\n### rename()\n\n> **rename**(`label`, `name`): `Promise`\\<[`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md)\\>\n\nRename a label for the whole team.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `label` | [`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md) |\n| `name` | `string` |\n\n#### Returns\n\n`Promise`\\<[`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md)\\>\n\n***\n\n### setLabel()\n\n> **setLabel**(`channel`, `label`): `Promise`\\<`void`\\>\n\nMove a channel into `label`, or out of any label when `label` is `undefined`.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `channel` | [`Channel`](../../channel/classes/Channel.md) |\n| `label` | [`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md) \\| `undefined` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### updateSmartTag()\n\n> **updateSmartTag**(`label`, `name`, `rule`): `Promise`\\<[`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md)\\>\n\nUpdate the name and matching rule of an existing smart tag.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `label` | [`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md) |\n| `name` | `string` |\n| `rule` | [`ChannelLabelRule`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabelRule.md) |\n\n#### Returns\n\n`Promise`\\<[`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md)\\>\n\n\n<!-- src/entities/channels/message/classes/Message.md -->\n# Class: Message\n\nA message in a channel. A thin handle: `id` and `channelId` are known up\nfront, and record-backed fields (`content`, `author`) load lazily on first\naccess and cache. Actions carry the ids for you.\n\n## Extends\n\n- [`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md)\\<[`Message`](../../../../../generated/storage/types.gen/type-aliases/Message.md)\\>\n\n## Properties\n\n| Property | Modifier | Type | Default value | Description | Overrides | Inherited from |\n| ------ | ------ | ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-channelid\"></a> `channelId` | `readonly` | `string` | `undefined` | - | - | - |\n| <a id=\"property-content\"></a> `content` | `readonly` | () => `Promise`\\<`string`\\> | `...` | The message body. | - | - |\n| <a id=\"property-createdat\"></a> `createdAt` | `readonly` | () => `Promise`\\<`string`\\> | `...` | When the message was created. | - | - |\n| <a id=\"property-editedat\"></a> `editedAt` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | `...` | When the message was last edited, if it has been. | - | - |\n| <a id=\"property-entitytype\"></a> `entityType` | `readonly` | `\"channel_message\"` | `'channel_message'` | Favorites identify channel messages as `channel_message`. | [`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`entityType`](../../../entity/classes/FavoritableEntity.md#property-entitytype) | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | `undefined` | - | - | [`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`id`](../../../entity/classes/FavoritableEntity.md#property-id) |\n| <a id=\"property-mentions\"></a> `mentions` | `readonly` | [`SimpleMention`](../../../../../generated/storage/types.gen/type-aliases/SimpleMention.md)[] | `[]` | Entities mentioned in this message, when a list, thread, or event supplied them. | - | - |\n| <a id=\"property-updatedat\"></a> `updatedAt` | `readonly` | () => `Promise`\\<`string`\\> | `...` | When the message was last updated. | - | - |\n\n## Methods\n\n### author()\n\n> **author**(): `Promise`\\<[`User`](../../../users/user/classes/User.md)\\>\n\nThe user who sent this message.\n\n#### Returns\n\n`Promise`\\<[`User`](../../../users/user/classes/User.md)\\>\n\n***\n\n### channel()\n\n> **channel**(): [`Channel`](../../channel/classes/Channel.md)\n\nThe channel this message is in.\n\n#### Returns\n\n[`Channel`](../../channel/classes/Channel.md)\n\n***\n\n### delete()\n\n> **delete**(): `Promise`\\<`void`\\>\n\nDelete this message.\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### edit()\n\n> **edit**(`body`): `Promise`\\<`Message`\\>\n\nReplace this message's body.\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `body` | `string` \\| [`RichMessage`](../../../../mentions/interfaces/RichMessage.md) | Plain text, or a rich body composed with msg. |\n\n#### Returns\n\n`Promise`\\<`Message`\\>\n\n***\n\n### favorite()\n\n> **favorite**(): `Promise`\\<`Message`\\>\n\nAdd this entity to the user's favorites. Returns this handle for chaining.\nPlain unwrap: favoriting alters the user's favorites collection, not this\nentity's own detail, so there's nothing cached to invalidate.\n\n#### Returns\n\n`Promise`\\<`Message`\\>\n\n#### Inherited from\n\n[`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`favorite`](../../../entity/classes/FavoritableEntity.md#favorite)\n\n***\n\n### permission()\n\n> **permission**(): `Promise`\\<\\{ `permission`: [`EntityPermission`](../../../../../generated/storage/types.gen/type-aliases/EntityPermission.md); `status`: `\"access\"`; \\} \\| \\{ `status`: `\"no_access\"`; \\}\\>\n\nRead the caller's effective permission on this entity.\n\n#### Returns\n\n`Promise`\\<\\{ `permission`: [`EntityPermission`](../../../../../generated/storage/types.gen/type-aliases/EntityPermission.md); `status`: `\"access\"`; \\} \\| \\{ `status`: `\"no_access\"`; \\}\\>\n\n#### Inherited from\n\n[`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`permission`](../../../entity/classes/FavoritableEntity.md#permission)\n\n***\n\n### react()\n\n> **react**(`emoji`): `Promise`\\<`Message`\\>\n\nAdd an emoji reaction to this message.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `emoji` | `string` |\n\n#### Returns\n\n`Promise`\\<`Message`\\>\n\n***\n\n### reply()\n\n> **reply**(`body`): `Promise`\\<`Message`\\>\n\nPost a reply in this message's thread.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `body` | `string` \\| [`RichMessage`](../../../../mentions/interfaces/RichMessage.md) |\n\n#### Returns\n\n`Promise`\\<`Message`\\>\n\n***\n\n### thread()\n\n> **thread**(): [`Thread`](../../thread/classes/Thread.md)\n\nThe thread rooted at this message.\n\n#### Returns\n\n[`Thread`](../../thread/classes/Thread.md)\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`Message`](../../../../../generated/storage/types.gen/type-aliases/Message.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`Message`](../../../../../generated/storage/types.gen/type-aliases/Message.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`Message`](../../../../../generated/storage/types.gen/type-aliases/Message.md) |\n| `id` | `string` |\n\n#### Inherited from\n\n[`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`toJSON`](../../../entity/classes/FavoritableEntity.md#tojson)\n\n***\n\n### unfavorite()\n\n> **unfavorite**(): `Promise`\\<`Message`\\>\n\nRemove this entity from the user's favorites. Returns this handle for chaining.\n\n#### Returns\n\n`Promise`\\<`Message`\\>\n\n#### Inherited from\n\n[`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`unfavorite`](../../../entity/classes/FavoritableEntity.md#unfavorite)\n\n***\n\n### unreact()\n\n> **unreact**(`emoji`): `Promise`\\<`Message`\\>\n\nRemove one of your emoji reactions from this message.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `emoji` | `string` |\n\n#### Returns\n\n`Promise`\\<`Message`\\>\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `channelId`, `id`, `mentions?`): `Message`\n\nA handle to a message by id. Fields load on first access.\n\n#### Parameters\n\n| Parameter | Type | Default value |\n| ------ | ------ | ------ |\n| `client` | `MacroClient` | `undefined` |\n| `channelId` | `string` | `undefined` |\n| `id` | `string` | `undefined` |\n| `mentions?` | [`SimpleMention`](../../../../../generated/storage/types.gen/type-aliases/SimpleMention.md)[] | `[]` |\n\n#### Returns\n\n`Message`\n\n***\n\n### from()\n\n> `static` **from**(`client`, `channelId`, `data`): `Message`\n\nBuild a root or reply from a message record (pre-seeded, no fetch).\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `channelId` | `string` |\n| `data` | [`Message`](../../../../../generated/storage/types.gen/type-aliases/Message.md) |\n\n#### Returns\n\n`Message`\n\n\n<!-- src/entities/channels/message/type-aliases/MessageData.md -->\n# Type Alias: MessageData\n\n> **MessageData** = [`Message`](../../../../../generated/storage/types.gen/type-aliases/Message.md)\n\nThe API's representation of a message; the same record the document comment API returns.\n\n\n<!-- src/entities/channels/namespace/classes/ChannelNamespace.md -->\n# Class: ChannelNamespace\n\n## Constructors\n\n### Constructor\n\n> **new ChannelNamespace**(`client`): `ChannelNamespace`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`ChannelNamespace`\n\n## Properties\n\n| Property | Modifier | Type | Description |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-labels\"></a> `labels` | `readonly` | [`ChannelLabelsNamespace`](../../labels/classes/ChannelLabelsNamespace.md) | Team-shared labels that group channels in the Chat sidebar. |\n\n## Methods\n\n### activity()\n\n> **activity**(): `Promise`\\<[`ChannelActivity`](../../activity/classes/ChannelActivity.md)[]\\>\n\nRecent channel activity, with channel and user handles.\n\n#### Returns\n\n`Promise`\\<[`ChannelActivity`](../../activity/classes/ChannelActivity.md)[]\\>\n\n***\n\n### byId()\n\n> **byId**(`id`): [`Channel`](../../channel/classes/Channel.md)\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n[`Channel`](../../channel/classes/Channel.md)\n\n***\n\n### create()\n\n> **create**(`opts`): `Promise`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\nCreate a channel. The caller becomes the owner.\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `opts` | \\{ `name?`: `string`; `participants?`: [`User`](../../../users/user/classes/User.md)[]; `team?`: [`Team`](../../../teams/team/classes/Team.md); `type`: [`ChannelType`](../../../../../generated/storage/types.gen/type-aliases/ChannelType.md); \\} | - |\n| `opts.name?` | `string` | - |\n| `opts.participants?` | [`User`](../../../users/user/classes/User.md)[] | Participants to add, excluding the owner. |\n| `opts.team?` | [`Team`](../../../teams/team/classes/Team.md) | Team, for team channels. |\n| `opts.type` | [`ChannelType`](../../../../../generated/storage/types.gen/type-aliases/ChannelType.md) | - |\n\n#### Returns\n\n`Promise`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\n***\n\n### dm()\n\n> **dm**(`recipient`): `Promise`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `recipient` | [`User`](../../../users/user/classes/User.md) |\n\n#### Returns\n\n`Promise`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\n***\n\n### list()\n\n> **list**(): `Promise`\\<[`Channel`](../../channel/classes/Channel.md)[]\\>\n\nAll channels the authenticated user is a member of.\n\n#### Returns\n\n`Promise`\\<[`Channel`](../../channel/classes/Channel.md)[]\\>\n\n***\n\n### private()\n\n> **private**(`recipients`): `Promise`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\nOpen (creating if needed) the private group channel with a set of users.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `recipients` | [`User`](../../../users/user/classes/User.md)[] |\n\n#### Returns\n\n`Promise`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\n***\n\n### search()\n\n> **search**(`query`, `opts?`): `AsyncGenerator`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\nSearch channels by name (client-side fuzzy filter on the full channel list)\nor by content (server-side unified search).\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `query` | `string` |\n| `opts?` | [`SearchOpts`](../../../search/interfaces/SearchOpts.md) |\n\n#### Returns\n\n`AsyncGenerator`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\n\n<!-- src/entities/channels/picture/classes/ChannelPicture.md -->\n# Class: ChannelPicture\n\nAn uploaded channel profile picture in static file storage.\n\n## Properties\n\n| Property | Modifier | Type |\n| ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `readonly` | `string` |\n\n## Methods\n\n### toJSON()\n\n> **toJSON**(): \\{ `id`: `string`; \\}\n\nSerialize the uploaded picture reference.\n\n#### Returns\n\n\\{ `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n***\n\n### byId()\n\n> `static` **byId**(`id`): `ChannelPicture`\n\nConstruct a reference from the upload receipt.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n`ChannelPicture`\n\n\n<!-- src/entities/channels/post/functions/postToChannel.md -->\n# Function: postToChannel()\n\n> **postToChannel**(`client`, `target`, `body`): `Promise`\\<`string`\\>\n\nPost a message using the endpoint supported by the caller's credentials.\n\nMost credentials use `POST /messages/channel/{id}`. User-owned bots without\nan acting user instead use `POST /channels/{id}/webhook`, which authorizes\nthrough channel membership. The bot owner is read from `GET /bots/me` and\ncached by the client.\n\nThe webhook endpoint supports content only. Mentions in `<m-*>` tags still\nwork, but threads and attachments are not supported.\n\nPosting to a `Thread` puts the message in that thread; to a `Channel`, at the\nchannel root. One target rather than a channel plus a thread id, so the two\ncan't disagree.\n\n## Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `target` | [`Channel`](../../channel/classes/Channel.md) \\| [`Thread`](../../thread/classes/Thread.md) |\n| `body` | [`RichMessage`](../../../../mentions/interfaces/RichMessage.md) |\n\n## Returns\n\n`Promise`\\<`string`\\>\n\n\n<!-- src/entities/channels/thread/classes/Thread.md -->\n# Class: Thread\n\nA thread within a channel, rooted at a top-level message. Replies and\nthread-scoped posting live here.\n\n## Constructors\n\n### Constructor\n\n> **new Thread**(`client`, `channelId`, `rootId`): `Thread`\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `client` | `MacroClient` | - |\n| `channelId` | `string` | - |\n| `rootId` | `string` | The id of the message this thread hangs off. |\n\n#### Returns\n\n`Thread`\n\n## Properties\n\n| Property | Modifier | Type | Description |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-channelid\"></a> `channelId` | `readonly` | `string` | - |\n| <a id=\"property-rootid\"></a> `rootId` | `readonly` | `string` | The id of the message this thread hangs off. |\n\n## Methods\n\n### channel()\n\n> **channel**(): [`Channel`](../../channel/classes/Channel.md)\n\nThe channel this thread is in.\n\n#### Returns\n\n[`Channel`](../../channel/classes/Channel.md)\n\n***\n\n### replies()\n\n> **replies**(): `Promise`\\<[`Message`](../../message/classes/Message.md)[]\\>\n\nList the replies in this thread, oldest first.\n\n#### Returns\n\n`Promise`\\<[`Message`](../../message/classes/Message.md)[]\\>\n\n***\n\n### reply()\n\n> **reply**(`body`): `Promise`\\<[`Message`](../../message/classes/Message.md)\\>\n\nPost a reply in this thread.\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `body` | `string` \\| [`RichMessage`](../../../../mentions/interfaces/RichMessage.md) | Plain text, or a rich body composed with msg. |\n\n#### Returns\n\n`Promise`\\<[`Message`](../../message/classes/Message.md)\\>\n\nThe created reply.\n\n***\n\n### root()\n\n> **root**(): [`Message`](../../message/classes/Message.md)\n\nThe message this thread hangs off.\n\n#### Returns\n\n[`Message`](../../message/classes/Message.md)\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `channelId`: `string`; `rootId`: `string`; \\}\n\nSerialize the thread identity without its authenticated client.\n\n#### Returns\n\n\\{ `channelId`: `string`; `rootId`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `channelId` | `string` |\n| `rootId` | `string` |\n\n\n<!-- src/entities/whatsapp/account/classes/WhatsAppAccount.md -->\n# Class: WhatsAppAccount\n\nThe current user's WhatsApp account, connected through the Macro app.\n\n## Extends\n\n- [`MacroEntity`](../../../entity/classes/MacroEntity.md)\\<[`LinkedAccount`](../../../../../generated/storage/types.gen/type-aliases/LinkedAccount.md)\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | - | [`MacroEntity`](../../../entity/classes/MacroEntity.md).[`id`](../../../entity/classes/MacroEntity.md#property-id) |\n| <a id=\"property-identity\"></a> `identity` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | Verified remote identity, absent until pairing succeeds. | - |\n| <a id=\"property-owner\"></a> `owner` | `readonly` | () => `Promise`\\<[`User`](../../../users/user/classes/User.md)\\> | The Macro user who owns this account. | - |\n| <a id=\"property-state\"></a> `state` | `readonly` | () => `Promise`\\<[`LinkedAccountState`](../../../../../generated/storage/types.gen/type-aliases/LinkedAccountState.md)\\> | Account connection state; call refresh before polling it again. | - |\n\n## Methods\n\n### refresh()\n\n> **refresh**(): `Promise`\\<`WhatsAppAccount`\\>\n\nDiscard cached connection state and load its current value.\n\n#### Returns\n\n`Promise`\\<`WhatsAppAccount`\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`LinkedAccount`](../../../../../generated/storage/types.gen/type-aliases/LinkedAccount.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`LinkedAccount`](../../../../../generated/storage/types.gen/type-aliases/LinkedAccount.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`LinkedAccount`](../../../../../generated/storage/types.gen/type-aliases/LinkedAccount.md) |\n| `id` | `string` |\n\n#### Inherited from\n\n[`MacroEntity`](../../../entity/classes/MacroEntity.md).[`toJSON`](../../../entity/classes/MacroEntity.md#tojson)\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `id`): `WhatsAppAccount`\n\nReference an account; reads still enforce the authenticated owner's scope.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `id` | `string` |\n\n#### Returns\n\n`WhatsAppAccount`\n\n***\n\n### from()\n\n> `static` **from**(`client`, `record`): `WhatsAppAccount`\n\nSeed an account handle from an API record.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `record` | [`LinkedAccount`](../../../../../generated/storage/types.gen/type-aliases/LinkedAccount.md) |\n\n#### Returns\n\n`WhatsAppAccount`\n\n\n<!-- src/entities/whatsapp/chat/classes/WhatsAppChat.md -->\n# Class: WhatsAppChat\n\nOne chat of the current user's WhatsApp chat list: a group or a direct chat.\n\n## Extends\n\n- [`MacroEntity`](../../../entity/classes/MacroEntity.md)\\<[`LinkedChat`](../../../../../generated/storage/types.gen/type-aliases/LinkedChat.md)\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-archived\"></a> `archived` | `readonly` | () => `Promise`\\<`boolean`\\> | Archived in WhatsApp. | - |\n| <a id=\"property-canadd\"></a> `canAdd` | `readonly` | () => `Promise`\\<`boolean`\\> | Whether adding it to Macro works now. | - |\n| <a id=\"property-cannotaddreason\"></a> `cannotAddReason` | `readonly` | () => `Promise`\\<`NonNullable`\\<LinkedCannotAdd \\| null \\| undefined\\> \\| `undefined`\\> | Why it can't be added (`not_in_group`, `community`, `own_chat`, `not_in_chat_list`), when it is neither added, shared nor addable. | - |\n| <a id=\"property-community\"></a> `community` | `readonly` | () => `Promise`\\<[`WhatsAppCommunity`](../type-aliases/WhatsAppCommunity.md) \\| `undefined`\\> | The WhatsApp community a group belongs to, if any: the community's own chat, its name, and whether this is its announcement group. | - |\n| <a id=\"property-group\"></a> `group` | `readonly` | () => `Promise`\\<[`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) \\| `undefined`\\> | The current user's own Macro group for this chat, once added. | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | - | [`MacroEntity`](../../../entity/classes/MacroEntity.md).[`id`](../../../entity/classes/MacroEntity.md#property-id) |\n| <a id=\"property-kind\"></a> `kind` | `readonly` | () => `Promise`\\<[`LinkedChatKind`](../../../../../generated/storage/types.gen/type-aliases/LinkedChatKind.md)\\> | `group` or `direct`. | - |\n| <a id=\"property-lastactivityat\"></a> `lastActivityAt` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | Newest activity WhatsApp reported, when known. | - |\n| <a id=\"property-name\"></a> `name` | `readonly` | () => `Promise`\\<`string`\\> | Group subject (or member names), or the other person's name or number. | - |\n| <a id=\"property-pinned\"></a> `pinned` | `readonly` | () => `Promise`\\<`boolean`\\> | Pinned in WhatsApp. | - |\n| <a id=\"property-shared\"></a> `shared` | `readonly` | () => `Promise`\\<[`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) \\| `undefined`\\> | Someone else's Macro group for this chat, shared with the current user. | - |\n\n## Methods\n\n### adopt()\n\n> **adopt**(): `Promise`\\<[`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md)\\>\n\nAdd the chat (a group or a direct chat) to Macro as the current user's\nown; its earlier messages are imported from the phone. Adding it again\nreturns the same chat. Only the owner sends in a direct chat.\n\n#### Returns\n\n`Promise`\\<[`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md)\\>\n\n***\n\n### refresh()\n\n> **refresh**(): `Promise`\\<`WhatsAppChat`\\>\n\nReload the chat's list entry.\n\n#### Returns\n\n`Promise`\\<`WhatsAppChat`\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`LinkedChat`](../../../../../generated/storage/types.gen/type-aliases/LinkedChat.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`LinkedChat`](../../../../../generated/storage/types.gen/type-aliases/LinkedChat.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`LinkedChat`](../../../../../generated/storage/types.gen/type-aliases/LinkedChat.md) |\n| `id` | `string` |\n\n#### Inherited from\n\n[`MacroEntity`](../../../entity/classes/MacroEntity.md).[`toJSON`](../../../entity/classes/MacroEntity.md#tojson)\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `id`): `WhatsAppChat`\n\nReference a chat by its WhatsApp JID.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `id` | `string` |\n\n#### Returns\n\n`WhatsAppChat`\n\n***\n\n### from()\n\n> `static` **from**(`client`, `record`): `WhatsAppChat`\n\nSeed a chat handle from the chat list.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `record` | [`LinkedChat`](../../../../../generated/storage/types.gen/type-aliases/LinkedChat.md) |\n\n#### Returns\n\n`WhatsAppChat`\n\n\n<!-- src/entities/whatsapp/chat/functions/communityOf.md -->\n# Function: communityOf()\n\n> **communityOf**(`client`, `record`): [`WhatsAppCommunity`](../type-aliases/WhatsAppCommunity.md)\n\nA community reference as a handle on the community's own chat.\n\n## Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `record` | [`LinkedCommunityReference`](../../../../../generated/storage/types.gen/type-aliases/LinkedCommunityReference.md) |\n\n## Returns\n\n[`WhatsAppCommunity`](../type-aliases/WhatsAppCommunity.md)\n\n\n<!-- src/entities/whatsapp/chat/type-aliases/WhatsAppCommunity.md -->\n# Type Alias: WhatsAppCommunity\n\n> **WhatsAppCommunity** = \\{ `announcements`: `boolean`; `chat`: [`WhatsAppChat`](../classes/WhatsAppChat.md); `name`: `string`; \\}\n\nThe WhatsApp community a group belongs to.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-announcements\"></a> `announcements` | `boolean` | This group is the community's announcement group. |\n| <a id=\"property-chat\"></a> `chat` | [`WhatsAppChat`](../classes/WhatsAppChat.md) | The community itself, as a chat of the list (it can't be added). |\n| <a id=\"property-name\"></a> `name` | `string` | The community's name. |\n\n\n<!-- src/entities/whatsapp/group/classes/WhatsAppGroup.md -->\n# Class: WhatsAppGroup\n\nIndependently shareable added WhatsApp chat: a group or a direct chat.\n\n## Extends\n\n- [`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md)\\<[`WhatsAppGroupDetail`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppGroupDetail.md)\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Overrides | Inherited from |\n| ------ | ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-backfill\"></a> `backfill` | `readonly` | () => `Promise`\\<[`LinkedBackfill`](../../../../../generated/storage/types.gen/type-aliases/LinkedBackfill.md) \\| `undefined`\\> | Importing earlier messages from the owner's phone after adding, if any. | - | - |\n| <a id=\"property-cansend\"></a> `canSend` | `readonly` | () => `Promise`\\<`boolean`\\> | Whether the caller can send from their own connected account. | - | - |\n| <a id=\"property-community\"></a> `community` | `readonly` | () => `Promise`\\<[`WhatsAppCommunity`](../../chat/type-aliases/WhatsAppCommunity.md) \\| `undefined`\\> | The WhatsApp community this group belongs to, if any: the community's own chat, its name, and whether this is its announcement group. | - | - |\n| <a id=\"property-disappearingseconds\"></a> `disappearingSeconds` | `readonly` | () => `Promise`\\<`number` \\| `undefined`\\> | WhatsApp's disappearing-messages timer in seconds while on; Macro keeps the messages. | - | - |\n| <a id=\"property-entitytype\"></a> `entityType` | `readonly` | `\"whatsapp_group\"` | Canonical sharing and favorites kind. | [`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`entityType`](../../../entity/classes/FavoritableEntity.md#property-entitytype) | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | - | - | [`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`id`](../../../entity/classes/FavoritableEntity.md#property-id) |\n| <a id=\"property-kind\"></a> `kind` | `readonly` | () => `Promise`\\<[`LinkedChatKind`](../../../../../generated/storage/types.gen/type-aliases/LinkedChatKind.md)\\> | `group`, or `direct` for a one-to-one chat (only its owner sends). | - | - |\n| <a id=\"property-limits\"></a> `limits` | `readonly` | () => `Promise`\\<[`LinkedCapabilities`](../../../../../generated/storage/types.gen/type-aliases/LinkedCapabilities.md)\\> | Supported sizes and mutation window. | - | - |\n| <a id=\"property-name\"></a> `name` | `readonly` | () => `Promise`\\<`string`\\> | Display name: the group's, or a direct chat's other person. | - | - |\n| <a id=\"property-owner\"></a> `owner` | `readonly` | () => `Promise`\\<[`User`](../../../users/user/classes/User.md)\\> | Actual owner, independent of WhatsApp membership. | - | - |\n| <a id=\"property-participants\"></a> `participants` | `readonly` | () => `Promise`\\<[`WhatsAppParticipant`](../../participant/classes/WhatsAppParticipant.md)[]\\> | Everyone in the chat, from its roster; empty when no roster is known. | - | - |\n| <a id=\"property-roster\"></a> `roster` | `readonly` | () => `Promise`\\<[`LinkedGroupInfo`](../../../../../generated/storage/types.gen/type-aliases/LinkedGroupInfo.md) \\| `undefined`\\> | Current remote roster (name, participants, announce), when available. | - | - |\n| <a id=\"property-sendingidentity\"></a> `sendingIdentity` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | Caller's own verified sending identity. | - | - |\n| <a id=\"property-sendreason\"></a> `sendReason` | `readonly` | () => `Promise`\\<`NonNullable`\\<LinkedReplyBlock \\| null \\| undefined\\> \\| `undefined`\\> | Reason sending is blocked. | - | - |\n| <a id=\"property-unreadcount\"></a> `unreadCount` | `readonly` | () => `Promise`\\<`number`\\> | Per-user unread count. | - | - |\n\n## Methods\n\n### delivery()\n\n> **delivery**(`sends`): `Promise`\\<[`WhatsAppSend`](../../send/classes/WhatsAppSend.md)[]\\>\n\nRead delivery for selected caller-owned intents or messages.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `sends` | ([`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md) \\| [`WhatsAppSend`](../../send/classes/WhatsAppSend.md))[] |\n\n#### Returns\n\n`Promise`\\<[`WhatsAppSend`](../../send/classes/WhatsAppSend.md)[]\\>\n\n***\n\n### detach()\n\n> **detach**(): `Promise`\\<`void`\\>\n\nStop observation while preserving history and established sharing.\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### favorite()\n\n> **favorite**(): `Promise`\\<`WhatsAppGroup`\\>\n\nAdd this entity to the user's favorites. Returns this handle for chaining.\nPlain unwrap: favoriting alters the user's favorites collection, not this\nentity's own detail, so there's nothing cached to invalidate.\n\n#### Returns\n\n`Promise`\\<`WhatsAppGroup`\\>\n\n#### Inherited from\n\n[`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`favorite`](../../../entity/classes/FavoritableEntity.md#favorite)\n\n***\n\n### markRead()\n\n> **markRead**(`message`): `Promise`\\<`void`\\>\n\nAdvance the caller's own read cursor.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `message` | [`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### messageAttachments()\n\n> **messageAttachments**(`messages`): `Promise`\\<\\{ `attachments`: \\{ `document`: [`Document`](../../../documents/document/classes/Document.md) \\| `undefined`; `fileName`: `string`; `mime`: `string`; `ordinal`: `number`; `size`: `number`; `state`: [`LinkedAttachmentState`](../../../../../generated/storage/types.gen/type-aliases/LinkedAttachmentState.md); \\}[]; `message`: [`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md); \\}[]\\>\n\nRead attachment states for selected messages.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `messages` | [`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md)[] |\n\n#### Returns\n\n`Promise`\\<\\{ `attachments`: \\{ `document`: [`Document`](../../../documents/document/classes/Document.md) \\| `undefined`; `fileName`: `string`; `mime`: `string`; `ordinal`: `number`; `size`: `number`; `state`: [`LinkedAttachmentState`](../../../../../generated/storage/types.gen/type-aliases/LinkedAttachmentState.md); \\}[]; `message`: [`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md); \\}[]\\>\n\n***\n\n### messages()\n\n> **messages**(`options?`): `AsyncGenerator`\\<[`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md)\\>\n\nIterate newest-first timeline pages lazily.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options?` | \\{ `limit?`: `number`; \\} |\n| `options.limit?` | `number` |\n\n#### Returns\n\n`AsyncGenerator`\\<[`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md)\\>\n\n***\n\n### permission()\n\n> **permission**(): `Promise`\\<\\{ `permission`: [`EntityPermission`](../../../../../generated/storage/types.gen/type-aliases/EntityPermission.md); `status`: `\"access\"`; \\} \\| \\{ `status`: `\"no_access\"`; \\}\\>\n\nRead the caller's effective permission on this entity.\n\n#### Returns\n\n`Promise`\\<\\{ `permission`: [`EntityPermission`](../../../../../generated/storage/types.gen/type-aliases/EntityPermission.md); `status`: `\"access\"`; \\} \\| \\{ `status`: `\"no_access\"`; \\}\\>\n\n#### Inherited from\n\n[`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`permission`](../../../entity/classes/FavoritableEntity.md#permission)\n\n***\n\n### permissions()\n\n> **permissions**(): `Promise`\\<[`SharePermissionV2`](../../../../../generated/storage/types.gen/type-aliases/SharePermissionV2.md)\\>\n\nRead standard link/team sharing settings.\n\n#### Returns\n\n`Promise`\\<[`SharePermissionV2`](../../../../../generated/storage/types.gen/type-aliases/SharePermissionV2.md)\\>\n\n***\n\n### refresh()\n\n> **refresh**(): `Promise`\\<`WhatsAppGroup`\\>\n\nReload detail, permissions and caller capabilities.\n\n#### Returns\n\n`Promise`\\<`WhatsAppGroup`\\>\n\n***\n\n### reply()\n\n> **reply**(`content`, `options`): `Promise`\\<[`WhatsAppSend`](../../send/classes/WhatsAppSend.md)\\>\n\nPersonal sessions and owner API credentials can send. Bots never send.\nPreserve the idempotency key; uncertain outcomes are never automatically resent.\nThe server enforces one request per second per user.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `content` | [`WhatsAppReply`](../type-aliases/WhatsAppReply.md) |\n| `options` | \\{ `idempotencyKey`: `string`; `replyTo?`: [`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md); \\} |\n| `options.idempotencyKey` | `string` |\n| `options.replyTo?` | [`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md) |\n\n#### Returns\n\n`Promise`\\<[`WhatsAppSend`](../../send/classes/WhatsAppSend.md)\\>\n\n***\n\n### sends()\n\n> **sends**(): `Promise`\\<[`WhatsAppSend`](../../send/classes/WhatsAppSend.md)[]\\>\n\nRead only the caller's pending, uncertain or failed sends.\n\n#### Returns\n\n`Promise`\\<[`WhatsAppSend`](../../send/classes/WhatsAppSend.md)[]\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`WhatsAppGroupDetail`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppGroupDetail.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`WhatsAppGroupDetail`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppGroupDetail.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`WhatsAppGroupDetail`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppGroupDetail.md) |\n| `id` | `string` |\n\n#### Inherited from\n\n[`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`toJSON`](../../../entity/classes/FavoritableEntity.md#tojson)\n\n***\n\n### unfavorite()\n\n> **unfavorite**(): `Promise`\\<`WhatsAppGroup`\\>\n\nRemove this entity from the user's favorites. Returns this handle for chaining.\n\n#### Returns\n\n`Promise`\\<`WhatsAppGroup`\\>\n\n#### Inherited from\n\n[`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`unfavorite`](../../../entity/classes/FavoritableEntity.md#unfavorite)\n\n***\n\n### updatePermissions()\n\n> **updatePermissions**(`update`): `Promise`\\<`void`\\>\n\nActual owner updates standard link/team sharing settings.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `update` | [`UpdateSharePermissionRequestV2`](../../../../../generated/storage/types.gen/type-aliases/UpdateSharePermissionRequestV2.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### upload()\n\n> **upload**(`file`): `Promise`\\<[`WhatsAppUpload`](../../upload/classes/WhatsAppUpload.md)\\>\n\nStage a supported attachment for a deliberate send.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `file` | `Blob` \\| `File` |\n\n#### Returns\n\n`Promise`\\<[`WhatsAppUpload`](../../upload/classes/WhatsAppUpload.md)\\>\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `id`): `WhatsAppGroup`\n\nReference an adopted group; access is checked on each request.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `id` | `string` |\n\n#### Returns\n\n`WhatsAppGroup`\n\n\n<!-- src/entities/whatsapp/group/type-aliases/WhatsAppReply.md -->\n# Type Alias: WhatsAppReply\n\n> **WhatsAppReply** = \\{ `mentions?`: [`WhatsAppParticipant`](../../participant/classes/WhatsAppParticipant.md)[]; `text`: `string`; `type`: `\"text\"`; \\} \\| \\{ `caption?`: `string`; `type`: `\"media\"`; `upload`: [`WhatsAppUpload`](../../upload/classes/WhatsAppUpload.md); \\} \\| \\{ `message`: [`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md); `operation`: `\"reaction\"` \\| `\"edit\"` \\| `\"delete\"`; `text?`: `string`; `type`: `\"mutation\"`; \\}\n\nDeliberate content from the credential owner's own WhatsApp account.\n\n## Union Members\n\n### Type Literal\n\n\\{ `mentions?`: [`WhatsAppParticipant`](../../participant/classes/WhatsAppParticipant.md)[]; `text`: `string`; `type`: `\"text\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `mentions?` | [`WhatsAppParticipant`](../../participant/classes/WhatsAppParticipant.md)[] | Participants mentioned (from `participants()`); the text names each as `@<mentionToken>`. |\n| `text` | `string` | - |\n| `type` | `\"text\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `caption?`: `string`; `type`: `\"media\"`; `upload`: [`WhatsAppUpload`](../../upload/classes/WhatsAppUpload.md); \\}\n\n***\n\n### Type Literal\n\n\\{ `message`: [`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md); `operation`: `\"reaction\"` \\| `\"edit\"` \\| `\"delete\"`; `text?`: `string`; `type`: `\"mutation\"`; \\}\n\n\n<!-- src/entities/whatsapp/message/classes/WhatsAppMessage.md -->\n# Class: WhatsAppMessage\n\nMessage in an independently shared WhatsApp group.\n\n## Extends\n\n- [`MacroEntity`](../../../entity/classes/MacroEntity.md)\\<[`WhatsAppGroupMessage`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppGroupMessage.md)\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-attachments\"></a> `attachments` | `readonly` | () => `Promise`\\<\\{ `document`: [`Document`](../../../documents/document/classes/Document.md) \\| `undefined`; `durationSeconds`: `number` \\| `undefined`; `fileName`: `string`; `height`: `number` \\| `undefined`; `mime`: `string`; `ordinal`: `number`; `presentation`: [`LinkedMediaPresentation`](../../../../../generated/storage/types.gen/type-aliases/LinkedMediaPresentation.md) \\| `undefined`; `size`: `number`; `state`: [`LinkedAttachmentState`](../../../../../generated/storage/types.gen/type-aliases/LinkedAttachmentState.md); `width`: `number` \\| `undefined`; \\}[]\\> | Attachment state and imported document handles. | - |\n| <a id=\"property-body\"></a> `body` | `readonly` | () => `Promise`\\<`string`\\> | Plain WhatsApp text. | - |\n| <a id=\"property-deleted\"></a> `deleted` | `readonly` | () => `Promise`\\<`boolean`\\> | Deleted for everyone. | - |\n| <a id=\"property-deliverystate\"></a> `deliveryState` | `readonly` | () => `Promise`\\<`NonNullable`\\<LinkedDeliveryState \\| null \\| undefined\\> \\| `undefined`\\> | Caller-owned send's delivery state, when present. | - |\n| <a id=\"property-editedat\"></a> `editedAt` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | Last edit time. | - |\n| <a id=\"property-forwarded\"></a> `forwarded` | `readonly` | () => `Promise`\\<`boolean`\\> | Forwarded from another chat. | - |\n| <a id=\"property-group\"></a> `group` | `readonly` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) | The chat this message is in. | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | - | [`MacroEntity`](../../../entity/classes/MacroEntity.md).[`id`](../../../entity/classes/MacroEntity.md#property-id) |\n| <a id=\"property-kind\"></a> `kind` | `readonly` | () => `Promise`\\<[`WhatsAppMessageKind`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppMessageKind.md)\\> | `message`, or `system` for something that happened in the group (see `rich`). | - |\n| <a id=\"property-mentions\"></a> `mentions` | `readonly` | () => `Promise`\\<[`WhatsAppMention`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppMention.md)[]\\> | People the body @-mentions: `@<token>` in the body is this person. | - |\n| <a id=\"property-reactions\"></a> `reactions` | `readonly` | () => `Promise`\\<[`WhatsAppGroupReaction`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppGroupReaction.md)[]\\> | Grouped emoji counts and caller's own reaction. | - |\n| <a id=\"property-replyto\"></a> `replyTo` | `readonly` | () => `Promise`\\<`WhatsAppMessage` \\| `undefined`\\> | Quoted message in this group. | - |\n| <a id=\"property-rich\"></a> `rich` | `readonly` | () => `Promise`\\<`NonNullable`\\<WhatsAppRichContent \\| null \\| undefined\\> \\| `undefined`\\> | Poll (with tallies), location, contact cards, event or system line. | - |\n| <a id=\"property-sender\"></a> `sender` | `readonly` | () => `Promise`\\<[`WhatsAppGroupSender`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppGroupSender.md)\\> | Protocol-verified sender association and display name. | - |\n| <a id=\"property-sentat\"></a> `sentAt` | `readonly` | () => `Promise`\\<`string`\\> | WhatsApp timestamp. | - |\n| <a id=\"property-viewonce\"></a> `viewOnce` | `readonly` | () => `Promise`\\<`boolean`\\> | Sent as view-once in WhatsApp; Macro keeps and shows it like any media. | - |\n\n## Methods\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`WhatsAppGroupMessage`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppGroupMessage.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`WhatsAppGroupMessage`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppGroupMessage.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`WhatsAppGroupMessage`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppGroupMessage.md) |\n| `id` | `string` |\n\n#### Inherited from\n\n[`MacroEntity`](../../../entity/classes/MacroEntity.md).[`toJSON`](../../../entity/classes/MacroEntity.md#tojson)\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `group`, `id`): `WhatsAppMessage`\n\nReference a message within its original group.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `group` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) |\n| `id` | `string` |\n\n#### Returns\n\n`WhatsAppMessage`\n\n***\n\n### from()\n\n> `static` **from**(`client`, `group`, `record`): `WhatsAppMessage`\n\nSeed a message handle from a timeline response.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `group` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) |\n| `record` | [`WhatsAppGroupMessage`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppGroupMessage.md) |\n\n#### Returns\n\n`WhatsAppMessage`\n\n\n<!-- src/entities/whatsapp/namespace/classes/WhatsAppNamespace.md -->\n# Class: WhatsAppNamespace\n\nOperate on an account already paired through the Macro app.\n\n## Constructors\n\n### Constructor\n\n> **new WhatsAppNamespace**(`client`): `WhatsAppNamespace`\n\nBind existing-account operations to this authenticated client.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`WhatsAppNamespace`\n\n## Methods\n\n### account()\n\n> **account**(): `Promise`\\<[`WhatsAppAccount`](../../account/classes/WhatsAppAccount.md) \\| `undefined`\\>\n\nCurrent owner's account, or undefined when no account has been connected.\n\n#### Returns\n\n`Promise`\\<[`WhatsAppAccount`](../../account/classes/WhatsAppAccount.md) \\| `undefined`\\>\n\n***\n\n### byId()\n\n> **byId**(`id`): [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md)\n\nReference an adopted entity without fetching it.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n[`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md)\n\n***\n\n### groups()\n\n> **groups**(): `Promise`\\<[`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md)[]\\>\n\nAdopted groups shared with the caller, including without WhatsApp.\n\n#### Returns\n\n`Promise`\\<[`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md)[]\\>\n\n\n<!-- src/entities/whatsapp/participant/classes/WhatsAppParticipant.md -->\n# Class: WhatsAppParticipant\n\nSomeone in an added WhatsApp chat, from its roster; mention them in a text reply.\n\n## Properties\n\n| Property | Modifier | Type | Description |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-group\"></a> `group` | `readonly` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) | The chat whose roster lists them. |\n| <a id=\"property-id\"></a> `id` | `readonly` | `string` | Their WhatsApp id: correlation data, not a Macro user. |\n\n## Accessors\n\n### admin\n\n#### Get Signature\n\n> **get** **admin**(): `boolean` \\| `undefined`\n\nWhether they administer the group, when read from the roster.\n\n##### Returns\n\n`boolean` \\| `undefined`\n\n***\n\n### displayName\n\n#### Get Signature\n\n> **get** **displayName**(): `string` \\| `undefined`\n\nTheir WhatsApp name, untrusted, when the roster had one.\n\n##### Returns\n\n`string` \\| `undefined`\n\n***\n\n### mentionToken\n\n#### Get Signature\n\n> **get** **mentionToken**(): `string`\n\nThe digits a text reply writes as `@<digits>` to mention them.\n\n##### Returns\n\n`string`\n\n## Methods\n\n### toJSON()\n\n> **toJSON**(): \\{ `admin`: `boolean` \\| `undefined`; `displayName`: `string` \\| `undefined`; `group`: `string`; `id`: `string`; \\}\n\nSerialize the participant reference without credentials.\n\n#### Returns\n\n\\{ `admin`: `boolean` \\| `undefined`; `displayName`: `string` \\| `undefined`; `group`: `string`; `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `admin` | `boolean` \\| `undefined` |\n| `displayName` | `string` \\| `undefined` |\n| `group` | `string` |\n| `id` | `string` |\n\n***\n\n### byId()\n\n> `static` **byId**(`group`, `id`): `WhatsAppParticipant`\n\nReference a participant of a chat by WhatsApp id.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `group` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) |\n| `id` | `string` |\n\n#### Returns\n\n`WhatsAppParticipant`\n\n***\n\n### from()\n\n> `static` **from**(`group`, `record`): `WhatsAppParticipant`\n\nSeed a participant from the chat's roster.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `group` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) |\n| `record` | [`LinkedParticipant`](../../../../../generated/storage/types.gen/type-aliases/LinkedParticipant.md) |\n\n#### Returns\n\n`WhatsAppParticipant`\n\n\n<!-- src/entities/whatsapp/send/classes/WhatsAppSend.md -->\n# Class: WhatsAppSend\n\nOne deliberate send intent. Unknown outcomes must never be automatically resent.\n\n## Extends\n\n- [`MacroEntity`](../../../entity/classes/MacroEntity.md)\\<[`LinkedSendProgress`](../../../../../generated/storage/types.gen/type-aliases/LinkedSendProgress.md)\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-createdat\"></a> `createdAt` | `readonly` | () => `Promise`\\<`string`\\> | When the send intent was created. | - |\n| <a id=\"property-errorcode\"></a> `errorCode` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | Sanitized failure code, when present. | - |\n| <a id=\"property-group\"></a> `group` | `readonly` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) | Group entity containing this send. | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | - | [`MacroEntity`](../../../entity/classes/MacroEntity.md).[`id`](../../../entity/classes/MacroEntity.md#property-id) |\n| <a id=\"property-message\"></a> `message` | `readonly` | () => `Promise`\\<[`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md) \\| `undefined`\\> | Group message once WhatsApp accepted the send. | - |\n| <a id=\"property-state\"></a> `state` | `readonly` | () => `Promise`\\<[`LinkedDeliveryState`](../../../../../generated/storage/types.gen/type-aliases/LinkedDeliveryState.md)\\> | Last observed delivery state; refresh explicitly to poll again. | - |\n\n## Methods\n\n### refresh()\n\n> **refresh**(): `Promise`\\<`WhatsAppSend`\\>\n\nFetch current delivery state without retrying or submitting the message.\n\n#### Returns\n\n`Promise`\\<`WhatsAppSend`\\>\n\n***\n\n### request()\n\n> **request**(): `Promise`\\<\\{ `idempotencyKey`: `string`; `message`: [`WhatsAppReply`](../../group/type-aliases/WhatsAppReply.md); `replyTo?`: [`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md); \\}\\>\n\nInspect the original intent for reconciliation; never resubmit an unknown outcome automatically.\n\n#### Returns\n\n`Promise`\\<\\{ `idempotencyKey`: `string`; `message`: [`WhatsAppReply`](../../group/type-aliases/WhatsAppReply.md); `replyTo?`: [`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md); \\}\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`LinkedSendProgress`](../../../../../generated/storage/types.gen/type-aliases/LinkedSendProgress.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`LinkedSendProgress`](../../../../../generated/storage/types.gen/type-aliases/LinkedSendProgress.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`LinkedSendProgress`](../../../../../generated/storage/types.gen/type-aliases/LinkedSendProgress.md) |\n| `id` | `string` |\n\n#### Inherited from\n\n[`MacroEntity`](../../../entity/classes/MacroEntity.md).[`toJSON`](../../../entity/classes/MacroEntity.md#tojson)\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `group`, `id`): `WhatsAppSend`\n\nReference a send intent within its original group.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `group` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) |\n| `id` | `string` |\n\n#### Returns\n\n`WhatsAppSend`\n\n***\n\n### from()\n\n> `static` **from**(`client`, `group`, `record`): `WhatsAppSend`\n\nSeed a send handle from a server response.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `group` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) |\n| `record` | [`LinkedSendProgress`](../../../../../generated/storage/types.gen/type-aliases/LinkedSendProgress.md) |\n\n#### Returns\n\n`WhatsAppSend`\n\n\n<!-- src/entities/whatsapp/upload/classes/WhatsAppUpload.md -->\n# Class: WhatsAppUpload\n\nA staged attachment scoped to one adopted group; use it in a deliberate media send.\n\n## Properties\n\n| Property | Modifier | Type | Description |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-filename\"></a> `filename?` | `readonly` | `string` | Display filename supplied by the server. |\n| <a id=\"property-group\"></a> `group` | `readonly` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) | The chat this upload can be sent to. |\n| <a id=\"property-id\"></a> `id` | `readonly` | `string` | Correlation identity of the staged upload. |\n| <a id=\"property-kind\"></a> `kind?` | `readonly` | [`LinkedMediaKind`](../../../../../generated/storage/types.gen/type-aliases/LinkedMediaKind.md) | Media category supplied by the server. |\n\n## Methods\n\n### toJSON()\n\n> **toJSON**(): \\{ `filename`: `string` \\| `undefined`; `group`: `string`; `id`: `string`; `kind`: [`LinkedMediaKind`](../../../../../generated/storage/types.gen/type-aliases/LinkedMediaKind.md) \\| `undefined`; \\}\n\nSerialize the upload reference without credentials.\n\n#### Returns\n\n\\{ `filename`: `string` \\| `undefined`; `group`: `string`; `id`: `string`; `kind`: [`LinkedMediaKind`](../../../../../generated/storage/types.gen/type-aliases/LinkedMediaKind.md) \\| `undefined`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `filename` | `string` \\| `undefined` |\n| `group` | `string` |\n| `id` | `string` |\n| `kind` | [`LinkedMediaKind`](../../../../../generated/storage/types.gen/type-aliases/LinkedMediaKind.md) \\| `undefined` |\n\n***\n\n### byId()\n\n> `static` **byId**(`group`, `id`): `WhatsAppUpload`\n\nReference a previously staged upload in its original group.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `group` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) |\n| `id` | `string` |\n\n#### Returns\n\n`WhatsAppUpload`\n\n***\n\n### from()\n\n> `static` **from**(`group`, `record`): `WhatsAppUpload`\n\nSeed a handle from the server's upload receipt.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `group` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) |\n| `record` | [`LinkedUploadedAttachment`](../../../../../generated/storage/types.gen/type-aliases/LinkedUploadedAttachment.md) |\n\n#### Returns\n\n`WhatsAppUpload`\n"
+ "documentation": "# Macro SDK: channels\n\nGenerated by TypeDoc. Paths below refer to the canonical Markdown hierarchy. Other entity handles are documented in their named section; request core for shared SDK helpers.\n\n<!-- generated/properties/types.gen/type-aliases/BulkUpdateEntityPropertyOptionsResponse.md -->\n# Type Alias: BulkUpdateEntityPropertyOptionsResponse\n\n> **BulkUpdateEntityPropertyOptionsResponse** = \\{ `properties`: [`EntityPropertyOptionSelectionResponse`](EntityPropertyOptionSelectionResponse.md)[]; \\}\n\nResponse for a bulk option update: each property's reconciled final ids.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-properties\"></a> `properties` | [`EntityPropertyOptionSelectionResponse`](EntityPropertyOptionSelectionResponse.md)[] | The final option ids per updated property. |\n\n\n<!-- generated/properties/types.gen/type-aliases/DataType.md -->\n# Type Alias: DataType\n\n> **DataType** = `\"BOOLEAN\"` \\| `\"DATE\"` \\| `\"NUMBER\"` \\| `\"STRING\"` \\| `\"SELECT_NUMBER\"` \\| `\"SELECT_STRING\"` \\| `\"TAG\"` \\| `\"ENTITY\"` \\| `\"LINK\"`\n\nData type for property values, determining storage and validation.\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityProperty.md -->\n# Type Alias: EntityProperty\n\n> **EntityProperty** = \\{ `created_at`: `string`; `entity_id`: `string`; `entity_type`: [`EntityType`](EntityType.md); `id`: `string`; `property_definition_id`: `string`; `updated_at`: `string`; \\}\n\nAssignment of a property definition to a specific entity (service representation).\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-created_at\"></a> `created_at` | `string` |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` |\n| <a id=\"property-entity_type\"></a> `entity_type` | [`EntityType`](EntityType.md) |\n| <a id=\"property-id\"></a> `id` | `string` |\n| <a id=\"property-property_definition_id\"></a> `property_definition_id` | `string` |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` |\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityPropertyOptionSelectionResponse.md -->\n# Type Alias: EntityPropertyOptionSelectionResponse\n\n> **EntityPropertyOptionSelectionResponse** = \\{ `option_ids`: `string`[]; `property_id`: `string`; \\}\n\nThe reconciled final option ids stored for one property after a bulk update.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-option_ids\"></a> `option_ids` | `string`[] | The final option ids the server persisted, in stored order. |\n| <a id=\"property-property_id\"></a> `property_id` | `string` | The property definition the options belong to. |\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityPropertyWithDefinition.md -->\n# Type Alias: EntityPropertyWithDefinition\n\n> **EntityPropertyWithDefinition** = \\{ `definition`: [`PropertyDefinition`](PropertyDefinition.md); `options?`: [`PropertyOption`](PropertyOption.md)[] \\| `null`; `property`: [`EntityProperty`](EntityProperty.md); `value?`: `null` \\| [`PropertyValue`](PropertyValue.md); \\}\n\nEntity property with its definition, value, and options (service representation).\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-definition\"></a> `definition` | [`PropertyDefinition`](PropertyDefinition.md) |\n| <a id=\"property-options\"></a> `options?` | [`PropertyOption`](PropertyOption.md)[] \\| `null` |\n| <a id=\"property-property\"></a> `property` | [`EntityProperty`](EntityProperty.md) |\n| <a id=\"property-value\"></a> `value?` | `null` \\| [`PropertyValue`](PropertyValue.md) |\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityReference.md -->\n# Type Alias: EntityReference\n\n> **EntityReference** = \\{ `entity_id`: `string`; `entity_type`: [`EntityType`](EntityType.md); `specific_message_id?`: `string` \\| `null`; \\}\n\nEntity reference for entity-type property values.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` | - |\n| <a id=\"property-entity_type\"></a> `entity_type` | [`EntityType`](EntityType.md) | - |\n| <a id=\"property-specific_message_id\"></a> `specific_message_id?` | `string` \\| `null` | For CHANNEL, CHAT, THREAD entity types - optional specific message ID. This allows referencing a specific message within a thread/channel/chat. |\n\n\n<!-- generated/properties/types.gen/type-aliases/EntityType.md -->\n# Type Alias: EntityType\n\n> **EntityType** = `\"CALENDAR_EVENT\"` \\| `\"CALL_RECORD\"` \\| `\"CHANNEL\"` \\| `\"CHAT\"` \\| `\"COMPANY\"` \\| `\"DATABASE_ROW\"` \\| `\"CONTACT\"` \\| `\"DOCUMENT\"` \\| `\"INITIATIVE\"` \\| `\"PROJECT\"` \\| `\"TASK\"` \\| `\"THREAD\"` \\| `\"USER\"`\n\nType of entity that can be referenced by entity properties.\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyDefinition.md -->\n# Type Alias: PropertyDefinition\n\n> **PropertyDefinition** = \\{ `created_at`: `string`; `data_type`: [`DataType`](DataType.md); `display_name`: `string`; `id`: `string`; `is_metadata`: `boolean`; `is_multi_select`: `boolean`; `is_system`: `boolean`; `owner`: [`PropertyOwner`](PropertyOwner.md); `specific_entity_type`: `null` \\| [`EntityType`](EntityType.md); `updated_at`: `string`; \\}\n\nProperty definition model (service representation).\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | - |\n| <a id=\"property-data_type\"></a> `data_type` | [`DataType`](DataType.md) | - |\n| <a id=\"property-display_name\"></a> `display_name` | `string` | - |\n| <a id=\"property-id\"></a> `id` | `string` | - |\n| <a id=\"property-is_metadata\"></a> `is_metadata` | `boolean` | Flag to indicate if this is a system-generated metadata property. Not stored in database - computed at service layer. |\n| <a id=\"property-is_multi_select\"></a> `is_multi_select` | `boolean` | - |\n| <a id=\"property-is_system\"></a> `is_system` | `boolean` | Flag to indicate if this is a system property (stored in DB). |\n| <a id=\"property-owner\"></a> `owner` | [`PropertyOwner`](PropertyOwner.md) | - |\n| <a id=\"property-specific_entity_type\"></a> `specific_entity_type` | `null` \\| [`EntityType`](EntityType.md) | - |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` | - |\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyOption.md -->\n# Type Alias: PropertyOption\n\n> **PropertyOption** = \\{ `color`: `string` \\| `null`; `created_at`: `string`; `display_order`: `number`; `id`: `string`; `property_definition_id`: `string`; `updated_at`: `string`; `value`: [`PropertyOptionValue`](PropertyOptionValue.md); \\}\n\nA selectable option for select-type properties (service representation).\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-color\"></a> `color` | `string` \\| `null` |\n| <a id=\"property-created_at\"></a> `created_at` | `string` |\n| <a id=\"property-display_order\"></a> `display_order` | `number` |\n| <a id=\"property-id\"></a> `id` | `string` |\n| <a id=\"property-property_definition_id\"></a> `property_definition_id` | `string` |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` |\n| <a id=\"property-value\"></a> `value` | [`PropertyOptionValue`](PropertyOptionValue.md) |\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyOptionValue.md -->\n# Type Alias: PropertyOptionValue\n\n> **PropertyOptionValue** = \\{ `type`: `\"string\"`; `value`: `string`; \\} \\| \\{ `type`: `\"number\"`; `value`: `number`; \\}\n\nThe value of a property option - either a string or a number.\n\n## Union Members\n\n### Type Literal\n\n\\{ `type`: `\"string\"`; `value`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"string\"` | - |\n| `value` | `string` | String value for SelectString properties |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"number\"`; `value`: `number`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"number\"` | - |\n| `value` | `number` | Number value for SelectNumber properties |\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyOwner.md -->\n# Type Alias: PropertyOwner\n\n> **PropertyOwner** = \\{ `scope`: `\"user\"`; `user_id`: `string`; \\} \\| \\{ `scope`: `\"team\"`; `team_id`: `string`; \\} \\| \\{ `database_id`: `string`; `scope`: `\"database\"`; \\} \\| \\{ `scope`: `\"system\"`; \\}\n\nDefines who owns a property - user-scoped, team-scoped, database-scoped, or system.\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyTargetEntityType.md -->\n# Type Alias: PropertyTargetEntityType\n\n> **PropertyTargetEntityType** = `\"CALL_RECORD\"` \\| `\"CHANNEL\"` \\| `\"CHAT\"` \\| `\"COMPANY\"` \\| `\"DATABASE_ROW\"` \\| `\"DOCUMENT\"` \\| `\"INITIATIVE\"` \\| `\"PROJECT\"` \\| `\"THREAD\"` \\| `\"USER\"`\n\nCanonical type of an entity receiving properties.\n\nTasks are documents at API boundaries. `Task` intentionally does not exist\nhere; task classification is resolved by the properties domain from the\ndocument subtype.\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyTargetReference.md -->\n# Type Alias: PropertyTargetReference\n\n> **PropertyTargetReference** = \\{ `entity_id`: `string`; `entity_type`: [`PropertyTargetEntityType`](PropertyTargetEntityType.md); \\}\n\nCanonical reference to an entity receiving properties.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` | Entity identifier. |\n| <a id=\"property-entity_type\"></a> `entity_type` | [`PropertyTargetEntityType`](PropertyTargetEntityType.md) | Canonical entity type. |\n\n\n<!-- generated/properties/types.gen/type-aliases/PropertyValue.md -->\n# Type Alias: PropertyValue\n\n> **PropertyValue** = \\{ `type`: `\"Boolean\"`; `value`: `boolean`; \\} \\| \\{ `type`: `\"Number\"`; `value`: `number`; \\} \\| \\{ `type`: `\"String\"`; `value`: `string`; \\} \\| \\{ `type`: `\"Date\"`; `value`: `string`; \\} \\| \\{ `type`: `\"SelectOption\"`; `value`: `string`[]; \\} \\| \\{ `type`: `\"EntityReference\"`; `value`: [`EntityReference`](EntityReference.md)[]; \\} \\| \\{ `type`: `\"Link\"`; `value`: `string`[]; \\}\n\nProperty value (service representation).\n\nRepresents the actual value stored for an entity property.\nThis is serialized to/from JSONB in the database.\n\n## Union Members\n\n### Type Literal\n\n\\{ `type`: `\"Boolean\"`; `value`: `boolean`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"Boolean\"` | - |\n| `value` | `boolean` | Boolean value Serializes as: {\"type\": \"Boolean\", \"value\": true} |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"Number\"`; `value`: `number`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"Number\"` | - |\n| `value` | `number` | Numeric value Serializes as: {\"type\": \"Number\", \"value\": 42.5} |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"String\"`; `value`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"String\"` | - |\n| `value` | `string` | String value Serializes as: {\"type\": \"String\", \"value\": \"text\"} |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"Date\"`; `value`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"Date\"` | - |\n| `value` | `string` | Date/timestamp value Serializes as: {\"type\": \"Date\", \"value\": \"2025-01-01T00:00:00Z\"} |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"SelectOption\"`; `value`: `string`[]; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"SelectOption\"` | - |\n| `value` | `string`[] | Select option(s) - always an array (check is_multi_select to determine if single or multi) Single-select: {\"type\": \"SelectOption\", \"value\": [\"uuid\"]} (length 0 or 1) Multi-select: {\"type\": \"SelectOption\", \"value\": [\"uuid1\", \"uuid2\", ...]} (length 0+) |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"EntityReference\"`; `value`: [`EntityReference`](EntityReference.md)[]; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"EntityReference\"` | - |\n| `value` | [`EntityReference`](EntityReference.md)[] | Entity reference(s) - always an array (check is_multi_select to determine if single or multi) Single-select: {\"type\": \"EntityReference\", \"value\": [{...}]} (length 0 or 1) Multi-select: {\"type\": \"EntityReference\", \"value\": [{...}, {...}, ...]} (length 0+) |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"Link\"`; `value`: `string`[]; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `type` | `\"Link\"` | - |\n| `value` | `string`[] | Link value(s) - always an array (check is_multi_select to determine if single or multi) Single-select: {\"type\": \"Link\", \"value\": [\"https://example.com\"]} (length 0 or 1) Multi-select: {\"type\": \"Link\", \"value\": [\"https://example.com\", \"https://other.com\"]} (length 0+) |\n\n\n<!-- generated/properties/types.gen/type-aliases/SetPropertyValue.md -->\n# Type Alias: SetPropertyValue\n\n> **SetPropertyValue** = \\{ `type`: `\"boolean\"`; `value`: `boolean`; \\} \\| \\{ `type`: `\"date\"`; `value`: `string`; \\} \\| \\{ `type`: `\"number\"`; `value`: `number`; \\} \\| \\{ `type`: `\"string\"`; `value`: `string`; \\} \\| \\{ `option_id`: `string`; `type`: `\"select_option\"`; \\} \\| \\{ `option_ids`: `string`[]; `type`: `\"multi_select_option\"`; \\} \\| \\{ `reference`: [`EntityReference`](EntityReference.md); `type`: `\"entity_reference\"`; \\} \\| \\{ `references`: [`EntityReference`](EntityReference.md)[]; `type`: `\"multi_entity_reference\"`; \\} \\| \\{ `type`: `\"link\"`; `url`: `string`; \\} \\| \\{ `type`: `\"multi_link\"`; `urls`: `string`[]; \\}\n\nType-safe enum for setting entity property values - provides compile-time validation.\n\n\n<!-- generated/storage/types.gen/type-aliases/AccessLevel.md -->\n# Type Alias: AccessLevel\n\n> **AccessLevel** = `\"view\"` \\| `\"comment\"` \\| `\"edit\"` \\| `\"owner\"`\n\nOrdered from least to most access top -> bottom\n\n\n<!-- generated/storage/types.gen/type-aliases/ActivityType.md -->\n# Type Alias: ActivityType\n\n> **ActivityType** = `\"view\"` \\| `\"interact\"`\n\nThe kind of activity a user performs in a channel.\n\n\n<!-- generated/storage/types.gen/type-aliases/ApiActivity.md -->\n# Type Alias: ApiActivity\n\n> **ApiActivity** = \\{ `channel_id`: `string`; `created_at`: `string`; `id`: `string`; `interacted_at?`: `string` \\| `null`; `updated_at`: `string`; `user_id`: `string`; `viewed_at?`: `string` \\| `null`; \\}\n\nA user's activity (view/interaction) within a channel.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-channel_id\"></a> `channel_id` | `string` | Channel id. |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | When the activity row was created. |\n| <a id=\"property-id\"></a> `id` | `string` | Activity id. |\n| <a id=\"property-interacted_at\"></a> `interacted_at?` | `string` \\| `null` | The last time the user interacted with the channel. |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` | When the activity row was last updated. |\n| <a id=\"property-user_id\"></a> `user_id` | `string` | User id. |\n| <a id=\"property-viewed_at\"></a> `viewed_at?` | `string` \\| `null` | The last time the user viewed the channel. |\n\n\n<!-- generated/storage/types.gen/type-aliases/ApiChannelAttachment.md -->\n# Type Alias: ApiChannelAttachment\n\n> **ApiChannelAttachment** = \\{ `channel_id`: `string`; `created_at`: `string`; `entity_id`: `string`; `entity_type`: `string`; `height?`: `number` \\| `null`; `id`: `string`; `message_id`: `string`; `sender_id`: `string`; `width?`: `number` \\| `null`; \\}\n\nA channel-level attachment.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-channel_id\"></a> `channel_id` | `string` | Channel id. |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | When the attachment was created. |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` | Entity id. |\n| <a id=\"property-entity_type\"></a> `entity_type` | `string` | Type of entity. |\n| <a id=\"property-height\"></a> `height?` | `number` \\| `null` | Height (for images). |\n| <a id=\"property-id\"></a> `id` | `string` | Attachment id. |\n| <a id=\"property-message_id\"></a> `message_id` | `string` | Message id this attachment belongs to. |\n| <a id=\"property-sender_id\"></a> `sender_id` | `string` | The user who sent the message containing this attachment. |\n| <a id=\"property-width\"></a> `width?` | `number` \\| `null` | Width (for images). |\n\n\n<!-- generated/storage/types.gen/type-aliases/ApiChannelAttachmentsPage.md -->\n# Type Alias: ApiChannelAttachmentsPage\n\n> **ApiChannelAttachmentsPage** = \\{ `items`: [`ApiChannelAttachment`](ApiChannelAttachment.md)[]; `next_cursor?`: `string` \\| `null`; \\}\n\nPaginated response of channel attachments.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-items\"></a> `items` | [`ApiChannelAttachment`](ApiChannelAttachment.md)[] | Attachments on this page. |\n| <a id=\"property-next_cursor\"></a> `next_cursor?` | `string` \\| `null` | Cursor for the next page, null if no more pages. |\n\n\n<!-- generated/storage/types.gen/type-aliases/ApiChannelDetail.md -->\n# Type Alias: ApiChannelDetail\n\n> **ApiChannelDetail** = \\{ `channel_id`: `string`; `channel_name`: `string`; `channel_type`: [`ChannelType`](ChannelType.md); `participants`: [`ApiChannelParticipant`](ApiChannelParticipant.md)[]; \\}\n\nChannel detail: metadata and active participants.\n\nMessages are read through `/messages/channel/{channel_id}`.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-channel_id\"></a> `channel_id` | `string` | Channel id. |\n| <a id=\"property-channel_name\"></a> `channel_name` | `string` | Resolved display name from the viewer's perspective. |\n| <a id=\"property-channel_type\"></a> `channel_type` | [`ChannelType`](ChannelType.md) | Channel type. |\n| <a id=\"property-participants\"></a> `participants` | [`ApiChannelParticipant`](ApiChannelParticipant.md)[] | Active participants. |\n\n\n<!-- generated/storage/types.gen/type-aliases/ApiChannelParticipant.md -->\n# Type Alias: ApiChannelParticipant\n\n> **ApiChannelParticipant** = \\{ `channel_id`: `string`; `joined_at`: `string`; `role`: [`ApiParticipantRole`](ApiParticipantRole.md); `user_id`: `string`; \\}\n\nA channel participant.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-channel_id\"></a> `channel_id` | `string` | Channel id. |\n| <a id=\"property-joined_at\"></a> `joined_at` | `string` | When the user joined. |\n| <a id=\"property-role\"></a> `role` | [`ApiParticipantRole`](ApiParticipantRole.md) | Role in the channel. |\n| <a id=\"property-user_id\"></a> `user_id` | `string` | User id. |\n\n\n<!-- generated/storage/types.gen/type-aliases/ApiParticipantRole.md -->\n# Type Alias: ApiParticipantRole\n\n> **ApiParticipantRole** = `\"owner\"` \\| `\"admin\"` \\| `\"member\"`\n\nParticipant role in a channel.\n\n\n<!-- generated/storage/types.gen/type-aliases/BotSenderProfile.md -->\n# Type Alias: BotSenderProfile\n\n> **BotSenderProfile** = \\{ `avatar_url?`: `string` \\| `null`; `name`: `string`; \\}\n\nPublic bot profile attached to bot-authored messages.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-avatar_url\"></a> `avatar_url?` | `string` \\| `null` | Bot avatar URL. |\n| <a id=\"property-name\"></a> `name` | `string` | Bot display name. |\n\n\n<!-- generated/storage/types.gen/type-aliases/ChannelLabel.md -->\n# Type Alias: ChannelLabel\n\n> **ChannelLabel** = \\{ `channelCount`: `number`; `channelIds`: `string`[]; `createdAt`: `string`; `id`: `string`; `name`: `string`; `rule?`: `null` \\| [`ChannelLabelRule`](ChannelLabelRule.md); `sortOrder`: `number`; `teamId?`: `string` \\| `null`; `updatedAt`: `string`; \\}\n\nA shared or account-private label grouping chat channels in the sidebar.\n\n`channel_ids` is viewer-relative: it lists only the labelled channels the\nrequesting user participates in. `channel_count` counts every channel in\nthe label so clients can warn accurately before a delete.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-channelcount\"></a> `channelCount` | `number` | All assignments for a manual label; visible matches for a smart tag. |\n| <a id=\"property-channelids\"></a> `channelIds` | `string`[] | Channels in this label that the requesting user participates in. |\n| <a id=\"property-createdat\"></a> `createdAt` | `string` | When the label was created. |\n| <a id=\"property-id\"></a> `id` | `string` | Stable label id. |\n| <a id=\"property-name\"></a> `name` | `string` | Display name, unique within the scope (case-insensitive). |\n| <a id=\"property-rule\"></a> `rule?` | `null` \\| [`ChannelLabelRule`](ChannelLabelRule.md) | - |\n| <a id=\"property-sortorder\"></a> `sortOrder` | `number` | Manual ordering value within the scope; lower sorts first. |\n| <a id=\"property-teamid\"></a> `teamId?` | `string` \\| `null` | Owning team, or `None` for account-private labels. |\n| <a id=\"property-updatedat\"></a> `updatedAt` | `string` | When the label was last renamed or reordered. |\n\n\n<!-- generated/storage/types.gen/type-aliases/ChannelLabelRule.md -->\n# Type Alias: ChannelLabelRule\n\n> **ChannelLabelRule** = \\{ `attribute`: `\"name\"`; `contains`: `string`; \\}\n\nCase-insensitive, literal substring matching on the channel name.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attribute\"></a> `attribute` | `\"name\"` | - |\n| <a id=\"property-contains\"></a> `contains` | `string` | The substring to find anywhere in the name. |\n\n\n<!-- generated/storage/types.gen/type-aliases/ChannelSharePermission.md -->\n# Type Alias: ChannelSharePermission\n\n> **ChannelSharePermission** = \\{ `access_level`: [`AccessLevel`](AccessLevel.md); `channel_id`: `string`; \\}\n\nThe channel share permission\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-access_level\"></a> `access_level` | [`AccessLevel`](AccessLevel.md) | The access level for the channel |\n| <a id=\"property-channel_id\"></a> `channel_id` | `string` | The channel id |\n\n\n<!-- generated/storage/types.gen/type-aliases/ChannelType.md -->\n# Type Alias: ChannelType\n\n> **ChannelType** = `\"public\"` \\| `\"private\"` \\| `\"direct_message\"` \\| `\"team\"`\n\nType of channel.\n\n\n<!-- generated/storage/types.gen/type-aliases/CountedReaction.md -->\n# Type Alias: CountedReaction\n\n> **CountedReaction** = \\{ `emoji`: `string`; `users`: `string`[]; \\}\n\nReaction emoji and the users who added it.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-emoji\"></a> `emoji` | `string` | Emoji being reacted with. |\n| <a id=\"property-users\"></a> `users` | `string`[] | User identifiers. |\n\n\n<!-- generated/storage/types.gen/type-aliases/DocumentId.md -->\n# Type Alias: DocumentId\n\n> **DocumentId** = `string`\n\nA validated document identifier. Historical document ids need not be UUIDs.\n\n\n<!-- generated/storage/types.gen/type-aliases/EntityPermission.md -->\n# Type Alias: EntityPermission\n\n> **EntityPermission** = \\{ `access_level`: [`AccessLevel`](AccessLevel.md); `type`: `\"access_level\"`; \\} \\| \\{ `type`: `\"channel_view_only\"`; \\} \\| \\{ `role`: [`ParticipantRole`](ParticipantRole.md); `type`: `\"channel_role\"`; \\} \\| \\{ `role`: [`TeamRole`](TeamRole.md); `type`: `\"team_role\"`; \\}\n\nA user's permission for an entity, discriminated by entity kind.\n\nItems (documents, chats, projects, threads) use access levels.\nChannels use view-only permission or participant roles.\n\n## Union Members\n\n### Type Literal\n\n\\{ `access_level`: [`AccessLevel`](AccessLevel.md); `type`: `\"access_level\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `access_level` | [`AccessLevel`](AccessLevel.md) | The access level the user has. |\n| `type` | `\"access_level\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `type`: `\"channel_view_only\"`; \\}\n\n***\n\n### Type Literal\n\n\\{ `role`: [`ParticipantRole`](ParticipantRole.md); `type`: `\"channel_role\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `role` | [`ParticipantRole`](ParticipantRole.md) | The role the user has in the channel. |\n| `type` | `\"channel_role\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `role`: [`TeamRole`](TeamRole.md); `type`: `\"team_role\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `role` | [`TeamRole`](TeamRole.md) | The role the user has in the team. |\n| `type` | `\"team_role\"` | - |\n\n\n<!-- generated/storage/types.gen/type-aliases/GetChannelAttachmentsResponses.md -->\n# Type Alias: GetChannelAttachmentsResponses\n\n> **GetChannelAttachmentsResponses** = \\{ `200`: [`ApiChannelAttachmentsPage`](ApiChannelAttachmentsPage.md); \\}\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-200\"></a> `200` | [`ApiChannelAttachmentsPage`](ApiChannelAttachmentsPage.md) |\n\n\n<!-- generated/storage/types.gen/type-aliases/GetChannelParticipantsResponses.md -->\n# Type Alias: GetChannelParticipantsResponses\n\n> **GetChannelParticipantsResponses** = \\{ `200`: [`ApiChannelParticipant`](ApiChannelParticipant.md)[]; \\}\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-200\"></a> `200` | [`ApiChannelParticipant`](ApiChannelParticipant.md)[] |\n\n\n<!-- generated/storage/types.gen/type-aliases/ImportedAuthor.md -->\n# Type Alias: ImportedAuthor\n\n> **ImportedAuthor** = \\{ `name`: `string`; \\}\n\nDisplay attribution for a comment imported from an external document.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-name\"></a> `name` | `string` | Original author text; never interpreted as an authenticated principal. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkShare.md -->\n# Type Alias: LinkShare\n\n> **LinkShare** = `\"PUBLIC\"` \\| `\"TEAM\"`\n\nDefines who can access an item through its share link.\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedAccount.md -->\n# Type Alias: LinkedAccount\n\n> **LinkedAccount** = \\{ `authorizationGeneration`: `number`; `id`: `string`; `identityJid?`: `string` \\| `null`; `state`: [`LinkedAccountState`](LinkedAccountState.md); `userId`: `string`; \\}\n\nOne person's account, never owned by a workspace.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-authorizationgeneration\"></a> `authorizationGeneration` | `number` | Explicit consent generation; reconnecting a socket never changes it. |\n| <a id=\"property-id\"></a> `id` | `string` | Stable account identity. |\n| <a id=\"property-identityjid\"></a> `identityJid?` | `string` \\| `null` | WhatsApp-verified identity, absent until the first pairing succeeds. |\n| <a id=\"property-state\"></a> `state` | [`LinkedAccountState`](LinkedAccountState.md) | Lifecycle. |\n| <a id=\"property-userid\"></a> `userId` | `string` | Authenticated owner. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedAccountState.md -->\n# Type Alias: LinkedAccountState\n\n> **LinkedAccountState** = `\"pairing\"` \\| `\"connected\"` \\| `\"logged_out\"` \\| `\"disconnected\"`\n\nAccount lifecycle. Transport outages are not stored: a connected account\nstays connected while its session service reconnects.\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedAttachment.md -->\n# Type Alias: LinkedAttachment\n\n> **LinkedAttachment** = \\{ `documentId?`: `string` \\| `null`; `durationSeconds?`: `number` \\| `null`; `fileName`: `string`; `height?`: `number` \\| `null`; `mime`: `string`; `ordinal`: `number`; `presentation?`: `null` \\| [`LinkedMediaPresentation`](LinkedMediaPresentation.md); `size`: `number`; `state`: [`LinkedAttachmentState`](LinkedAttachmentState.md); `width?`: `number` \\| `null`; \\}\n\nOne attachment of a linked message.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-documentid\"></a> `documentId?` | `string` \\| `null` | The private document, once ready. |\n| <a id=\"property-durationseconds\"></a> `durationSeconds?` | `number` \\| `null` | Length of audio or video in whole seconds, when declared. |\n| <a id=\"property-filename\"></a> `fileName` | `string` | Display filename. |\n| <a id=\"property-height\"></a> `height?` | `number` \\| `null` | Pixel height, when declared. |\n| <a id=\"property-mime\"></a> `mime` | `string` | Declared MIME type. |\n| <a id=\"property-ordinal\"></a> `ordinal` | `number` | Position within the message. |\n| <a id=\"property-presentation\"></a> `presentation?` | `null` \\| [`LinkedMediaPresentation`](LinkedMediaPresentation.md) | - |\n| <a id=\"property-size\"></a> `size` | `number` | Declared size in bytes. |\n| <a id=\"property-state\"></a> `state` | [`LinkedAttachmentState`](LinkedAttachmentState.md) | Current state. |\n| <a id=\"property-width\"></a> `width?` | `number` \\| `null` | Pixel width of an image, sticker or video, when WhatsApp declared it. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedAttachmentState.md -->\n# Type Alias: LinkedAttachmentState\n\n> **LinkedAttachmentState** = `\"loading\"` \\| `\"ready\"` \\| `\"unavailable\"` \\| `\"unsupported\"`\n\nWhere an attachment of a linked message stands.\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedBackfill.md -->\n# Type Alias: LinkedBackfill\n\n> **LinkedBackfill** = \\{ `imported`: `number`; `state`: [`LinkedBackfillState`](LinkedBackfillState.md); \\}\n\nEarlier messages imported after adding a group.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-imported\"></a> `imported` | `number` | Messages received from the phone so far (including ones already shown). |\n| <a id=\"property-state\"></a> `state` | [`LinkedBackfillState`](LinkedBackfillState.md) | Progress. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedBackfillState.md -->\n# Type Alias: LinkedBackfillState\n\n> **LinkedBackfillState** = `\"waiting_for_message\"` \\| `\"pending\"` \\| `\"running\"` \\| `\"waiting_for_phone\"` \\| `\"done\"` \\| `\"partial\"`\n\nWhere importing a group's earlier messages stands.\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedCannotAdd.md -->\n# Type Alias: LinkedCannotAdd\n\n> **LinkedCannotAdd** = `\"not_in_group\"` \\| `\"community\"` \\| `\"own_chat\"` \\| `\"not_in_chat_list\"`\n\nWhy a chat can't be added to Macro; the app words it from the code.\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedCapabilities.md -->\n# Type Alias: LinkedCapabilities\n\n> **LinkedCapabilities** = \\{ `attachmentLimitBytes`: `number`; `attachmentTypes`: `string`[]; `maxAttachments`: `number`; `mutations`: [`LinkedMutation`](LinkedMutation.md)[]; `mutationWindowSeconds`: `number`; `textLimitBytes`: `number`; \\}\n\nOperations implemented for linked groups, independent of current permission.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attachmentlimitbytes\"></a> `attachmentLimitBytes` | `number` | Largest attachment in bytes. |\n| <a id=\"property-attachmenttypes\"></a> `attachmentTypes` | `string`[] | Supported attachment MIME types. |\n| <a id=\"property-maxattachments\"></a> `maxAttachments` | `number` | Attachments per send. |\n| <a id=\"property-mutations\"></a> `mutations` | [`LinkedMutation`](LinkedMutation.md)[] | Supported message operations. |\n| <a id=\"property-mutationwindowseconds\"></a> `mutationWindowSeconds` | `number` | Edits and deletes are offered this long after sending. |\n| <a id=\"property-textlimitbytes\"></a> `textLimitBytes` | `number` | Maximum UTF-8 bytes per text send. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedChat.md -->\n# Type Alias: LinkedChat\n\n> **LinkedChat** = \\{ `archived`: `boolean`; `canAdd`: `boolean`; `cannotAddReason?`: `null` \\| [`LinkedCannotAdd`](LinkedCannotAdd.md); `community?`: `null` \\| [`LinkedCommunityReference`](LinkedCommunityReference.md); `group?`: `null` \\| [`LinkedGroupReference`](LinkedGroupReference.md); `jid`: `string`; `kind`: [`LinkedChatKind`](LinkedChatKind.md); `lastActivityAt?`: `string` \\| `null`; `name`: `string`; `pinned`: `boolean`; `shared?`: `null` \\| [`LinkedSharedGroupReference`](LinkedSharedGroupReference.md); \\}\n\nOne chat of the caller's WhatsApp chat list, as WhatsApp Web lists it.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-archived\"></a> `archived` | `boolean` | Archived in WhatsApp. |\n| <a id=\"property-canadd\"></a> `canAdd` | `boolean` | \"Add to Macro\" works now. |\n| <a id=\"property-cannotaddreason\"></a> `cannotAddReason?` | `null` \\| [`LinkedCannotAdd`](LinkedCannotAdd.md) | - |\n| <a id=\"property-community\"></a> `community?` | `null` \\| [`LinkedCommunityReference`](LinkedCommunityReference.md) | - |\n| <a id=\"property-group\"></a> `group?` | `null` \\| [`LinkedGroupReference`](LinkedGroupReference.md) | - |\n| <a id=\"property-jid\"></a> `jid` | `string` | WhatsApp chat JID: a group, or the other person's phone-number JID (LID when WhatsApp never told us the number). |\n| <a id=\"property-kind\"></a> `kind` | [`LinkedChatKind`](LinkedChatKind.md) | Group or direct chat. |\n| <a id=\"property-lastactivityat\"></a> `lastActivityAt?` | `string` \\| `null` | Newest activity WhatsApp reported (message or history sync); `null` when unknown. The list is sorted by it, newest first, unknown last. |\n| <a id=\"property-name\"></a> `name` | `string` | Group: the subject, or member names for an unnamed group. Direct: the contact or WhatsApp name, else `+<phone>`. Always non-empty. |\n| <a id=\"property-pinned\"></a> `pinned` | `boolean` | Pinned in WhatsApp. |\n| <a id=\"property-shared\"></a> `shared?` | `null` \\| [`LinkedSharedGroupReference`](LinkedSharedGroupReference.md) | - |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedChatKind.md -->\n# Type Alias: LinkedChatKind\n\n> **LinkedChatKind** = `\"group\"` \\| `\"direct\"`\n\nWhether a WhatsApp chat is a group or a one-to-one chat.\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedCommunityReference.md -->\n# Type Alias: LinkedCommunityReference\n\n> **LinkedCommunityReference** = \\{ `announcements`: `boolean`; `id`: `string`; `name`: `string`; \\}\n\nThe WhatsApp community a group belongs to.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-announcements\"></a> `announcements` | `boolean` | This group is the community's announcement group. |\n| <a id=\"property-id\"></a> `id` | `string` | The community's WhatsApp JID. |\n| <a id=\"property-name\"></a> `name` | `string` | The community's name. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedDeliveryState.md -->\n# Type Alias: LinkedDeliveryState\n\n> **LinkedDeliveryState** = `\"pending\"` \\| `\"sending\"` \\| `\"unknown\"` \\| `\"accepted\"` \\| `\"failed\"`\n\nObserved send state. `unknown` means the request may have reached WhatsApp;\nit is never sent again automatically.\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedGroupReference.md -->\n# Type Alias: LinkedGroupReference\n\n> **LinkedGroupReference** = \\{ `id`: `string`; `name`: `string`; \\}\n\nA group entity bound to a remote group.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `string` | Group entity id. |\n| <a id=\"property-name\"></a> `name` | `string` | Display name, following WhatsApp. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedMediaKind.md -->\n# Type Alias: LinkedMediaKind\n\n> **LinkedMediaKind** = `\"image\"` \\| `\"audio\"` \\| `\"video\"` \\| `\"document\"`\n\nAttachment categories WhatsApp distinguishes.\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedMediaPresentation.md -->\n# Type Alias: LinkedMediaPresentation\n\n> **LinkedMediaPresentation** = `\"sticker\"` \\| `\"gif\"` \\| `\"voice_note\"`\n\nHow WhatsApp shows an attachment, when not as a plain file of its kind.\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedMutation.md -->\n# Type Alias: LinkedMutation\n\n> **LinkedMutation** = `\"reaction\"` \\| `\"edit\"` \\| `\"delete\"`\n\nDeliberate operations on an existing linked-group message.\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedReplyBlock.md -->\n# Type Alias: LinkedReplyBlock\n\n> **LinkedReplyBlock** = `\"sending_disabled\"` \\| `\"no_account\"` \\| `\"disconnected\"` \\| `\"not_observing\"` \\| `\"not_allowed_in_group\"` \\| `\"group_unavailable\"`\n\nWhy the viewer cannot send now.\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedReplyContent.md -->\n# Type Alias: LinkedReplyContent\n\n> **LinkedReplyContent** = \\{ `mentions?`: `string`[]; `text`: `string`; `type`: `\"text\"`; \\} \\| \\{ `caption?`: `string` \\| `null`; `type`: `\"media\"`; `uploadId`: `string`; \\} \\| \\{ `messageId`: `string`; `operation`: [`LinkedMutation`](LinkedMutation.md); `text?`: `string` \\| `null`; `type`: `\"mutation\"`; \\}\n\nContent of a deliberate send.\n\n## Union Members\n\n### Type Literal\n\n\\{ `mentions?`: `string`[]; `text`: `string`; `type`: `\"text\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `mentions?` | `string`[] | Group participants the text @-mentions, by their WhatsApp id (`jid` of a roster participant); the text must contain `@<digits before the @ of the id>` for each. |\n| `text` | `string` | UTF-8 text, at most [`TEXT_LIMIT_BYTES`] bytes. |\n| `type` | `\"text\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `caption?`: `string` \\| `null`; `type`: `\"media\"`; `uploadId`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `caption?` | `string` \\| `null` | Optional caption; audio has none. |\n| `type` | `\"media\"` | - |\n| `uploadId` | `string` | The staged upload, which becomes the message's private document. |\n\n***\n\n### Type Literal\n\n\\{ `messageId`: `string`; `operation`: [`LinkedMutation`](LinkedMutation.md); `text?`: `string` \\| `null`; `type`: `\"mutation\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `messageId` | `string` | Existing group message, resolved to its WhatsApp source by the server. |\n| `operation` | [`LinkedMutation`](LinkedMutation.md) | Explicit operation. |\n| `text?` | `string` \\| `null` | Replacement text or emoji; absent for delete, empty to remove a reaction. |\n| `type` | `\"mutation\"` | - |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedSendProgress.md -->\n# Type Alias: LinkedSendProgress\n\n> **LinkedSendProgress** = \\{ `createdAt`: `string`; `errorCode?`: `string` \\| `null`; `groupId`: `string`; `id`: `string`; `messageId?`: `string` \\| `null`; `payload`: [`LinkedSendReply`](LinkedSendReply.md); `state`: [`LinkedDeliveryState`](LinkedDeliveryState.md); `userId`: `string`; \\}\n\nDurable result of a deliberate send.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-createdat\"></a> `createdAt` | `string` | Intent creation time. |\n| <a id=\"property-errorcode\"></a> `errorCode?` | `string` \\| `null` | Sanitized failure code. |\n| <a id=\"property-groupid\"></a> `groupId` | `string` | Group entity. |\n| <a id=\"property-id\"></a> `id` | `string` | Stable intent id. |\n| <a id=\"property-messageid\"></a> `messageId?` | `string` \\| `null` | Group message, once WhatsApp accepted it. |\n| <a id=\"property-payload\"></a> `payload` | [`LinkedSendReply`](LinkedSendReply.md) | The original request, so a failed draft can be recovered. |\n| <a id=\"property-state\"></a> `state` | [`LinkedDeliveryState`](LinkedDeliveryState.md) | Current state. |\n| <a id=\"property-userid\"></a> `userId` | `string` | Person who submitted it. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedSendReply.md -->\n# Type Alias: LinkedSendReply\n\n> **LinkedSendReply** = \\{ `idempotencyKey`: `string`; `message`: [`LinkedReplyContent`](LinkedReplyContent.md); `replyTo?`: `string` \\| `null`; \\}\n\nExplicit send action from a person. Only deliberate sends reach WhatsApp.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-idempotencykey\"></a> `idempotencyKey` | `string` | Stable client intent key. A changed payload with this key is a conflict. |\n| <a id=\"property-message\"></a> `message` | [`LinkedReplyContent`](LinkedReplyContent.md) | Content. |\n| <a id=\"property-replyto\"></a> `replyTo?` | `string` \\| `null` | Group message being quoted, within this group. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedSharedGroupReference.md -->\n# Type Alias: LinkedSharedGroupReference\n\n> **LinkedSharedGroupReference** = \\{ `id`: `string`; `name`: `string`; `ownerId`: `string`; \\}\n\nAnother person's group entity the caller can view.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `string` | Group entity id. |\n| <a id=\"property-name\"></a> `name` | `string` | Display name, following WhatsApp. |\n| <a id=\"property-ownerid\"></a> `ownerId` | `string` | Macro user who added the group and shared it. |\n\n\n<!-- generated/storage/types.gen/type-aliases/LinkedUploadedAttachment.md -->\n# Type Alias: LinkedUploadedAttachment\n\n> **LinkedUploadedAttachment** = \\{ `filename`: `string`; `kind`: [`LinkedMediaKind`](LinkedMediaKind.md); `uploadId`: `string`; \\}\n\nA staged attachment, sent only by a later deliberate send.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-filename\"></a> `filename` | `string` | Display filename. |\n| <a id=\"property-kind\"></a> `kind` | [`LinkedMediaKind`](LinkedMediaKind.md) | Category. |\n| <a id=\"property-uploadid\"></a> `uploadId` | `string` | Use as `upload_id` in a media send; also the future document id. |\n\n\n<!-- generated/storage/types.gen/type-aliases/Message.md -->\n# Type Alias: Message\n\n> **Message** = \\{ `attachments`: [`MessageAttachment`](MessageAttachment.md)[]; `bot_profile?`: `null` \\| [`BotSenderProfile`](BotSenderProfile.md); `content`: `string`; `created_at`: `string`; `deleted_at?`: `string` \\| `null`; `edited_at?`: `string` \\| `null`; `guest_name?`: `string` \\| `null`; `id`: `string`; `imported_author?`: `null` \\| [`ImportedAuthor`](ImportedAuthor.md); `mentions`: [`SimpleMention`](SimpleMention.md)[]; `parent`: [`MessageParent`](MessageParent.md); `reactions`: [`CountedReaction`](CountedReaction.md)[]; `sender_id`: `string`; `thread_id?`: `string` \\| `null`; `triggered_by?`: `string` \\| `null`; `updated_at`: `string`; \\}\n\nShared message representation for channel timelines and entity discussions.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attachments\"></a> `attachments` | [`MessageAttachment`](MessageAttachment.md)[] | Attached entities. |\n| <a id=\"property-bot_profile\"></a> `bot_profile?` | `null` \\| [`BotSenderProfile`](BotSenderProfile.md) | - |\n| <a id=\"property-content\"></a> `content` | `string` | Macro Markdown body. |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | Creation time. |\n| <a id=\"property-deleted_at\"></a> `deleted_at?` | `string` \\| `null` | Message tombstone, independent of thread deletion. |\n| <a id=\"property-edited_at\"></a> `edited_at?` | `string` \\| `null` | Last content edit, if any. |\n| <a id=\"property-guest_name\"></a> `guest_name?` | `string` \\| `null` | Display name of a verified call guest, retained after the call ends. |\n| <a id=\"property-id\"></a> `id` | `string` | Message UUID. |\n| <a id=\"property-imported_author\"></a> `imported_author?` | `null` \\| [`ImportedAuthor`](ImportedAuthor.md) | - |\n| <a id=\"property-mentions\"></a> `mentions` | [`SimpleMention`](SimpleMention.md)[] | Tracked mentions, retained when a caller changes attachments only. |\n| <a id=\"property-parent\"></a> `parent` | [`MessageParent`](MessageParent.md) | Entity that owns this conversation. |\n| <a id=\"property-reactions\"></a> `reactions` | [`CountedReaction`](CountedReaction.md)[] | Aggregated reactions. |\n| <a id=\"property-sender_id\"></a> `sender_id` | `string` | Authenticated actor or owner of imported content. |\n| <a id=\"property-thread_id\"></a> `thread_id?` | `string` \\| `null` | Root message UUID for replies; absent on roots. |\n| <a id=\"property-triggered_by\"></a> `triggered_by?` | `string` \\| `null` | User who triggered a bot-authored message. |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` | Last persisted update. |\n\n\n<!-- generated/storage/types.gen/type-aliases/MessageAttachment.md -->\n# Type Alias: MessageAttachment\n\n> **MessageAttachment** = \\{ `created_at`: `string`; `entity_id`: `string`; `entity_type`: `string`; `height?`: `number` \\| `null`; `id`: `string`; `width?`: `number` \\| `null`; \\}\n\nAn entity attached to a message.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | When the attachment was added. |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` | Attached entity identifier. |\n| <a id=\"property-entity_type\"></a> `entity_type` | `string` | Attached entity type. |\n| <a id=\"property-height\"></a> `height?` | `number` \\| `null` | Optional media height. |\n| <a id=\"property-id\"></a> `id` | `string` | Attachment UUID. |\n| <a id=\"property-width\"></a> `width?` | `number` \\| `null` | Optional media width. |\n\n\n<!-- generated/storage/types.gen/type-aliases/MessageCursor.md -->\n# Type Alias: MessageCursor\n\n> **MessageCursor** = \\{ `created_at`: `string`; `id`: `string`; \\}\n\nCursor for a chronological parent timeline.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | Last message creation time or activity occurrence time. |\n| <a id=\"property-id\"></a> `id` | `string` | Last entry UUID, used to break timestamp ties across both sources. |\n\n\n<!-- generated/storage/types.gen/type-aliases/MessageParent.md -->\n# Type Alias: MessageParent\n\n> **MessageParent** = \\{ `id`: `string`; `type`: `\"channel\"`; \\} \\| \\{ `id`: [`DocumentId`](DocumentId.md); `type`: `\"document\"`; \\} \\| \\{ `id`: `string`; `type`: `\"initiative\"`; \\} \\| \\{ `id`: `string`; `type`: `\"crm_company\"`; \\} \\| \\{ `id`: `string`; `type`: `\"crm_contact\"`; \\} \\| \\{ `id`: `string`; `type`: `\"call\"`; \\}\n\nThe entity whose permissions and lifecycle govern a message.\n\n## Union Members\n\n### Type Literal\n\n\\{ `id`: `string`; `type`: `\"channel\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | A channel, including direct messages. |\n| `type` | `\"channel\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: [`DocumentId`](DocumentId.md); `type`: `\"document\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | [`DocumentId`](DocumentId.md) | A document, including tasks and PDFs. |\n| `type` | `\"document\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: `string`; `type`: `\"initiative\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | An initiative, presented as a project in the application. |\n| `type` | `\"initiative\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: `string`; `type`: `\"crm_company\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | A CRM company. |\n| `type` | `\"crm_company\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: `string`; `type`: `\"crm_contact\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | A CRM contact. |\n| `type` | `\"crm_contact\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: `string`; `type`: `\"call\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | A video call and its persistent chat thread. |\n| `type` | `\"call\"` | - |\n\n\n<!-- generated/storage/types.gen/type-aliases/ParticipantRole.md -->\n# Type Alias: ParticipantRole\n\n> **ParticipantRole** = `\"owner\"` \\| `\"admin\"` \\| `\"member\"`\n\nThe role a user has within a channel.\n\n\n<!-- generated/storage/types.gen/type-aliases/SharePermissionV2.md -->\n# Type Alias: SharePermissionV2\n\n> **SharePermissionV2** = \\{ `channelSharePermissions?`: [`ChannelSharePermission`](ChannelSharePermission.md)[] \\| `null`; `id`: `string`; `linkShare?`: `null` \\| [`LinkShare`](LinkShare.md); `linkShareAccessLevel?`: `null` \\| [`AccessLevel`](AccessLevel.md); `owner`: `string`; `teamShareAccessLevel?`: `null` \\| [`AccessLevel`](AccessLevel.md); \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-channelsharepermissions\"></a> `channelSharePermissions?` | [`ChannelSharePermission`](ChannelSharePermission.md)[] \\| `null` | The channel share permissions for the item |\n| <a id=\"property-id\"></a> `id` | `string` | The share permission id |\n| <a id=\"property-linkshare\"></a> `linkShare?` | `null` \\| [`LinkShare`](LinkShare.md) | - |\n| <a id=\"property-linkshareaccesslevel\"></a> `linkShareAccessLevel?` | `null` \\| [`AccessLevel`](AccessLevel.md) | - |\n| <a id=\"property-owner\"></a> `owner` | `string` | The owner of the item |\n| <a id=\"property-teamshareaccesslevel\"></a> `teamShareAccessLevel?` | `null` \\| [`AccessLevel`](AccessLevel.md) | - |\n\n\n<!-- generated/storage/types.gen/type-aliases/SimpleMention.md -->\n# Type Alias: SimpleMention\n\n> **SimpleMention** = \\{ `entity_id`: `string`; `entity_type`: `string`; \\}\n\nA mention tracked in a message body.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-entity_id\"></a> `entity_id` | `string` | Mentioned entity identifier. |\n| <a id=\"property-entity_type\"></a> `entity_type` | `string` | Mentioned entity type. |\n\n\n<!-- generated/storage/types.gen/type-aliases/SmartTagChannelMatch.md -->\n# Type Alias: SmartTagChannelMatch\n\n> **SmartTagChannelMatch** = \\{ `id`: `string`; `name`: `string`; \\}\n\nA channel visible to the caller that matches a smart tag rule.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `string` | Channel id. |\n| <a id=\"property-name\"></a> `name` | `string` | Channel display name. |\n\n\n<!-- generated/storage/types.gen/type-aliases/SmartTagPreview.md -->\n# Type Alias: SmartTagPreview\n\n> **SmartTagPreview** = \\{ `channels`: [`SmartTagChannelMatch`](SmartTagChannelMatch.md)[]; `totalCount`: `number`; \\}\n\nA bounded preview and the total number of visible channels matching a rule.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-channels\"></a> `channels` | [`SmartTagChannelMatch`](SmartTagChannelMatch.md)[] | First matches, in alphabetical order. |\n| <a id=\"property-totalcount\"></a> `totalCount` | `number` | Number of matching channels the caller participates in, including overflow. |\n\n\n<!-- generated/storage/types.gen/type-aliases/TeamRole.md -->\n# Type Alias: TeamRole\n\n> **TeamRole** = `\"member\"` \\| `\"admin\"` \\| `\"owner\"`\n\nThe role a user has within a team.\n\nOrdered least to most privileged so comparisons reflect access strength.\n\n\n<!-- generated/storage/types.gen/type-aliases/UpdateChannelSharePermission.md -->\n# Type Alias: UpdateChannelSharePermission\n\n> **UpdateChannelSharePermission** = \\{ `accessLevel?`: `null` \\| [`AccessLevel`](AccessLevel.md); `channelId`: `string`; `operation`: [`UpdateOperation`](UpdateOperation.md); \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-accesslevel\"></a> `accessLevel?` | `null` \\| [`AccessLevel`](AccessLevel.md) | - |\n| <a id=\"property-channelid\"></a> `channelId` | `string` | The channel id |\n| <a id=\"property-operation\"></a> `operation` | [`UpdateOperation`](UpdateOperation.md) | The type of operation to be performed on the chanel share permission You can add, remove or replace and existing permission |\n\n\n<!-- generated/storage/types.gen/type-aliases/UpdateOperation.md -->\n# Type Alias: UpdateOperation\n\n> **UpdateOperation** = `\"add\"` \\| `\"remove\"` \\| `\"replace\"`\n\n\n<!-- generated/storage/types.gen/type-aliases/UpdateSharePermissionRequestV2.md -->\n# Type Alias: UpdateSharePermissionRequestV2\n\n> **UpdateSharePermissionRequestV2** = \\{ `channelSharePermissions?`: [`UpdateChannelSharePermission`](UpdateChannelSharePermission.md)[] \\| `null`; `linkShare?`: `null` \\| [`LinkShare`](LinkShare.md); `linkShareAccessLevel?`: `null` \\| [`AccessLevel`](AccessLevel.md); `teamShareAccessLevel?`: `null` \\| [`AccessLevel`](AccessLevel.md); \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-channelsharepermissions\"></a> `channelSharePermissions?` | [`UpdateChannelSharePermission`](UpdateChannelSharePermission.md)[] \\| `null` | Any channel share permissions to be created/updated/removed |\n| <a id=\"property-linkshare\"></a> `linkShare?` | `null` \\| [`LinkShare`](LinkShare.md) | - |\n| <a id=\"property-linkshareaccesslevel\"></a> `linkShareAccessLevel?` | `null` \\| [`AccessLevel`](AccessLevel.md) | - |\n| <a id=\"property-teamshareaccesslevel\"></a> `teamShareAccessLevel?` | `null` \\| [`AccessLevel`](AccessLevel.md) | - |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppCall.md -->\n# Type Alias: WhatsAppCall\n\n> **WhatsAppCall** = \\{ `durationSeconds?`: `number` \\| `null`; `outcome`: [`WhatsAppCallOutcome`](WhatsAppCallOutcome.md); `video`: `boolean`; \\}\n\nA call in the group.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-durationseconds\"></a> `durationSeconds?` | `number` \\| `null` | Length, when it connected. |\n| <a id=\"property-outcome\"></a> `outcome` | [`WhatsAppCallOutcome`](WhatsAppCallOutcome.md) | How it went for the account that saw it. |\n| <a id=\"property-video\"></a> `video` | `boolean` | Video rather than voice. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppCallOutcome.md -->\n# Type Alias: WhatsAppCallOutcome\n\n> **WhatsAppCallOutcome** = `\"answered\"` \\| `\"missed\"` \\| `\"rejected\"` \\| `\"other\"`\n\nHow a call went.\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppContactCard.md -->\n# Type Alias: WhatsAppContactCard\n\n> **WhatsAppContactCard** = \\{ `name`: `string`; `phones`: `string`[]; \\}\n\nOne contact card, from its vCard.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-name\"></a> `name` | `string` | Display name. |\n| <a id=\"property-phones\"></a> `phones` | `string`[] | Phone numbers as written on the card. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppContacts.md -->\n# Type Alias: WhatsAppContacts\n\n> **WhatsAppContacts** = \\{ `contacts`: [`WhatsAppContactCard`](WhatsAppContactCard.md)[]; \\}\n\nContact cards.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-contacts\"></a> `contacts` | [`WhatsAppContactCard`](WhatsAppContactCard.md)[] | The cards, in order. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppEvent.md -->\n# Type Alias: WhatsAppEvent\n\n> **WhatsAppEvent** = \\{ `canceled?`: `boolean`; `description?`: `string` \\| `null`; `endAt?`: `string` \\| `null`; `joinLink?`: `string` \\| `null`; `location?`: `string` \\| `null`; `name`: `string`; `startAt?`: `string` \\| `null`; \\}\n\nA WhatsApp event.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-canceled\"></a> `canceled?` | `boolean` | Canceled by its organizer. |\n| <a id=\"property-description\"></a> `description?` | `string` \\| `null` | Description. |\n| <a id=\"property-endat\"></a> `endAt?` | `string` \\| `null` | End. |\n| <a id=\"property-joinlink\"></a> `joinLink?` | `string` \\| `null` | Call link for an online event. |\n| <a id=\"property-location\"></a> `location?` | `string` \\| `null` | Place name or address. |\n| <a id=\"property-name\"></a> `name` | `string` | Title. |\n| <a id=\"property-startat\"></a> `startAt?` | `string` \\| `null` | Start. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppGroupDetail.md -->\n# Type Alias: WhatsAppGroupDetail\n\n> **WhatsAppGroupDetail** = [`WhatsAppGroupSummary`](WhatsAppGroupSummary.md) & \\{ `accessLevel`: [`AccessLevel`](AccessLevel.md); `disappearingSeconds?`: `number` \\| `null`; `limits`: [`LinkedCapabilities`](LinkedCapabilities.md); `roster?`: `null` \\| [`WhatsAppRoster`](WhatsAppRoster.md); `sendingIdentity?`: `string` \\| `null`; `sharePermission`: [`SharePermissionV2`](SharePermissionV2.md); \\}\n\nFull group detail and current viewer capabilities.\n\n## Type Declaration\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `accessLevel` | [`AccessLevel`](AccessLevel.md) | Caller's effective permission. |\n| `disappearingSeconds?` | `number` \\| `null` | WhatsApp's disappearing-messages timer in seconds while it is on; Macro keeps the messages anyway. `null` when off or unknown. |\n| `limits` | [`LinkedCapabilities`](LinkedCapabilities.md) | Size and mutation limits. |\n| `roster?` | `null` \\| [`WhatsAppRoster`](WhatsAppRoster.md) | - |\n| `sendingIdentity?` | `string` \\| `null` | Caller's own phone identity, never another account's identity. |\n| `sharePermission` | [`SharePermissionV2`](SharePermissionV2.md) | Owner-controlled standard sharing configuration. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppGroupMessage.md -->\n# Type Alias: WhatsAppGroupMessage\n\n> **WhatsAppGroupMessage** = \\{ `attachments`: [`LinkedAttachment`](LinkedAttachment.md)[]; `body`: `string`; `deleted`: `boolean`; `deliveryState?`: `null` \\| [`LinkedDeliveryState`](LinkedDeliveryState.md); `editedAt?`: `string` \\| `null`; `forwarded`: `boolean`; `id`: `string`; `kind`: [`WhatsAppMessageKind`](WhatsAppMessageKind.md); `mentions`: [`WhatsAppMention`](WhatsAppMention.md)[]; `reactions`: [`WhatsAppGroupReaction`](WhatsAppGroupReaction.md)[]; `receivedAt`: `string`; `replyTo?`: `string` \\| `null`; `rich?`: `null` \\| [`WhatsAppRichContent`](WhatsAppRichContent.md); `sender`: [`WhatsAppGroupSender`](WhatsAppGroupSender.md); `sentAt`: `string`; `viewOnce`: `boolean`; \\}\n\nOne message in an adopted group.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attachments\"></a> `attachments` | [`LinkedAttachment`](LinkedAttachment.md)[] | Imported or pending attachments. |\n| <a id=\"property-body\"></a> `body` | `string` | Plain WhatsApp text. |\n| <a id=\"property-deleted\"></a> `deleted` | `boolean` | Deleted for everyone. |\n| <a id=\"property-deliverystate\"></a> `deliveryState?` | `null` \\| [`LinkedDeliveryState`](LinkedDeliveryState.md) | - |\n| <a id=\"property-editedat\"></a> `editedAt?` | `string` \\| `null` | Last edit timestamp. |\n| <a id=\"property-forwarded\"></a> `forwarded` | `boolean` | Forwarded from another chat. |\n| <a id=\"property-id\"></a> `id` | `string` | Stable message id. |\n| <a id=\"property-kind\"></a> `kind` | [`WhatsAppMessageKind`](WhatsAppMessageKind.md) | A message, or a system line. |\n| <a id=\"property-mentions\"></a> `mentions` | [`WhatsAppMention`](WhatsAppMention.md)[] | People the body @-mentions. |\n| <a id=\"property-reactions\"></a> `reactions` | [`WhatsAppGroupReaction`](WhatsAppGroupReaction.md)[] | Reactions grouped by emoji. |\n| <a id=\"property-receivedat\"></a> `receivedAt` | `string` | Timestamp first received by Macro. |\n| <a id=\"property-replyto\"></a> `replyTo?` | `string` \\| `null` | Message quoted by this one. |\n| <a id=\"property-rich\"></a> `rich?` | `null` \\| [`WhatsAppRichContent`](WhatsAppRichContent.md) | - |\n| <a id=\"property-sender\"></a> `sender` | [`WhatsAppGroupSender`](WhatsAppGroupSender.md) | Sender. |\n| <a id=\"property-sentat\"></a> `sentAt` | `string` | Timestamp assigned by WhatsApp. |\n| <a id=\"property-viewonce\"></a> `viewOnce` | `boolean` | Sent as view-once in WhatsApp; Macro shows it like any media. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppGroupReaction.md -->\n# Type Alias: WhatsAppGroupReaction\n\n> **WhatsAppGroupReaction** = \\{ `count`: `number`; `emoji`: `string`; `mine`: `boolean`; \\}\n\nGrouped reactions.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-count\"></a> `count` | `number` | Number of reacting people. |\n| <a id=\"property-emoji\"></a> `emoji` | `string` | Emoji. |\n| <a id=\"property-mine\"></a> `mine` | `boolean` | Caller has this reaction. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppGroupSender.md -->\n# Type Alias: WhatsAppGroupSender\n\n> **WhatsAppGroupSender** = \\{ `name`: `string`; `personId`: `string`; `userId?`: `string` \\| `null`; \\}\n\nMessage sender from protocol-verified identity evidence.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-name\"></a> `name` | `string` | Display name, never authentication evidence. |\n| <a id=\"property-personid\"></a> `personId` | `string` | External person identity. |\n| <a id=\"property-userid\"></a> `userId?` | `string` \\| `null` | Verified Macro user association, if present. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppGroupSummary.md -->\n# Type Alias: WhatsAppGroupSummary\n\n> **WhatsAppGroupSummary** = \\{ `backfill?`: `null` \\| [`LinkedBackfill`](LinkedBackfill.md); `canSend`: `boolean`; `community?`: `null` \\| [`LinkedCommunityReference`](LinkedCommunityReference.md); `id`: `string`; `kind`: [`LinkedChatKind`](LinkedChatKind.md); `lastMessageAt?`: `string` \\| `null`; `name`: `string`; `sendReason?`: `null` \\| [`LinkedReplyBlock`](LinkedReplyBlock.md); `unreadCount`: `number`; `userId`: `string`; \\}\n\nAdopted group visible through ordinary entity sharing.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-backfill\"></a> `backfill?` | `null` \\| [`LinkedBackfill`](LinkedBackfill.md) | - |\n| <a id=\"property-cansend\"></a> `canSend` | `boolean` | Caller may currently send from their own account. |\n| <a id=\"property-community\"></a> `community?` | `null` \\| [`LinkedCommunityReference`](LinkedCommunityReference.md) | - |\n| <a id=\"property-id\"></a> `id` | `string` | Entity identifier. |\n| <a id=\"property-kind\"></a> `kind` | [`LinkedChatKind`](LinkedChatKind.md) | A group, or a direct chat with one person (only its owner sends). |\n| <a id=\"property-lastmessageat\"></a> `lastMessageAt?` | `string` \\| `null` | Latest message timestamp. |\n| <a id=\"property-name\"></a> `name` | `string` | Display name: the group's, or a direct chat's other person. |\n| <a id=\"property-sendreason\"></a> `sendReason?` | `null` \\| [`LinkedReplyBlock`](LinkedReplyBlock.md) | - |\n| <a id=\"property-unreadcount\"></a> `unreadCount` | `number` | Unread live messages for this viewer, counted up to [`UNREAD_COUNT_CAP`]. |\n| <a id=\"property-userid\"></a> `userId` | `string` | Actual entity owner. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppLocation.md -->\n# Type Alias: WhatsAppLocation\n\n> **WhatsAppLocation** = \\{ `address?`: `string` \\| `null`; `comment?`: `string` \\| `null`; `latitude`: `number`; `live?`: `boolean`; `longitude`: `number`; `name?`: `string` \\| `null`; `url?`: `string` \\| `null`; \\}\n\nA shared place.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-address\"></a> `address?` | `string` \\| `null` | Street address. |\n| <a id=\"property-comment\"></a> `comment?` | `string` \\| `null` | Caption or comment. |\n| <a id=\"property-latitude\"></a> `latitude` | `number` | Degrees. |\n| <a id=\"property-live\"></a> `live?` | `boolean` | Shared as a live location (this is where it started). |\n| <a id=\"property-longitude\"></a> `longitude` | `number` | Degrees. |\n| <a id=\"property-name\"></a> `name?` | `string` \\| `null` | Place name. |\n| <a id=\"property-url\"></a> `url?` | `string` \\| `null` | Link the sender attached. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppMention.md -->\n# Type Alias: WhatsAppMention\n\n> **WhatsAppMention** = [`WhatsAppPersonRef`](WhatsAppPersonRef.md) & \\{ `token`: `string`; \\}\n\nAn @-mention in a message body.\n\n## Type Declaration\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `token` | `string` | What follows the `@` in the body (the digits of the person's WhatsApp id); replace `@<token>` with the name. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppMessageKind.md -->\n# Type Alias: WhatsAppMessageKind\n\n> **WhatsAppMessageKind** = `\"message\"` \\| `\"system\"`\n\nWhat a timeline entry is.\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppParticipant.md -->\n# Type Alias: WhatsAppParticipant\n\n> **WhatsAppParticipant** = \\{ `admin`: `boolean`; `alternateJid?`: `string` \\| `null`; `displayName?`: `string` \\| `null`; `jid`: `string`; \\}\n\nSomeone in a WhatsApp chat; Macro access is a separate grant.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-admin\"></a> `admin` | `boolean` | Group admin. |\n| <a id=\"property-alternatejid\"></a> `alternateJid?` | `string` \\| `null` | The other address WhatsApp verified for them. |\n| <a id=\"property-displayname\"></a> `displayName?` | `string` \\| `null` | Their WhatsApp name, untrusted. |\n| <a id=\"property-jid\"></a> `jid` | `string` | Phone-number or LID JID. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppPersonRef.md -->\n# Type Alias: WhatsAppPersonRef\n\n> **WhatsAppPersonRef** = \\{ `name`: `string`; `userId?`: `string` \\| `null`; \\}\n\nA person named in a message: a Macro user when verified, else their\nWhatsApp name, else their phone number.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-name\"></a> `name` | `string` | Display name, never authentication evidence. |\n| <a id=\"property-userid\"></a> `userId?` | `string` \\| `null` | Verified Macro user, if any. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppPoll.md -->\n# Type Alias: WhatsAppPoll\n\n> **WhatsAppPoll** = \\{ `options`: [`WhatsAppPollOption`](WhatsAppPollOption.md)[]; `question`: `string`; `selectableCount`: `number`; `voters`: `number`; \\}\n\nA poll, read-only in Macro.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-options\"></a> `options` | [`WhatsAppPollOption`](WhatsAppPollOption.md)[] | Options in order, with tallies. |\n| <a id=\"property-question\"></a> `question` | `string` | The question. |\n| <a id=\"property-selectablecount\"></a> `selectableCount` | `number` | How many options one person may choose; 0 means any number. |\n| <a id=\"property-voters\"></a> `voters` | `number` | People who voted for anything. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppPollOption.md -->\n# Type Alias: WhatsAppPollOption\n\n> **WhatsAppPollOption** = \\{ `mine`: `boolean`; `name`: `string`; `voters`: [`WhatsAppPersonRef`](WhatsAppPersonRef.md)[]; `votes`: `number`; \\}\n\nOne option of a poll with its votes.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-mine\"></a> `mine` | `boolean` | The caller chose it. |\n| <a id=\"property-name\"></a> `name` | `string` | Option text. |\n| <a id=\"property-voters\"></a> `voters` | [`WhatsAppPersonRef`](WhatsAppPersonRef.md)[] | Who chose it. |\n| <a id=\"property-votes\"></a> `votes` | `number` | People who chose it. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppRichContent.md -->\n# Type Alias: WhatsAppRichContent\n\n> **WhatsAppRichContent** = [`WhatsAppPoll`](WhatsAppPoll.md) & \\{ `type`: `\"poll\"`; \\} \\| [`WhatsAppLocation`](WhatsAppLocation.md) & \\{ `type`: `\"location\"`; \\} \\| [`WhatsAppContacts`](WhatsAppContacts.md) & \\{ `type`: `\"contacts\"`; \\} \\| [`WhatsAppEvent`](WhatsAppEvent.md) & \\{ `type`: `\"event\"`; \\} \\| [`WhatsAppSystemLine`](WhatsAppSystemLine.md) & \\{ `type`: `\"system\"`; \\}\n\nStructured content of a message besides its body.\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppRoster.md -->\n# Type Alias: WhatsAppRoster\n\n> **WhatsAppRoster** = \\{ `announce`: `boolean`; `name`: `string`; `observedAt`: `string`; `participants`: [`WhatsAppParticipant`](WhatsAppParticipant.md)[]; \\}\n\nA chat's WhatsApp metadata as the caller's account last read it.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-announce\"></a> `announce` | `boolean` | Only admins may post. |\n| <a id=\"property-name\"></a> `name` | `string` | WhatsApp subject. |\n| <a id=\"property-observedat\"></a> `observedAt` | `string` | When this was read from WhatsApp. |\n| <a id=\"property-participants\"></a> `participants` | [`WhatsAppParticipant`](WhatsAppParticipant.md)[] | Everyone in the chat. |\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppSystemAction.md -->\n# Type Alias: WhatsAppSystemAction\n\n> **WhatsAppSystemAction** = `\"group_created\"` \\| `\"participants_added\"` \\| `\"participants_removed\"` \\| `\"participants_left\"` \\| `\"participants_joined\"` \\| `\"participants_promoted\"` \\| `\"participants_demoted\"` \\| `\"subject_changed\"` \\| `\"icon_changed\"` \\| `\"description_changed\"` \\| `\"disappearing_changed\"` \\| `\"message_pinned\"` \\| `\"message_unpinned\"` \\| `\"call\"`\n\nKinds of system lines.\n\n\n<!-- generated/storage/types.gen/type-aliases/WhatsAppSystemLine.md -->\n# Type Alias: WhatsAppSystemLine\n\n> **WhatsAppSystemLine** = \\{ `action`: [`WhatsAppSystemAction`](WhatsAppSystemAction.md); `actor?`: `null` \\| [`WhatsAppPersonRef`](WhatsAppPersonRef.md); `call?`: `null` \\| [`WhatsAppCall`](WhatsAppCall.md); `participants`: [`WhatsAppPersonRef`](WhatsAppPersonRef.md)[]; `value?`: `string` \\| `null`; \\}\n\nSomething that happened in the group.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-action\"></a> `action` | [`WhatsAppSystemAction`](WhatsAppSystemAction.md) | What happened. |\n| <a id=\"property-actor\"></a> `actor?` | `null` \\| [`WhatsAppPersonRef`](WhatsAppPersonRef.md) | - |\n| <a id=\"property-call\"></a> `call?` | `null` \\| [`WhatsAppCall`](WhatsAppCall.md) | - |\n| <a id=\"property-participants\"></a> `participants` | [`WhatsAppPersonRef`](WhatsAppPersonRef.md)[] | Who it happened to (added, removed, promoted, …). |\n| <a id=\"property-value\"></a> `value?` | `string` \\| `null` | New subject or description; disappearing-messages timer in seconds (`\"0\"` is off). |\n\n\n<!-- src/entities/channels/activity/classes/ChannelActivity.md -->\n# Class: ChannelActivity\n\nA user's channel activity marker.\n\n## Constructors\n\n### Constructor\n\n> **new ChannelActivity**(`client`, `channel`, `record`): `ChannelActivity`\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `client` | `MacroClient` | - |\n| `channel` | [`Channel`](../../channel/classes/Channel.md) | Related channel. |\n| `record` | [`ApiActivity`](../../../../../generated/storage/types.gen/type-aliases/ApiActivity.md) | - |\n\n#### Returns\n\n`ChannelActivity`\n\n## Properties\n\n| Property | Modifier | Type | Description |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-channel\"></a> `channel` | `readonly` | [`Channel`](../../channel/classes/Channel.md) | Related channel. |\n\n## Accessors\n\n### id\n\n#### Get Signature\n\n> **get** **id**(): `string`\n\nActivity identity.\n\n##### Returns\n\n`string`\n\n## Methods\n\n### createdAt()\n\n> **createdAt**(): `string`\n\nCreation time.\n\n#### Returns\n\n`string`\n\n***\n\n### recordInteraction()\n\n> **recordInteraction**(`type`): `Promise`\\<`ChannelActivity`\\>\n\nRecord a view or interaction in this channel.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `type` | [`ActivityType`](../../../../../generated/storage/types.gen/type-aliases/ActivityType.md) |\n\n#### Returns\n\n`Promise`\\<`ChannelActivity`\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): [`ApiActivity`](../../../../../generated/storage/types.gen/type-aliases/ApiActivity.md)\n\nSerialize activity without credentials.\n\n#### Returns\n\n[`ApiActivity`](../../../../../generated/storage/types.gen/type-aliases/ApiActivity.md)\n\n***\n\n### user()\n\n> **user**(): [`User`](../../../users/user/classes/User.md)\n\nUser who interacted.\n\n#### Returns\n\n[`User`](../../../users/user/classes/User.md)\n\n\n<!-- src/entities/channels/channel/classes/Channel.md -->\n# Class: Channel\n\nA channel.\n\n## Extends\n\n- [`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md)\\<`ChannelDetail`\\>\n\n## Properties\n\n| Property | Modifier | Type | Default value | Description | Overrides | Inherited from |\n| ------ | ------ | ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-entitytype\"></a> `entityType` | `readonly` | `\"channel\"` | `'channel'` | Favorites identify channels as `channel`. | [`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`entityType`](../../../entity/classes/PropertiedEntity.md#property-entitytype) | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | `undefined` | - | - | [`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`id`](../../../entity/classes/PropertiedEntity.md#property-id) |\n| <a id=\"property-name\"></a> `name` | `readonly` | () => `Promise`\\<`string`\\> | `...` | The channel's display name, resolved from the viewer's perspective. | - | - |\n| <a id=\"property-type\"></a> `type` | `readonly` | () => `Promise`\\<[`ChannelType`](../../../../../generated/storage/types.gen/type-aliases/ChannelType.md)\\> | `...` | The channel's type (e.g. `public`, `dm`, `private`). | - | - |\n| <a id=\"property-search\"></a> `search` | `static` | (`client`, `query`, `searchOpts?`) => `AsyncGenerator`\\<`Channel`\\> | `...` | Search channels by content, most relevant first, auto-paginated. | - | - |\n\n## Methods\n\n### addParticipants()\n\n> **addParticipants**(`users`): `Promise`\\<`void`\\>\n\nAdd users to the channel.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `users` | [`User`](../../../users/user/classes/User.md)[] |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### agentConversations()\n\n> **agentConversations**(): `Promise`\\<[`AgentConversation`](../../../agent-sessions/conversation/classes/AgentConversation.md)[]\\>\n\nConversations maintained by agents in this channel.\n\n#### Returns\n\n`Promise`\\<[`AgentConversation`](../../../agent-sessions/conversation/classes/AgentConversation.md)[]\\>\n\n***\n\n### attachments()\n\n> **attachments**(`opts?`): `AsyncGenerator`\\<[`ApiChannelAttachment`](../../../../../generated/storage/types.gen/type-aliases/ApiChannelAttachment.md)\\>\n\nThe attachments posted in this channel, auto-paginated.\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `opts?` | \\{ `pageSize?`: `number`; `type?`: `string`; \\} | - |\n| `opts.pageSize?` | `number` | - |\n| `opts.type?` | `string` | Filter by type: `static` for images/videos, `dss` for documents. |\n\n#### Returns\n\n`AsyncGenerator`\\<[`ApiChannelAttachment`](../../../../../generated/storage/types.gen/type-aliases/ApiChannelAttachment.md)\\>\n\n***\n\n### delete()\n\n> **delete**(): `Promise`\\<`void`\\>\n\nDelete the channel. This is not reversible.\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### deleteProperty()\n\n> **deleteProperty**(`assignment`): `Promise`\\<`void`\\>\n\nRemove a property from this entity, given its [properties](#properties) entry.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `assignment` | [`EntityPropertyWithDefinition`](../../../../../generated/properties/types.gen/type-aliases/EntityPropertyWithDefinition.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`deleteProperty`](../../../entity/classes/PropertiedEntity.md#deleteproperty)\n\n***\n\n### favorite()\n\n> **favorite**(): `Promise`\\<`Channel`\\>\n\nAdd this entity to the user's favorites. Returns this handle for chaining.\nPlain unwrap: favoriting alters the user's favorites collection, not this\nentity's own detail, so there's nothing cached to invalidate.\n\n#### Returns\n\n`Promise`\\<`Channel`\\>\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`favorite`](../../../entity/classes/PropertiedEntity.md#favorite)\n\n***\n\n### join()\n\n> **join**(): `Promise`\\<`void`\\>\n\nJoin the channel as the current user.\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### joinCode()\n\n> **joinCode**(): `Promise`\\<`string`\\>\n\nA reusable code that lets a user join this channel.\n\n#### Returns\n\n`Promise`\\<`string`\\>\n\n***\n\n### leave()\n\n> **leave**(): `Promise`\\<`void`\\>\n\nLeave the channel as the current user.\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### message()\n\n> **message**(`id`): [`Message`](../../message/classes/Message.md)\n\nA handle to a message in this channel by id.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n[`Message`](../../message/classes/Message.md)\n\n***\n\n### messages()\n\n> **messages**(`opts?`): `AsyncGenerator`\\<[`Message`](../../message/classes/Message.md)\\>\n\nRoot messages in this channel, most recent first, auto-paginated.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts?` | \\{ `pageSize?`: `number`; \\} |\n| `opts.pageSize?` | `number` |\n\n#### Returns\n\n`AsyncGenerator`\\<[`Message`](../../message/classes/Message.md)\\>\n\n***\n\n### messagesAfter()\n\n> **messagesAfter**(`after`, `opts?`): `AsyncGenerator`\\<[`Message`](../../message/classes/Message.md)\\>\n\nRoot messages created or replied to at or after `after`, most recent\nfirst, auto-paginated. Use it to catch up after a disconnect.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `after` | `string` \\| `Date` |\n| `opts?` | \\{ `pageSize?`: `number`; \\} |\n| `opts.pageSize?` | `number` |\n\n#### Returns\n\n`AsyncGenerator`\\<[`Message`](../../message/classes/Message.md)\\>\n\n***\n\n### messageThreadById()\n\n> **messageThreadById**(`id`): [`MessageThread`](../../../messages/thread/classes/MessageThread.md)\n\nA shared message thread scoped to this resource.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n[`MessageThread`](../../../messages/thread/classes/MessageThread.md)\n\n***\n\n### participants()\n\n> **participants**(): `Promise`\\<[`ApiChannelParticipant`](../../../../../generated/storage/types.gen/type-aliases/ApiChannelParticipant.md)[]\\>\n\nThe channel's members, with their roles and join times.\n\n#### Returns\n\n`Promise`\\<[`ApiChannelParticipant`](../../../../../generated/storage/types.gen/type-aliases/ApiChannelParticipant.md)[]\\>\n\n***\n\n### permission()\n\n> **permission**(): `Promise`\\<\\{ `permission`: [`EntityPermission`](../../../../../generated/storage/types.gen/type-aliases/EntityPermission.md); `status`: `\"access\"`; \\} \\| \\{ `status`: `\"no_access\"`; \\}\\>\n\nRead the caller's effective permission on this entity.\n\n#### Returns\n\n`Promise`\\<\\{ `permission`: [`EntityPermission`](../../../../../generated/storage/types.gen/type-aliases/EntityPermission.md); `status`: `\"access\"`; \\} \\| \\{ `status`: `\"no_access\"`; \\}\\>\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`permission`](../../../entity/classes/PropertiedEntity.md#permission)\n\n***\n\n### properties()\n\n> **properties**(`opts?`): `Promise`\\<[`EntityPropertyWithDefinition`](../../../../../generated/properties/types.gen/type-aliases/EntityPropertyWithDefinition.md)[]\\>\n\nThe properties set on this entity, each with its definition, value, and options.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts?` | \\{ `includeMetadata?`: `boolean`; \\} |\n| `opts.includeMetadata?` | `boolean` |\n\n#### Returns\n\n`Promise`\\<[`EntityPropertyWithDefinition`](../../../../../generated/properties/types.gen/type-aliases/EntityPropertyWithDefinition.md)[]\\>\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`properties`](../../../entity/classes/PropertiedEntity.md#properties)\n\n***\n\n### propertyReference()\n\n> **propertyReference**(): [`PropertyTargetReference`](../../../../../generated/properties/types.gen/type-aliases/PropertyTargetReference.md)\n\nThis entity's reference for bulk property operations.\n\n#### Returns\n\n[`PropertyTargetReference`](../../../../../generated/properties/types.gen/type-aliases/PropertyTargetReference.md)\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`propertyReference`](../../../entity/classes/PropertiedEntity.md#propertyreference)\n\n***\n\n### recordActivity()\n\n> **recordActivity**(`type`): `Promise`\\<[`ChannelActivity`](../../activity/classes/ChannelActivity.md)\\>\n\nRecord a view or interaction in this channel.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `type` | [`ActivityType`](../../../../../generated/storage/types.gen/type-aliases/ActivityType.md) |\n\n#### Returns\n\n`Promise`\\<[`ChannelActivity`](../../activity/classes/ChannelActivity.md)\\>\n\n***\n\n### removeParticipants()\n\n> **removeParticipants**(`users`): `Promise`\\<`void`\\>\n\nRemove users from the channel.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `users` | [`User`](../../../users/user/classes/User.md)[] |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### rename()\n\n> **rename**(`name`): `Promise`\\<`void`\\>\n\nRename the channel.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `name` | `string` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### send()\n\n> **send**(`body`, `opts?`): `Promise`\\<[`Message`](../../message/classes/Message.md)\\>\n\nPost a message. Plain text, or a rich body composed with `msg`.\n\nWorks with a channel webhook token as well as a normal one — see\n[postToChannel](../../post/functions/postToChannel.md) for which endpoint that picks and what it costs.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `body` | `string` \\| [`RichMessage`](../../../../mentions/interfaces/RichMessage.md) |\n| `opts?` | \\{ `thread?`: [`Thread`](../../thread/classes/Thread.md); \\} |\n| `opts.thread?` | [`Thread`](../../thread/classes/Thread.md) |\n\n#### Returns\n\n`Promise`\\<[`Message`](../../message/classes/Message.md)\\>\n\n***\n\n### setPicture()\n\n> **setPicture**(`picture?`): `Promise`\\<`void`\\>\n\nSet an uploaded profile picture, or clear it.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `picture?` | [`ChannelPicture`](../../picture/classes/ChannelPicture.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### setProperty()\n\n> **setProperty**(`property`, `value?`): `Promise`\\<`void`\\>\n\nSet a property value on this entity, or attach the property without a\nvalue when `value` is omitted.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `property` | [`PropertyDefinition`](../../../properties/property-definition/classes/PropertyDefinition.md) |\n| `value?` | [`SetPropertyValue`](../../../../../generated/properties/types.gen/type-aliases/SetPropertyValue.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`setProperty`](../../../entity/classes/PropertiedEntity.md#setproperty)\n\n***\n\n### timelinePage()\n\n> **timelinePage**(`selection?`): `Promise`\\<\\{ `entries`: (\\{ `activity`: \\{ `action`: `string`; `actor`: [`User`](../../../users/user/classes/User.md); `actor_id`: `string`; `id`: `string`; `occurred_at`: `string`; `payload?`: `unknown`; \\}; `message?`: `undefined`; `type`: `\"activity\"`; \\} \\| \\{ `activity?`: `undefined`; `message`: [`Message`](../../message/classes/Message.md); `type`: `\"message\"`; \\})[]; `nextCursor`: [`MessageCursor`](../../../../../generated/storage/types.gen/type-aliases/MessageCursor.md) \\| `undefined`; `previousCursor`: [`MessageCursor`](../../../../../generated/storage/types.gen/type-aliases/MessageCursor.md) \\| `undefined`; \\}\\>\n\nA mixed message and activity timeline page.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `selection?` | [`TimelineOptions`](../../../messages/thread/interfaces/TimelineOptions.md)\\<[`Message`](../../message/classes/Message.md)\\> |\n\n#### Returns\n\n`Promise`\\<\\{ `entries`: (\\{ `activity`: \\{ `action`: `string`; `actor`: [`User`](../../../users/user/classes/User.md); `actor_id`: `string`; `id`: `string`; `occurred_at`: `string`; `payload?`: `unknown`; \\}; `message?`: `undefined`; `type`: `\"activity\"`; \\} \\| \\{ `activity?`: `undefined`; `message`: [`Message`](../../message/classes/Message.md); `type`: `\"message\"`; \\})[]; `nextCursor`: [`MessageCursor`](../../../../../generated/storage/types.gen/type-aliases/MessageCursor.md) \\| `undefined`; `previousCursor`: [`MessageCursor`](../../../../../generated/storage/types.gen/type-aliases/MessageCursor.md) \\| `undefined`; \\}\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`ApiChannelDetail`](../../../../../generated/storage/types.gen/type-aliases/ApiChannelDetail.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`ApiChannelDetail`](../../../../../generated/storage/types.gen/type-aliases/ApiChannelDetail.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`ApiChannelDetail`](../../../../../generated/storage/types.gen/type-aliases/ApiChannelDetail.md) |\n| `id` | `string` |\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`toJSON`](../../../entity/classes/PropertiedEntity.md#tojson)\n\n***\n\n### typing()\n\n> **typing**(`action`, `opts?`): `Promise`\\<`void`\\>\n\nBroadcast a typing indicator, optionally scoped to a thread.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `action` | `\"stop\"` \\| `\"start\"` |\n| `opts?` | \\{ `thread?`: [`Thread`](../../thread/classes/Thread.md); \\} |\n| `opts.thread?` | [`Thread`](../../thread/classes/Thread.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### unfavorite()\n\n> **unfavorite**(): `Promise`\\<`Channel`\\>\n\nRemove this entity from the user's favorites. Returns this handle for chaining.\n\n#### Returns\n\n`Promise`\\<`Channel`\\>\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`unfavorite`](../../../entity/classes/PropertiedEntity.md#unfavorite)\n\n***\n\n### updatePropertyOptions()\n\n> **updatePropertyOptions**(`changes`): `Promise`\\<[`BulkUpdateEntityPropertyOptionsResponse`](../../../../../generated/properties/types.gen/type-aliases/BulkUpdateEntityPropertyOptionsResponse.md)\\>\n\nApply multi-select option deltas atomically across this entity's properties.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `changes` | [`PropertyOptionDelta`](../../../entity/interfaces/PropertyOptionDelta.md)[] |\n\n#### Returns\n\n`Promise`\\<[`BulkUpdateEntityPropertyOptionsResponse`](../../../../../generated/properties/types.gen/type-aliases/BulkUpdateEntityPropertyOptionsResponse.md)\\>\n\n#### Inherited from\n\n[`PropertiedEntity`](../../../entity/classes/PropertiedEntity.md).[`updatePropertyOptions`](../../../entity/classes/PropertiedEntity.md#updatepropertyoptions)\n\n***\n\n### webUrl()\n\n> **webUrl**(): `string`\n\nThe channel's URL in the Macro web app.\n\n#### Returns\n\n`string`\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `id`): `Channel`\n\nA handle to a channel by id. Details load on first access.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `id` | `string` |\n\n#### Returns\n\n`Channel`\n\n***\n\n### create()\n\n> `static` **create**(`client`, `opts`): `Promise`\\<`Channel`\\>\n\nCreate a channel. The caller becomes the owner.\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `client` | `MacroClient` | - |\n| `opts` | \\{ `name?`: `string`; `participants?`: [`User`](../../../users/user/classes/User.md)[]; `team?`: [`Team`](../../../teams/team/classes/Team.md); `type`: [`ChannelType`](../../../../../generated/storage/types.gen/type-aliases/ChannelType.md); \\} | - |\n| `opts.name?` | `string` | - |\n| `opts.participants?` | [`User`](../../../users/user/classes/User.md)[] | Participants to add, excluding the owner. |\n| `opts.team?` | [`Team`](../../../teams/team/classes/Team.md) | Team, for team channels. |\n| `opts.type` | [`ChannelType`](../../../../../generated/storage/types.gen/type-aliases/ChannelType.md) | - |\n\n#### Returns\n\n`Promise`\\<`Channel`\\>\n\n***\n\n### dm()\n\n> `static` **dm**(`client`, `recipient`): `Promise`\\<`Channel`\\>\n\nOpen (creating if needed) the DM channel with a user.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `recipient` | [`User`](../../../users/user/classes/User.md) |\n\n#### Returns\n\n`Promise`\\<`Channel`\\>\n\n***\n\n### private()\n\n> `static` **private**(`client`, `recipients`): `Promise`\\<`Channel`\\>\n\nOpen (creating if needed) the private group channel with a set of users.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `recipients` | [`User`](../../../users/user/classes/User.md)[] |\n\n#### Returns\n\n`Promise`\\<`Channel`\\>\n\n\n<!-- src/entities/channels/channel/type-aliases/ChannelAttachment.md -->\n# Type Alias: ChannelAttachment\n\n> **ChannelAttachment** = [`GetChannelAttachmentsResponses`](../../../../../generated/storage/types.gen/type-aliases/GetChannelAttachmentsResponses.md)\\[`200`\\]\\[`\"items\"`\\]\\[`number`\\]\n\nA file or entity attached to a message in a channel.\n\n\n<!-- src/entities/channels/channel/type-aliases/ChannelParticipant.md -->\n# Type Alias: ChannelParticipant\n\n> **ChannelParticipant** = [`GetChannelParticipantsResponses`](../../../../../generated/storage/types.gen/type-aliases/GetChannelParticipantsResponses.md)\\[`200`\\]\\[`number`\\]\n\nA member of a channel, with their role and join time.\n\n\n<!-- src/entities/channels/labels/classes/ChannelLabelsNamespace.md -->\n# Class: ChannelLabelsNamespace\n\nShared or private channel labels: named groups of channels shown in the Chat\nsidebar. Every member of the team sees the same labels in the same order,\nand any member may create, rename, delete, or move channels between them;\neach change applies to the whole team. Users without a team have private\nlabels belonging to their account.\n\nA label's `channelIds` lists only the channels the authenticated user is a\nmember of. Manual labels count all assignments; smart tags count visible\nmatches. A channel can be in one manual label and any number of matching\nsmart tags per team or account. Direct messages cannot be grouped.\n\n## Constructors\n\n### Constructor\n\n> **new ChannelLabelsNamespace**(`client`): `ChannelLabelsNamespace`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`ChannelLabelsNamespace`\n\n## Methods\n\n### create()\n\n> **create**(`name`, `channels?`): `Promise`\\<[`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md)\\>\n\nCreate a label and atomically move `channels` into it. Names are unique\nwithin the team or account, case-insensitively.\n\n#### Parameters\n\n| Parameter | Type | Default value |\n| ------ | ------ | ------ |\n| `name` | `string` | `undefined` |\n| `channels?` | [`Channel`](../../channel/classes/Channel.md)[] | `[]` |\n\n#### Returns\n\n`Promise`\\<[`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md)\\>\n\n***\n\n### createSmartTag()\n\n> **createSmartTag**(`name`, `rule`): `Promise`\\<[`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md)\\>\n\nCreate a smart tag whose membership follows an attribute rule automatically.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `name` | `string` |\n| `rule` | [`ChannelLabelRule`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabelRule.md) |\n\n#### Returns\n\n`Promise`\\<[`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md)\\>\n\n***\n\n### delete()\n\n> **delete**(`label`): `Promise`\\<`void`\\>\n\nDelete a label for the whole team; its channels return to the plain list.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `label` | [`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### list()\n\n> **list**(): `Promise`\\<[`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md)[]\\>\n\nEvery label in the authenticated user's shared or private scope.\n\n#### Returns\n\n`Promise`\\<[`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md)[]\\>\n\n***\n\n### previewSmartTag()\n\n> **previewSmartTag**(`rule`): `Promise`\\<[`SmartTagPreview`](../../../../../generated/storage/types.gen/type-aliases/SmartTagPreview.md)\\>\n\nPreview the first matches and total visible count without creating a tag.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `rule` | [`ChannelLabelRule`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabelRule.md) |\n\n#### Returns\n\n`Promise`\\<[`SmartTagPreview`](../../../../../generated/storage/types.gen/type-aliases/SmartTagPreview.md)\\>\n\n***\n\n### rename()\n\n> **rename**(`label`, `name`): `Promise`\\<[`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md)\\>\n\nRename a label for the whole team.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `label` | [`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md) |\n| `name` | `string` |\n\n#### Returns\n\n`Promise`\\<[`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md)\\>\n\n***\n\n### setLabel()\n\n> **setLabel**(`channel`, `label`): `Promise`\\<`void`\\>\n\nMove a channel into `label`, or out of any label when `label` is `undefined`.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `channel` | [`Channel`](../../channel/classes/Channel.md) |\n| `label` | [`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md) \\| `undefined` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### updateSmartTag()\n\n> **updateSmartTag**(`label`, `name`, `rule`): `Promise`\\<[`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md)\\>\n\nUpdate the name and matching rule of an existing smart tag.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `label` | [`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md) |\n| `name` | `string` |\n| `rule` | [`ChannelLabelRule`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabelRule.md) |\n\n#### Returns\n\n`Promise`\\<[`ChannelLabel`](../../../../../generated/storage/types.gen/type-aliases/ChannelLabel.md)\\>\n\n\n<!-- src/entities/channels/message/classes/Message.md -->\n# Class: Message\n\nA message in a channel. A thin handle: `id` and `channelId` are known up\nfront, and record-backed fields (`content`, `author`) load lazily on first\naccess and cache. Actions carry the ids for you.\n\n## Extends\n\n- [`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md)\\<[`Message`](../../../../../generated/storage/types.gen/type-aliases/Message.md)\\>\n\n## Properties\n\n| Property | Modifier | Type | Default value | Description | Overrides | Inherited from |\n| ------ | ------ | ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-channelid\"></a> `channelId` | `readonly` | `string` | `undefined` | - | - | - |\n| <a id=\"property-content\"></a> `content` | `readonly` | () => `Promise`\\<`string`\\> | `...` | The message body. | - | - |\n| <a id=\"property-createdat\"></a> `createdAt` | `readonly` | () => `Promise`\\<`string`\\> | `...` | When the message was created. | - | - |\n| <a id=\"property-editedat\"></a> `editedAt` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | `...` | When the message was last edited, if it has been. | - | - |\n| <a id=\"property-entitytype\"></a> `entityType` | `readonly` | `\"channel_message\"` | `'channel_message'` | Favorites identify channel messages as `channel_message`. | [`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`entityType`](../../../entity/classes/FavoritableEntity.md#property-entitytype) | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | `undefined` | - | - | [`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`id`](../../../entity/classes/FavoritableEntity.md#property-id) |\n| <a id=\"property-mentions\"></a> `mentions` | `readonly` | [`SimpleMention`](../../../../../generated/storage/types.gen/type-aliases/SimpleMention.md)[] | `[]` | Entities mentioned in this message, when a list, thread, or event supplied them. | - | - |\n| <a id=\"property-updatedat\"></a> `updatedAt` | `readonly` | () => `Promise`\\<`string`\\> | `...` | When the message was last updated. | - | - |\n\n## Methods\n\n### author()\n\n> **author**(): `Promise`\\<[`User`](../../../users/user/classes/User.md)\\>\n\nThe user who sent this message.\n\n#### Returns\n\n`Promise`\\<[`User`](../../../users/user/classes/User.md)\\>\n\n***\n\n### channel()\n\n> **channel**(): [`Channel`](../../channel/classes/Channel.md)\n\nThe channel this message is in.\n\n#### Returns\n\n[`Channel`](../../channel/classes/Channel.md)\n\n***\n\n### delete()\n\n> **delete**(): `Promise`\\<`void`\\>\n\nDelete this message.\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### edit()\n\n> **edit**(`body`): `Promise`\\<`Message`\\>\n\nReplace this message's body.\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `body` | `string` \\| [`RichMessage`](../../../../mentions/interfaces/RichMessage.md) | Plain text, or a rich body composed with msg. |\n\n#### Returns\n\n`Promise`\\<`Message`\\>\n\n***\n\n### favorite()\n\n> **favorite**(): `Promise`\\<`Message`\\>\n\nAdd this entity to the user's favorites. Returns this handle for chaining.\nPlain unwrap: favoriting alters the user's favorites collection, not this\nentity's own detail, so there's nothing cached to invalidate.\n\n#### Returns\n\n`Promise`\\<`Message`\\>\n\n#### Inherited from\n\n[`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`favorite`](../../../entity/classes/FavoritableEntity.md#favorite)\n\n***\n\n### permission()\n\n> **permission**(): `Promise`\\<\\{ `permission`: [`EntityPermission`](../../../../../generated/storage/types.gen/type-aliases/EntityPermission.md); `status`: `\"access\"`; \\} \\| \\{ `status`: `\"no_access\"`; \\}\\>\n\nRead the caller's effective permission on this entity.\n\n#### Returns\n\n`Promise`\\<\\{ `permission`: [`EntityPermission`](../../../../../generated/storage/types.gen/type-aliases/EntityPermission.md); `status`: `\"access\"`; \\} \\| \\{ `status`: `\"no_access\"`; \\}\\>\n\n#### Inherited from\n\n[`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`permission`](../../../entity/classes/FavoritableEntity.md#permission)\n\n***\n\n### react()\n\n> **react**(`emoji`): `Promise`\\<`Message`\\>\n\nAdd an emoji reaction to this message.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `emoji` | `string` |\n\n#### Returns\n\n`Promise`\\<`Message`\\>\n\n***\n\n### reply()\n\n> **reply**(`body`): `Promise`\\<`Message`\\>\n\nPost a reply in this message's thread.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `body` | `string` \\| [`RichMessage`](../../../../mentions/interfaces/RichMessage.md) |\n\n#### Returns\n\n`Promise`\\<`Message`\\>\n\n***\n\n### thread()\n\n> **thread**(): [`Thread`](../../thread/classes/Thread.md)\n\nThe thread rooted at this message.\n\n#### Returns\n\n[`Thread`](../../thread/classes/Thread.md)\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`Message`](../../../../../generated/storage/types.gen/type-aliases/Message.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`Message`](../../../../../generated/storage/types.gen/type-aliases/Message.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`Message`](../../../../../generated/storage/types.gen/type-aliases/Message.md) |\n| `id` | `string` |\n\n#### Inherited from\n\n[`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`toJSON`](../../../entity/classes/FavoritableEntity.md#tojson)\n\n***\n\n### unfavorite()\n\n> **unfavorite**(): `Promise`\\<`Message`\\>\n\nRemove this entity from the user's favorites. Returns this handle for chaining.\n\n#### Returns\n\n`Promise`\\<`Message`\\>\n\n#### Inherited from\n\n[`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`unfavorite`](../../../entity/classes/FavoritableEntity.md#unfavorite)\n\n***\n\n### unreact()\n\n> **unreact**(`emoji`): `Promise`\\<`Message`\\>\n\nRemove one of your emoji reactions from this message.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `emoji` | `string` |\n\n#### Returns\n\n`Promise`\\<`Message`\\>\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `channelId`, `id`, `mentions?`): `Message`\n\nA handle to a message by id. Fields load on first access.\n\n#### Parameters\n\n| Parameter | Type | Default value |\n| ------ | ------ | ------ |\n| `client` | `MacroClient` | `undefined` |\n| `channelId` | `string` | `undefined` |\n| `id` | `string` | `undefined` |\n| `mentions?` | [`SimpleMention`](../../../../../generated/storage/types.gen/type-aliases/SimpleMention.md)[] | `[]` |\n\n#### Returns\n\n`Message`\n\n***\n\n### from()\n\n> `static` **from**(`client`, `channelId`, `data`): `Message`\n\nBuild a root or reply from a message record (pre-seeded, no fetch).\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `channelId` | `string` |\n| `data` | [`Message`](../../../../../generated/storage/types.gen/type-aliases/Message.md) |\n\n#### Returns\n\n`Message`\n\n\n<!-- src/entities/channels/message/type-aliases/MessageData.md -->\n# Type Alias: MessageData\n\n> **MessageData** = [`Message`](../../../../../generated/storage/types.gen/type-aliases/Message.md)\n\nThe API's representation of a message; the same record the document comment API returns.\n\n\n<!-- src/entities/channels/namespace/classes/ChannelNamespace.md -->\n# Class: ChannelNamespace\n\n## Constructors\n\n### Constructor\n\n> **new ChannelNamespace**(`client`): `ChannelNamespace`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`ChannelNamespace`\n\n## Properties\n\n| Property | Modifier | Type | Description |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-labels\"></a> `labels` | `readonly` | [`ChannelLabelsNamespace`](../../labels/classes/ChannelLabelsNamespace.md) | Team-shared labels that group channels in the Chat sidebar. |\n\n## Methods\n\n### activity()\n\n> **activity**(): `Promise`\\<[`ChannelActivity`](../../activity/classes/ChannelActivity.md)[]\\>\n\nRecent channel activity, with channel and user handles.\n\n#### Returns\n\n`Promise`\\<[`ChannelActivity`](../../activity/classes/ChannelActivity.md)[]\\>\n\n***\n\n### byId()\n\n> **byId**(`id`): [`Channel`](../../channel/classes/Channel.md)\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n[`Channel`](../../channel/classes/Channel.md)\n\n***\n\n### create()\n\n> **create**(`opts`): `Promise`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\nCreate a channel. The caller becomes the owner.\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `opts` | \\{ `name?`: `string`; `participants?`: [`User`](../../../users/user/classes/User.md)[]; `team?`: [`Team`](../../../teams/team/classes/Team.md); `type`: [`ChannelType`](../../../../../generated/storage/types.gen/type-aliases/ChannelType.md); \\} | - |\n| `opts.name?` | `string` | - |\n| `opts.participants?` | [`User`](../../../users/user/classes/User.md)[] | Participants to add, excluding the owner. |\n| `opts.team?` | [`Team`](../../../teams/team/classes/Team.md) | Team, for team channels. |\n| `opts.type` | [`ChannelType`](../../../../../generated/storage/types.gen/type-aliases/ChannelType.md) | - |\n\n#### Returns\n\n`Promise`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\n***\n\n### dm()\n\n> **dm**(`recipient`): `Promise`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `recipient` | [`User`](../../../users/user/classes/User.md) |\n\n#### Returns\n\n`Promise`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\n***\n\n### list()\n\n> **list**(): `Promise`\\<[`Channel`](../../channel/classes/Channel.md)[]\\>\n\nAll channels the authenticated user is a member of.\n\n#### Returns\n\n`Promise`\\<[`Channel`](../../channel/classes/Channel.md)[]\\>\n\n***\n\n### private()\n\n> **private**(`recipients`): `Promise`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\nOpen (creating if needed) the private group channel with a set of users.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `recipients` | [`User`](../../../users/user/classes/User.md)[] |\n\n#### Returns\n\n`Promise`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\n***\n\n### search()\n\n> **search**(`query`, `opts?`): `AsyncGenerator`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\nSearch channels by name (client-side fuzzy filter on the full channel list)\nor by content (server-side unified search).\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `query` | `string` |\n| `opts?` | [`SearchOpts`](../../../search/interfaces/SearchOpts.md) |\n\n#### Returns\n\n`AsyncGenerator`\\<[`Channel`](../../channel/classes/Channel.md)\\>\n\n\n<!-- src/entities/channels/picture/classes/ChannelPicture.md -->\n# Class: ChannelPicture\n\nAn uploaded channel profile picture in static file storage.\n\n## Properties\n\n| Property | Modifier | Type |\n| ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `readonly` | `string` |\n\n## Methods\n\n### toJSON()\n\n> **toJSON**(): \\{ `id`: `string`; \\}\n\nSerialize the uploaded picture reference.\n\n#### Returns\n\n\\{ `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n***\n\n### byId()\n\n> `static` **byId**(`id`): `ChannelPicture`\n\nConstruct a reference from the upload receipt.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n`ChannelPicture`\n\n\n<!-- src/entities/channels/post/functions/postToChannel.md -->\n# Function: postToChannel()\n\n> **postToChannel**(`client`, `target`, `body`): `Promise`\\<`string`\\>\n\nPost a message using the endpoint supported by the caller's credentials.\n\nMost credentials use `POST /messages/channel/{id}`. User-owned bots without\nan acting user instead use `POST /channels/{id}/webhook`, which authorizes\nthrough channel membership. The bot owner is read from `GET /bots/me` and\ncached by the client.\n\nThe webhook endpoint supports content only. Mentions in `<m-*>` tags still\nwork, but threads and attachments are not supported.\n\nPosting to a `Thread` puts the message in that thread; to a `Channel`, at the\nchannel root. One target rather than a channel plus a thread id, so the two\ncan't disagree.\n\n## Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `target` | [`Channel`](../../channel/classes/Channel.md) \\| [`Thread`](../../thread/classes/Thread.md) |\n| `body` | [`RichMessage`](../../../../mentions/interfaces/RichMessage.md) |\n\n## Returns\n\n`Promise`\\<`string`\\>\n\n\n<!-- src/entities/channels/thread/classes/Thread.md -->\n# Class: Thread\n\nA thread within a channel, rooted at a top-level message. Replies and\nthread-scoped posting live here.\n\n## Constructors\n\n### Constructor\n\n> **new Thread**(`client`, `channelId`, `rootId`): `Thread`\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `client` | `MacroClient` | - |\n| `channelId` | `string` | - |\n| `rootId` | `string` | The id of the message this thread hangs off. |\n\n#### Returns\n\n`Thread`\n\n## Properties\n\n| Property | Modifier | Type | Description |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-channelid\"></a> `channelId` | `readonly` | `string` | - |\n| <a id=\"property-rootid\"></a> `rootId` | `readonly` | `string` | The id of the message this thread hangs off. |\n\n## Methods\n\n### channel()\n\n> **channel**(): [`Channel`](../../channel/classes/Channel.md)\n\nThe channel this thread is in.\n\n#### Returns\n\n[`Channel`](../../channel/classes/Channel.md)\n\n***\n\n### replies()\n\n> **replies**(): `Promise`\\<[`Message`](../../message/classes/Message.md)[]\\>\n\nList the replies in this thread, oldest first.\n\n#### Returns\n\n`Promise`\\<[`Message`](../../message/classes/Message.md)[]\\>\n\n***\n\n### reply()\n\n> **reply**(`body`): `Promise`\\<[`Message`](../../message/classes/Message.md)\\>\n\nPost a reply in this thread.\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `body` | `string` \\| [`RichMessage`](../../../../mentions/interfaces/RichMessage.md) | Plain text, or a rich body composed with msg. |\n\n#### Returns\n\n`Promise`\\<[`Message`](../../message/classes/Message.md)\\>\n\nThe created reply.\n\n***\n\n### root()\n\n> **root**(): [`Message`](../../message/classes/Message.md)\n\nThe message this thread hangs off.\n\n#### Returns\n\n[`Message`](../../message/classes/Message.md)\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `channelId`: `string`; `rootId`: `string`; \\}\n\nSerialize the thread identity without its authenticated client.\n\n#### Returns\n\n\\{ `channelId`: `string`; `rootId`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `channelId` | `string` |\n| `rootId` | `string` |\n\n\n<!-- src/entities/whatsapp/account/classes/WhatsAppAccount.md -->\n# Class: WhatsAppAccount\n\nThe current user's WhatsApp account, connected through the Macro app.\n\n## Extends\n\n- [`MacroEntity`](../../../entity/classes/MacroEntity.md)\\<[`LinkedAccount`](../../../../../generated/storage/types.gen/type-aliases/LinkedAccount.md)\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | - | [`MacroEntity`](../../../entity/classes/MacroEntity.md).[`id`](../../../entity/classes/MacroEntity.md#property-id) |\n| <a id=\"property-identity\"></a> `identity` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | Verified remote identity, absent until pairing succeeds. | - |\n| <a id=\"property-owner\"></a> `owner` | `readonly` | () => `Promise`\\<[`User`](../../../users/user/classes/User.md)\\> | The Macro user who owns this account. | - |\n| <a id=\"property-state\"></a> `state` | `readonly` | () => `Promise`\\<[`LinkedAccountState`](../../../../../generated/storage/types.gen/type-aliases/LinkedAccountState.md)\\> | Account connection state; call refresh before polling it again. | - |\n\n## Methods\n\n### refresh()\n\n> **refresh**(): `Promise`\\<`WhatsAppAccount`\\>\n\nDiscard cached connection state and load its current value.\n\n#### Returns\n\n`Promise`\\<`WhatsAppAccount`\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`LinkedAccount`](../../../../../generated/storage/types.gen/type-aliases/LinkedAccount.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`LinkedAccount`](../../../../../generated/storage/types.gen/type-aliases/LinkedAccount.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`LinkedAccount`](../../../../../generated/storage/types.gen/type-aliases/LinkedAccount.md) |\n| `id` | `string` |\n\n#### Inherited from\n\n[`MacroEntity`](../../../entity/classes/MacroEntity.md).[`toJSON`](../../../entity/classes/MacroEntity.md#tojson)\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `id`): `WhatsAppAccount`\n\nReference an account; reads still enforce the authenticated owner's scope.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `id` | `string` |\n\n#### Returns\n\n`WhatsAppAccount`\n\n***\n\n### from()\n\n> `static` **from**(`client`, `record`): `WhatsAppAccount`\n\nSeed an account handle from an API record.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `record` | [`LinkedAccount`](../../../../../generated/storage/types.gen/type-aliases/LinkedAccount.md) |\n\n#### Returns\n\n`WhatsAppAccount`\n\n\n<!-- src/entities/whatsapp/chat/classes/WhatsAppChat.md -->\n# Class: WhatsAppChat\n\nOne chat of the current user's WhatsApp chat list: a group or a direct chat.\n\n## Extends\n\n- [`MacroEntity`](../../../entity/classes/MacroEntity.md)\\<[`LinkedChat`](../../../../../generated/storage/types.gen/type-aliases/LinkedChat.md)\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-archived\"></a> `archived` | `readonly` | () => `Promise`\\<`boolean`\\> | Archived in WhatsApp. | - |\n| <a id=\"property-canadd\"></a> `canAdd` | `readonly` | () => `Promise`\\<`boolean`\\> | Whether adding it to Macro works now. | - |\n| <a id=\"property-cannotaddreason\"></a> `cannotAddReason` | `readonly` | () => `Promise`\\<`NonNullable`\\<LinkedCannotAdd \\| null \\| undefined\\> \\| `undefined`\\> | Why it can't be added (`not_in_group`, `community`, `own_chat`, `not_in_chat_list`), when it is neither added, shared nor addable. | - |\n| <a id=\"property-community\"></a> `community` | `readonly` | () => `Promise`\\<[`WhatsAppCommunity`](../type-aliases/WhatsAppCommunity.md) \\| `undefined`\\> | The WhatsApp community a group belongs to, if any: the community's own chat, its name, and whether this is its announcement group. | - |\n| <a id=\"property-group\"></a> `group` | `readonly` | () => `Promise`\\<[`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) \\| `undefined`\\> | The current user's own Macro group for this chat, once added. | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | - | [`MacroEntity`](../../../entity/classes/MacroEntity.md).[`id`](../../../entity/classes/MacroEntity.md#property-id) |\n| <a id=\"property-kind\"></a> `kind` | `readonly` | () => `Promise`\\<[`LinkedChatKind`](../../../../../generated/storage/types.gen/type-aliases/LinkedChatKind.md)\\> | `group` or `direct`. | - |\n| <a id=\"property-lastactivityat\"></a> `lastActivityAt` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | Newest activity WhatsApp reported, when known. | - |\n| <a id=\"property-name\"></a> `name` | `readonly` | () => `Promise`\\<`string`\\> | Group subject (or member names), or the other person's name or number. | - |\n| <a id=\"property-pinned\"></a> `pinned` | `readonly` | () => `Promise`\\<`boolean`\\> | Pinned in WhatsApp. | - |\n| <a id=\"property-shared\"></a> `shared` | `readonly` | () => `Promise`\\<[`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) \\| `undefined`\\> | Someone else's Macro group for this chat, shared with the current user. | - |\n\n## Methods\n\n### adopt()\n\n> **adopt**(): `Promise`\\<[`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md)\\>\n\nAdd the chat (a group or a direct chat) to Macro as the current user's\nown; its earlier messages are imported from the phone. Adding it again\nreturns the same chat. Only the owner sends in a direct chat.\n\n#### Returns\n\n`Promise`\\<[`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md)\\>\n\n***\n\n### refresh()\n\n> **refresh**(): `Promise`\\<`WhatsAppChat`\\>\n\nReload the chat's list entry.\n\n#### Returns\n\n`Promise`\\<`WhatsAppChat`\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`LinkedChat`](../../../../../generated/storage/types.gen/type-aliases/LinkedChat.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`LinkedChat`](../../../../../generated/storage/types.gen/type-aliases/LinkedChat.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`LinkedChat`](../../../../../generated/storage/types.gen/type-aliases/LinkedChat.md) |\n| `id` | `string` |\n\n#### Inherited from\n\n[`MacroEntity`](../../../entity/classes/MacroEntity.md).[`toJSON`](../../../entity/classes/MacroEntity.md#tojson)\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `id`): `WhatsAppChat`\n\nReference a chat by its WhatsApp JID.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `id` | `string` |\n\n#### Returns\n\n`WhatsAppChat`\n\n***\n\n### from()\n\n> `static` **from**(`client`, `record`): `WhatsAppChat`\n\nSeed a chat handle from the chat list.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `record` | [`LinkedChat`](../../../../../generated/storage/types.gen/type-aliases/LinkedChat.md) |\n\n#### Returns\n\n`WhatsAppChat`\n\n\n<!-- src/entities/whatsapp/chat/functions/communityOf.md -->\n# Function: communityOf()\n\n> **communityOf**(`client`, `record`): [`WhatsAppCommunity`](../type-aliases/WhatsAppCommunity.md)\n\nA community reference as a handle on the community's own chat.\n\n## Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `record` | [`LinkedCommunityReference`](../../../../../generated/storage/types.gen/type-aliases/LinkedCommunityReference.md) |\n\n## Returns\n\n[`WhatsAppCommunity`](../type-aliases/WhatsAppCommunity.md)\n\n\n<!-- src/entities/whatsapp/chat/type-aliases/WhatsAppCommunity.md -->\n# Type Alias: WhatsAppCommunity\n\n> **WhatsAppCommunity** = \\{ `announcements`: `boolean`; `chat`: [`WhatsAppChat`](../classes/WhatsAppChat.md); `name`: `string`; \\}\n\nThe WhatsApp community a group belongs to.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-announcements\"></a> `announcements` | `boolean` | This group is the community's announcement group. |\n| <a id=\"property-chat\"></a> `chat` | [`WhatsAppChat`](../classes/WhatsAppChat.md) | The community itself, as a chat of the list (it can't be added). |\n| <a id=\"property-name\"></a> `name` | `string` | The community's name. |\n\n\n<!-- src/entities/whatsapp/group/classes/WhatsAppGroup.md -->\n# Class: WhatsAppGroup\n\nIndependently shareable added WhatsApp chat: a group or a direct chat.\n\n## Extends\n\n- [`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md)\\<[`WhatsAppGroupDetail`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppGroupDetail.md)\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Overrides | Inherited from |\n| ------ | ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-backfill\"></a> `backfill` | `readonly` | () => `Promise`\\<[`LinkedBackfill`](../../../../../generated/storage/types.gen/type-aliases/LinkedBackfill.md) \\| `undefined`\\> | Importing earlier messages from the owner's phone after adding, if any. | - | - |\n| <a id=\"property-cansend\"></a> `canSend` | `readonly` | () => `Promise`\\<`boolean`\\> | Whether the caller can send from their own connected account. | - | - |\n| <a id=\"property-community\"></a> `community` | `readonly` | () => `Promise`\\<[`WhatsAppCommunity`](../../chat/type-aliases/WhatsAppCommunity.md) \\| `undefined`\\> | The WhatsApp community this group belongs to, if any: the community's own chat, its name, and whether this is its announcement group. | - | - |\n| <a id=\"property-disappearingseconds\"></a> `disappearingSeconds` | `readonly` | () => `Promise`\\<`number` \\| `undefined`\\> | WhatsApp's disappearing-messages timer in seconds while on; Macro keeps the messages. | - | - |\n| <a id=\"property-entitytype\"></a> `entityType` | `readonly` | `\"whatsapp_group\"` | Canonical sharing and favorites kind. | [`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`entityType`](../../../entity/classes/FavoritableEntity.md#property-entitytype) | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | - | - | [`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`id`](../../../entity/classes/FavoritableEntity.md#property-id) |\n| <a id=\"property-kind\"></a> `kind` | `readonly` | () => `Promise`\\<[`LinkedChatKind`](../../../../../generated/storage/types.gen/type-aliases/LinkedChatKind.md)\\> | `group`, or `direct` for a one-to-one chat (only its owner sends). | - | - |\n| <a id=\"property-limits\"></a> `limits` | `readonly` | () => `Promise`\\<[`LinkedCapabilities`](../../../../../generated/storage/types.gen/type-aliases/LinkedCapabilities.md)\\> | Supported sizes and mutation window. | - | - |\n| <a id=\"property-name\"></a> `name` | `readonly` | () => `Promise`\\<`string`\\> | Display name: the group's, or a direct chat's other person. | - | - |\n| <a id=\"property-owner\"></a> `owner` | `readonly` | () => `Promise`\\<[`User`](../../../users/user/classes/User.md)\\> | Actual owner, independent of WhatsApp membership. | - | - |\n| <a id=\"property-participants\"></a> `participants` | `readonly` | () => `Promise`\\<[`WhatsAppParticipant`](../../participant/classes/WhatsAppParticipant.md)[]\\> | Everyone in the chat, from its roster; empty when no roster is known. | - | - |\n| <a id=\"property-roster\"></a> `roster` | `readonly` | () => `Promise`\\<[`WhatsAppRoster`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppRoster.md) \\| `undefined`\\> | Current remote roster (name, participants, announce), when available. | - | - |\n| <a id=\"property-sendingidentity\"></a> `sendingIdentity` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | Caller's own verified sending identity. | - | - |\n| <a id=\"property-sendreason\"></a> `sendReason` | `readonly` | () => `Promise`\\<`NonNullable`\\<LinkedReplyBlock \\| null \\| undefined\\> \\| `undefined`\\> | Reason sending is blocked. | - | - |\n| <a id=\"property-unreadcount\"></a> `unreadCount` | `readonly` | () => `Promise`\\<`number`\\> | Per-user unread count. | - | - |\n\n## Methods\n\n### delivery()\n\n> **delivery**(`sends`): `Promise`\\<[`WhatsAppSend`](../../send/classes/WhatsAppSend.md)[]\\>\n\nRead delivery for selected caller-owned intents or messages.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `sends` | ([`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md) \\| [`WhatsAppSend`](../../send/classes/WhatsAppSend.md))[] |\n\n#### Returns\n\n`Promise`\\<[`WhatsAppSend`](../../send/classes/WhatsAppSend.md)[]\\>\n\n***\n\n### detach()\n\n> **detach**(): `Promise`\\<`void`\\>\n\nStop observation while preserving history and established sharing.\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### favorite()\n\n> **favorite**(): `Promise`\\<`WhatsAppGroup`\\>\n\nAdd this entity to the user's favorites. Returns this handle for chaining.\nPlain unwrap: favoriting alters the user's favorites collection, not this\nentity's own detail, so there's nothing cached to invalidate.\n\n#### Returns\n\n`Promise`\\<`WhatsAppGroup`\\>\n\n#### Inherited from\n\n[`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`favorite`](../../../entity/classes/FavoritableEntity.md#favorite)\n\n***\n\n### markRead()\n\n> **markRead**(`message`): `Promise`\\<`void`\\>\n\nAdvance the caller's own read cursor.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `message` | [`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### messageAttachments()\n\n> **messageAttachments**(`messages`): `Promise`\\<\\{ `attachments`: \\{ `document`: [`Document`](../../../documents/document/classes/Document.md) \\| `undefined`; `fileName`: `string`; `mime`: `string`; `ordinal`: `number`; `size`: `number`; `state`: [`LinkedAttachmentState`](../../../../../generated/storage/types.gen/type-aliases/LinkedAttachmentState.md); \\}[]; `message`: [`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md); \\}[]\\>\n\nRead attachment states for selected messages.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `messages` | [`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md)[] |\n\n#### Returns\n\n`Promise`\\<\\{ `attachments`: \\{ `document`: [`Document`](../../../documents/document/classes/Document.md) \\| `undefined`; `fileName`: `string`; `mime`: `string`; `ordinal`: `number`; `size`: `number`; `state`: [`LinkedAttachmentState`](../../../../../generated/storage/types.gen/type-aliases/LinkedAttachmentState.md); \\}[]; `message`: [`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md); \\}[]\\>\n\n***\n\n### messages()\n\n> **messages**(`options?`): `AsyncGenerator`\\<[`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md)\\>\n\nIterate newest-first timeline pages lazily.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options?` | \\{ `limit?`: `number`; \\} |\n| `options.limit?` | `number` |\n\n#### Returns\n\n`AsyncGenerator`\\<[`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md)\\>\n\n***\n\n### permission()\n\n> **permission**(): `Promise`\\<\\{ `permission`: [`EntityPermission`](../../../../../generated/storage/types.gen/type-aliases/EntityPermission.md); `status`: `\"access\"`; \\} \\| \\{ `status`: `\"no_access\"`; \\}\\>\n\nRead the caller's effective permission on this entity.\n\n#### Returns\n\n`Promise`\\<\\{ `permission`: [`EntityPermission`](../../../../../generated/storage/types.gen/type-aliases/EntityPermission.md); `status`: `\"access\"`; \\} \\| \\{ `status`: `\"no_access\"`; \\}\\>\n\n#### Inherited from\n\n[`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`permission`](../../../entity/classes/FavoritableEntity.md#permission)\n\n***\n\n### permissions()\n\n> **permissions**(): `Promise`\\<[`SharePermissionV2`](../../../../../generated/storage/types.gen/type-aliases/SharePermissionV2.md)\\>\n\nRead standard link/team sharing settings.\n\n#### Returns\n\n`Promise`\\<[`SharePermissionV2`](../../../../../generated/storage/types.gen/type-aliases/SharePermissionV2.md)\\>\n\n***\n\n### refresh()\n\n> **refresh**(): `Promise`\\<`WhatsAppGroup`\\>\n\nReload detail, permissions and caller capabilities.\n\n#### Returns\n\n`Promise`\\<`WhatsAppGroup`\\>\n\n***\n\n### reply()\n\n> **reply**(`content`, `options`): `Promise`\\<[`WhatsAppSend`](../../send/classes/WhatsAppSend.md)\\>\n\nPersonal sessions and owner API credentials can send. Bots never send.\nPreserve the idempotency key; uncertain outcomes are never automatically resent.\nThe server enforces one request per second per user.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `content` | [`WhatsAppReply`](../type-aliases/WhatsAppReply.md) |\n| `options` | \\{ `idempotencyKey`: `string`; `replyTo?`: [`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md); \\} |\n| `options.idempotencyKey` | `string` |\n| `options.replyTo?` | [`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md) |\n\n#### Returns\n\n`Promise`\\<[`WhatsAppSend`](../../send/classes/WhatsAppSend.md)\\>\n\n***\n\n### sends()\n\n> **sends**(): `Promise`\\<[`WhatsAppSend`](../../send/classes/WhatsAppSend.md)[]\\>\n\nRead only the caller's pending, uncertain or failed sends.\n\n#### Returns\n\n`Promise`\\<[`WhatsAppSend`](../../send/classes/WhatsAppSend.md)[]\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`WhatsAppGroupDetail`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppGroupDetail.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`WhatsAppGroupDetail`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppGroupDetail.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`WhatsAppGroupDetail`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppGroupDetail.md) |\n| `id` | `string` |\n\n#### Inherited from\n\n[`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`toJSON`](../../../entity/classes/FavoritableEntity.md#tojson)\n\n***\n\n### unfavorite()\n\n> **unfavorite**(): `Promise`\\<`WhatsAppGroup`\\>\n\nRemove this entity from the user's favorites. Returns this handle for chaining.\n\n#### Returns\n\n`Promise`\\<`WhatsAppGroup`\\>\n\n#### Inherited from\n\n[`FavoritableEntity`](../../../entity/classes/FavoritableEntity.md).[`unfavorite`](../../../entity/classes/FavoritableEntity.md#unfavorite)\n\n***\n\n### updatePermissions()\n\n> **updatePermissions**(`update`): `Promise`\\<`void`\\>\n\nActual owner updates standard link/team sharing settings.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `update` | [`UpdateSharePermissionRequestV2`](../../../../../generated/storage/types.gen/type-aliases/UpdateSharePermissionRequestV2.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### upload()\n\n> **upload**(`file`): `Promise`\\<[`WhatsAppUpload`](../../upload/classes/WhatsAppUpload.md)\\>\n\nStage a supported attachment for a deliberate send.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `file` | `Blob` \\| `File` |\n\n#### Returns\n\n`Promise`\\<[`WhatsAppUpload`](../../upload/classes/WhatsAppUpload.md)\\>\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `id`): `WhatsAppGroup`\n\nReference an adopted group; access is checked on each request.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `id` | `string` |\n\n#### Returns\n\n`WhatsAppGroup`\n\n\n<!-- src/entities/whatsapp/group/type-aliases/WhatsAppReply.md -->\n# Type Alias: WhatsAppReply\n\n> **WhatsAppReply** = \\{ `mentions?`: [`WhatsAppParticipant`](../../participant/classes/WhatsAppParticipant.md)[]; `text`: `string`; `type`: `\"text\"`; \\} \\| \\{ `caption?`: `string`; `type`: `\"media\"`; `upload`: [`WhatsAppUpload`](../../upload/classes/WhatsAppUpload.md); \\} \\| \\{ `message`: [`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md); `operation`: `\"reaction\"` \\| `\"edit\"` \\| `\"delete\"`; `text?`: `string`; `type`: `\"mutation\"`; \\}\n\nDeliberate content from the credential owner's own WhatsApp account.\n\n## Union Members\n\n### Type Literal\n\n\\{ `mentions?`: [`WhatsAppParticipant`](../../participant/classes/WhatsAppParticipant.md)[]; `text`: `string`; `type`: `\"text\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `mentions?` | [`WhatsAppParticipant`](../../participant/classes/WhatsAppParticipant.md)[] | Participants mentioned (from `participants()`); the text names each as `@<mentionToken>`. |\n| `text` | `string` | - |\n| `type` | `\"text\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `caption?`: `string`; `type`: `\"media\"`; `upload`: [`WhatsAppUpload`](../../upload/classes/WhatsAppUpload.md); \\}\n\n***\n\n### Type Literal\n\n\\{ `message`: [`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md); `operation`: `\"reaction\"` \\| `\"edit\"` \\| `\"delete\"`; `text?`: `string`; `type`: `\"mutation\"`; \\}\n\n\n<!-- src/entities/whatsapp/message/classes/WhatsAppMessage.md -->\n# Class: WhatsAppMessage\n\nMessage in an independently shared WhatsApp group.\n\n## Extends\n\n- [`MacroEntity`](../../../entity/classes/MacroEntity.md)\\<[`WhatsAppGroupMessage`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppGroupMessage.md)\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-attachments\"></a> `attachments` | `readonly` | () => `Promise`\\<\\{ `document`: [`Document`](../../../documents/document/classes/Document.md) \\| `undefined`; `durationSeconds`: `number` \\| `undefined`; `fileName`: `string`; `height`: `number` \\| `undefined`; `mime`: `string`; `ordinal`: `number`; `presentation`: [`LinkedMediaPresentation`](../../../../../generated/storage/types.gen/type-aliases/LinkedMediaPresentation.md) \\| `undefined`; `size`: `number`; `state`: [`LinkedAttachmentState`](../../../../../generated/storage/types.gen/type-aliases/LinkedAttachmentState.md); `width`: `number` \\| `undefined`; \\}[]\\> | Attachment state and imported document handles. | - |\n| <a id=\"property-body\"></a> `body` | `readonly` | () => `Promise`\\<`string`\\> | Plain WhatsApp text. | - |\n| <a id=\"property-deleted\"></a> `deleted` | `readonly` | () => `Promise`\\<`boolean`\\> | Deleted for everyone. | - |\n| <a id=\"property-deliverystate\"></a> `deliveryState` | `readonly` | () => `Promise`\\<`NonNullable`\\<LinkedDeliveryState \\| null \\| undefined\\> \\| `undefined`\\> | Caller-owned send's delivery state, when present. | - |\n| <a id=\"property-editedat\"></a> `editedAt` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | Last edit time. | - |\n| <a id=\"property-forwarded\"></a> `forwarded` | `readonly` | () => `Promise`\\<`boolean`\\> | Forwarded from another chat. | - |\n| <a id=\"property-group\"></a> `group` | `readonly` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) | The chat this message is in. | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | - | [`MacroEntity`](../../../entity/classes/MacroEntity.md).[`id`](../../../entity/classes/MacroEntity.md#property-id) |\n| <a id=\"property-kind\"></a> `kind` | `readonly` | () => `Promise`\\<[`WhatsAppMessageKind`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppMessageKind.md)\\> | `message`, or `system` for something that happened in the group (see `rich`). | - |\n| <a id=\"property-mentions\"></a> `mentions` | `readonly` | () => `Promise`\\<[`WhatsAppMention`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppMention.md)[]\\> | People the body @-mentions: `@<token>` in the body is this person. | - |\n| <a id=\"property-reactions\"></a> `reactions` | `readonly` | () => `Promise`\\<[`WhatsAppGroupReaction`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppGroupReaction.md)[]\\> | Grouped emoji counts and caller's own reaction. | - |\n| <a id=\"property-replyto\"></a> `replyTo` | `readonly` | () => `Promise`\\<`WhatsAppMessage` \\| `undefined`\\> | Quoted message in this group. | - |\n| <a id=\"property-rich\"></a> `rich` | `readonly` | () => `Promise`\\<`NonNullable`\\<WhatsAppRichContent \\| null \\| undefined\\> \\| `undefined`\\> | Poll (with tallies), location, contact cards, event or system line. | - |\n| <a id=\"property-sender\"></a> `sender` | `readonly` | () => `Promise`\\<[`WhatsAppGroupSender`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppGroupSender.md)\\> | Protocol-verified sender association and display name. | - |\n| <a id=\"property-sentat\"></a> `sentAt` | `readonly` | () => `Promise`\\<`string`\\> | WhatsApp timestamp. | - |\n| <a id=\"property-viewonce\"></a> `viewOnce` | `readonly` | () => `Promise`\\<`boolean`\\> | Sent as view-once in WhatsApp; Macro keeps and shows it like any media. | - |\n\n## Methods\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`WhatsAppGroupMessage`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppGroupMessage.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`WhatsAppGroupMessage`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppGroupMessage.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`WhatsAppGroupMessage`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppGroupMessage.md) |\n| `id` | `string` |\n\n#### Inherited from\n\n[`MacroEntity`](../../../entity/classes/MacroEntity.md).[`toJSON`](../../../entity/classes/MacroEntity.md#tojson)\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `group`, `id`): `WhatsAppMessage`\n\nReference a message within its original group.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `group` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) |\n| `id` | `string` |\n\n#### Returns\n\n`WhatsAppMessage`\n\n***\n\n### from()\n\n> `static` **from**(`client`, `group`, `record`): `WhatsAppMessage`\n\nSeed a message handle from a timeline response.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `group` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) |\n| `record` | [`WhatsAppGroupMessage`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppGroupMessage.md) |\n\n#### Returns\n\n`WhatsAppMessage`\n\n\n<!-- src/entities/whatsapp/namespace/classes/WhatsAppNamespace.md -->\n# Class: WhatsAppNamespace\n\nOperate on an account already paired through the Macro app.\n\n## Constructors\n\n### Constructor\n\n> **new WhatsAppNamespace**(`client`): `WhatsAppNamespace`\n\nBind existing-account operations to this authenticated client.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`WhatsAppNamespace`\n\n## Methods\n\n### account()\n\n> **account**(): `Promise`\\<[`WhatsAppAccount`](../../account/classes/WhatsAppAccount.md) \\| `undefined`\\>\n\nCurrent owner's account, or undefined when no account has been connected.\n\n#### Returns\n\n`Promise`\\<[`WhatsAppAccount`](../../account/classes/WhatsAppAccount.md) \\| `undefined`\\>\n\n***\n\n### byId()\n\n> **byId**(`id`): [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md)\n\nReference an adopted entity without fetching it.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n[`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md)\n\n***\n\n### groups()\n\n> **groups**(): `Promise`\\<[`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md)[]\\>\n\nAdopted groups shared with the caller, including without WhatsApp.\n\n#### Returns\n\n`Promise`\\<[`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md)[]\\>\n\n\n<!-- src/entities/whatsapp/participant/classes/WhatsAppParticipant.md -->\n# Class: WhatsAppParticipant\n\nSomeone in an added WhatsApp chat, from its roster; mention them in a text reply.\n\n## Properties\n\n| Property | Modifier | Type | Description |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-group\"></a> `group` | `readonly` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) | The chat whose roster lists them. |\n| <a id=\"property-id\"></a> `id` | `readonly` | `string` | Their WhatsApp id: correlation data, not a Macro user. |\n\n## Accessors\n\n### admin\n\n#### Get Signature\n\n> **get** **admin**(): `boolean` \\| `undefined`\n\nWhether they administer the group, when read from the roster.\n\n##### Returns\n\n`boolean` \\| `undefined`\n\n***\n\n### displayName\n\n#### Get Signature\n\n> **get** **displayName**(): `string` \\| `undefined`\n\nTheir WhatsApp name, untrusted, when the roster had one.\n\n##### Returns\n\n`string` \\| `undefined`\n\n***\n\n### mentionToken\n\n#### Get Signature\n\n> **get** **mentionToken**(): `string`\n\nThe digits a text reply writes as `@<digits>` to mention them.\n\n##### Returns\n\n`string`\n\n## Methods\n\n### toJSON()\n\n> **toJSON**(): \\{ `admin`: `boolean` \\| `undefined`; `displayName`: `string` \\| `undefined`; `group`: `string`; `id`: `string`; \\}\n\nSerialize the participant reference without credentials.\n\n#### Returns\n\n\\{ `admin`: `boolean` \\| `undefined`; `displayName`: `string` \\| `undefined`; `group`: `string`; `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `admin` | `boolean` \\| `undefined` |\n| `displayName` | `string` \\| `undefined` |\n| `group` | `string` |\n| `id` | `string` |\n\n***\n\n### byId()\n\n> `static` **byId**(`group`, `id`): `WhatsAppParticipant`\n\nReference a participant of a chat by WhatsApp id.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `group` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) |\n| `id` | `string` |\n\n#### Returns\n\n`WhatsAppParticipant`\n\n***\n\n### from()\n\n> `static` **from**(`group`, `record`): `WhatsAppParticipant`\n\nSeed a participant from the chat's roster.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `group` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) |\n| `record` | [`WhatsAppParticipant`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppParticipant.md) |\n\n#### Returns\n\n`WhatsAppParticipant`\n\n\n<!-- src/entities/whatsapp/send/classes/WhatsAppSend.md -->\n# Class: WhatsAppSend\n\nOne deliberate send intent. Unknown outcomes must never be automatically resent.\n\n## Extends\n\n- [`MacroEntity`](../../../entity/classes/MacroEntity.md)\\<[`LinkedSendProgress`](../../../../../generated/storage/types.gen/type-aliases/LinkedSendProgress.md)\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-createdat\"></a> `createdAt` | `readonly` | () => `Promise`\\<`string`\\> | When the send intent was created. | - |\n| <a id=\"property-errorcode\"></a> `errorCode` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | Sanitized failure code, when present. | - |\n| <a id=\"property-group\"></a> `group` | `readonly` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) | Group entity containing this send. | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | - | [`MacroEntity`](../../../entity/classes/MacroEntity.md).[`id`](../../../entity/classes/MacroEntity.md#property-id) |\n| <a id=\"property-message\"></a> `message` | `readonly` | () => `Promise`\\<[`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md) \\| `undefined`\\> | Group message once WhatsApp accepted the send. | - |\n| <a id=\"property-state\"></a> `state` | `readonly` | () => `Promise`\\<[`LinkedDeliveryState`](../../../../../generated/storage/types.gen/type-aliases/LinkedDeliveryState.md)\\> | Last observed delivery state; refresh explicitly to poll again. | - |\n\n## Methods\n\n### refresh()\n\n> **refresh**(): `Promise`\\<`WhatsAppSend`\\>\n\nFetch current delivery state without retrying or submitting the message.\n\n#### Returns\n\n`Promise`\\<`WhatsAppSend`\\>\n\n***\n\n### request()\n\n> **request**(): `Promise`\\<\\{ `idempotencyKey`: `string`; `message`: [`WhatsAppReply`](../../group/type-aliases/WhatsAppReply.md); `replyTo?`: [`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md); \\}\\>\n\nInspect the original intent for reconciliation; never resubmit an unknown outcome automatically.\n\n#### Returns\n\n`Promise`\\<\\{ `idempotencyKey`: `string`; `message`: [`WhatsAppReply`](../../group/type-aliases/WhatsAppReply.md); `replyTo?`: [`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md); \\}\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`LinkedSendProgress`](../../../../../generated/storage/types.gen/type-aliases/LinkedSendProgress.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`LinkedSendProgress`](../../../../../generated/storage/types.gen/type-aliases/LinkedSendProgress.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`LinkedSendProgress`](../../../../../generated/storage/types.gen/type-aliases/LinkedSendProgress.md) |\n| `id` | `string` |\n\n#### Inherited from\n\n[`MacroEntity`](../../../entity/classes/MacroEntity.md).[`toJSON`](../../../entity/classes/MacroEntity.md#tojson)\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `group`, `id`): `WhatsAppSend`\n\nReference a send intent within its original group.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `group` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) |\n| `id` | `string` |\n\n#### Returns\n\n`WhatsAppSend`\n\n***\n\n### from()\n\n> `static` **from**(`client`, `group`, `record`): `WhatsAppSend`\n\nSeed a send handle from a server response.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `group` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) |\n| `record` | [`LinkedSendProgress`](../../../../../generated/storage/types.gen/type-aliases/LinkedSendProgress.md) |\n\n#### Returns\n\n`WhatsAppSend`\n\n\n<!-- src/entities/whatsapp/upload/classes/WhatsAppUpload.md -->\n# Class: WhatsAppUpload\n\nA staged attachment scoped to one adopted group; use it in a deliberate media send.\n\n## Properties\n\n| Property | Modifier | Type | Description |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-filename\"></a> `filename?` | `readonly` | `string` | Display filename supplied by the server. |\n| <a id=\"property-group\"></a> `group` | `readonly` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) | The chat this upload can be sent to. |\n| <a id=\"property-id\"></a> `id` | `readonly` | `string` | Correlation identity of the staged upload. |\n| <a id=\"property-kind\"></a> `kind?` | `readonly` | [`LinkedMediaKind`](../../../../../generated/storage/types.gen/type-aliases/LinkedMediaKind.md) | Media category supplied by the server. |\n\n## Methods\n\n### toJSON()\n\n> **toJSON**(): \\{ `filename`: `string` \\| `undefined`; `group`: `string`; `id`: `string`; `kind`: [`LinkedMediaKind`](../../../../../generated/storage/types.gen/type-aliases/LinkedMediaKind.md) \\| `undefined`; \\}\n\nSerialize the upload reference without credentials.\n\n#### Returns\n\n\\{ `filename`: `string` \\| `undefined`; `group`: `string`; `id`: `string`; `kind`: [`LinkedMediaKind`](../../../../../generated/storage/types.gen/type-aliases/LinkedMediaKind.md) \\| `undefined`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `filename` | `string` \\| `undefined` |\n| `group` | `string` |\n| `id` | `string` |\n| `kind` | [`LinkedMediaKind`](../../../../../generated/storage/types.gen/type-aliases/LinkedMediaKind.md) \\| `undefined` |\n\n***\n\n### byId()\n\n> `static` **byId**(`group`, `id`): `WhatsAppUpload`\n\nReference a previously staged upload in its original group.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `group` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) |\n| `id` | `string` |\n\n#### Returns\n\n`WhatsAppUpload`\n\n***\n\n### from()\n\n> `static` **from**(`group`, `record`): `WhatsAppUpload`\n\nSeed a handle from the server's upload receipt.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `group` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) |\n| `record` | [`LinkedUploadedAttachment`](../../../../../generated/storage/types.gen/type-aliases/LinkedUploadedAttachment.md) |\n\n#### Returns\n\n`WhatsAppUpload`\n"
},
{
"name": "crm",
diff --git a/crates/agent_code_mode/src/domain/operations.json b/crates/agent_code_mode/src/domain/operations.json
index 8aeff35d18..b542358715 100644
--- a/crates/agent_code_mode/src/domain/operations.json
+++ b/crates/agent_code_mode/src/domain/operations.json
@@ -590,6 +590,7 @@
"storage.linkedDelivery": "Linked Delivery",
"storage.whatsappGroupMessages": "Whatsapp Group Messages",
"storage.linkedMessageAttachments": "Linked Message Attachments",
+ "storage.whatsappGroupMessage": "Whatsapp Group Message",
"storage.whatsappGroupPermissions": "Whatsapp Group Permissions",
"storage.whatsappGroupUpdatePermissions": "Whatsapp Group Update Permissions",
"storage.whatsappGroupRead": "Whatsapp Group Read",
diff --git a/crates/code_execution/src/outbound/deno/sdk.mjs b/crates/code_execution/src/outbound/deno/sdk.mjs
index 7b622dc790..ad451f3217 100644
--- a/crates/code_execution/src/outbound/deno/sdk.mjs
+++ b/crates/code_execution/src/outbound/deno/sdk.mjs
@@ -1,5 +1,5 @@
// Generated by packages/code-mode-sdk/scripts/generate.ts.
-async function uO($,O,j){if(!Number.isInteger(O)||O<1)throw RangeError(`concurrency limit must be a positive integer, got ${O}`);let x=Array($.length),S=0,K=async()=>{while(S<$.length){let X=S;S+=1,x[X]=await j($[X])}},Z=Array.from({length:Math.min(O,$.length)},K);return await Promise.all(Z),x}class B${loader;value;inflight;constructor($,O){this.loader=$;this.value=O}get(){if(this.value!==void 0)return Promise.resolve(this.value);return this.inflight??=this.loader().then(($)=>{return this.value=$,$}),this.inflight}peek(){return this.value}clear(){this.value=void 0,this.inflight=void 0}}async function*u($){let O;do{let j=await $(O),x=j.nextCursor??void 0;if(O!==void 0&&x!==void 0&&JSON.stringify(x)===JSON.stringify(O))throw Error("Pagination cursor did not advance");yield*j.items,O=x}while(O!==void 0)}class f extends Error{constructor($){super($);this.name="MacroError"}}class QO extends f{status;data;constructor($,O){super(`Macro API error ${$}`);this.status=$;this.data=O;this.name="MacroApiError"}}class E extends f{constructor($){super($);this.name="MacroNotFoundError"}}function G($){if($.error!==void 0)throw new QO($.response?.status??0,$.error);return $.data}class P{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new B$(()=>this.fetch(),j)}field($){return async()=>(await this.detail.get())[$]??void 0}mappedField($,O){return async()=>O((await this.detail.get())[$]??void 0)}toJSON(){let $=this.detail.peek();return $===void 0?{id:this.id}:{id:this.id,detail:$}}async mutate($){let O=G(await $(this.client));return this.detail.clear(),O}}class z$ extends P{async permission(){return G(await this.client.storage.getEntityPermission({path:{entity_type:this.entityType,entity_id:this.id}}))}async favorite(){return G(await this.client.storage.addFavorite({body:{entityId:this.id,entityType:this.entityType}})),this}async unfavorite(){return G(await this.client.storage.removeFavoriteByEntity({path:{entity_type:this.entityType,entity_id:this.id}})),this}}class X$ extends z${propertyReference(){return{entity_type:this.propertyEntityType,entity_id:this.id}}async properties($){let{properties:O}=G(await this.client.properties.getEntityProperties({path:{entity_type:this.propertyEntityType,entity_id:this.id},query:$?.includeMetadata!==void 0?{include_metadata:$.includeMetadata}:void 0}));return O}async setProperty($,O){G(await this.client.properties.setEntityProperty({path:{...this.propertyReference(),property_id:$.id},body:{value:O??null}}))}async updatePropertyOptions($){return G(await this.client.properties.bulkUpdateEntityPropertyOptions({path:this.propertyReference(),body:{properties:$.map((O)=>({property_id:O.property.id,...O.add?{add_option_ids:O.add.map((j)=>j.id)}:{},...O.remove?{remove_option_ids:O.remove.map((j)=>j.id)}:{}}))}}))}async deleteProperty($){G(await this.client.properties.deleteEntityProperty({path:{entity_property_id:$.property.id}}))}}var f6={"<":"\\u003c",">":"\\u003e","&":"\\u0026"};function a$($,O){let j=JSON.stringify(O).replace(/[<>&]/g,(x)=>f6[x]??x);return`<${$}>${j}</${$}>`}function b6($){return typeof $==="object"&&$!==null&&typeof $.toMention==="function"}var k6={toMention:()=>({tag:a$("m-group-mention",{groupAlias:"here"}),mention:{entity_type:"group",entity_id:"here"}})};function g6($,...O){let j="",x=[];for(let[S,K]of $.entries()){j+=K;let Z=O[S];if(Z===void 0)continue;if(b6(Z)){let X=Z.toMention();j+=X.tag,x.push(X.mention)}else j+=String(Z)}return{content:j,mentions:y6(x)}}function y6($){let O=new Set;return $.filter((j)=>{let x=`${j.entity_type}:${j.entity_id}`;if(O.has(x))return!1;return O.add(x),!0})}function O$($){return typeof $==="string"?{content:$,mentions:[]}:$}class W$ extends P{static byId($,O){return new W$($,O)}static from($,O){return new W$($,O.id,O)}async fetch(){let $=G(await this.client.storage.listHarnesses()).find((O)=>O.id===this.id);if(!$)throw new E(`Harness ${this.id} is unavailable`);return $}name=this.field("name");connected=this.field("connected");kind=this.field("kind");async delete(){await this.mutate(($)=>$.storage.deleteHarness({path:{harness_id:this.id}}))}}class I$ extends P{static byId($,O){return new I$($,O)}static from($,O){return new I$($,O.bot.id,O)}async fetch(){let $=G(await this.client.storage.listAgents()).find((O)=>O.bot.id===this.id);if(!$)throw new E(`Agent ${this.id} is unavailable`);return $}name=this.mappedField("bot",($)=>$.name);instructions=this.field("instructions");defaultModel=this.field("default_model");channels=this.mappedField("channel_ids",($)=>$.map((O)=>b.byId(this.client,O)));host=this.mappedField("harness_id",($)=>$?W$.byId(this.client,$):void 0);async update($){await this.mutate((O)=>O.storage.updateAgent({path:{agent_id:this.id},body:yx($)}))}}function yx($){let{channels:O,team:j,host:x,autoAcceptPermissions:S,avatarUrl:K,channelScope:Z,defaultModel:X,isCoding:Y,...L}=$;return{...L,channel_ids:O?.map((Q)=>Q.id),team_id:j?.id,harness_id:x?.id,auto_accept_permissions:S,avatar_url:K,channel_scope:Z,default_model:X,is_coding:Y}}async function Wj($,O,j){let{channelId:x,thread:S}=v6(O);if(await h6($)){let{id:Z}=G(await $.storage.entityMessageCreate({path:{parent_type:"channel",parent_id:x},body:{content:j.content,mentions:j.mentions,attachments:[],thread_id:S?.rootId??null,nonce:crypto.randomUUID()}}));return Z}if(S)throw new f("a user-owned bot can only post via the channel webhook endpoint, which "+"does not support threads — use a team-owned bot, or requestedAs(user), "+"to reply in a thread");let{message_id:K}=G(await $.storage.postChannelBotWebhook({path:{channel_id:x},body:{content:j.content},headers:{"x-macro-bot-scope":"user"}}));return K}function v6($){return"rootId"in $?{channelId:$.channelId,thread:$}:{channelId:$.id}}async function h6($){if($.authConfig.type!=="bot"||$.hasActingUser())return!0;let{owner:O}=await $.selfBot();return O?.type==="team"}class h${client;channelId;rootId;constructor($,O,j){this.client=$;this.channelId=O;this.rootId=j}toJSON(){return{channelId:this.channelId,rootId:this.rootId}}channel(){return b.byId(this.client,this.channelId)}root(){return e.byId(this.client,this.channelId,this.rootId)}async replies(){let{replies:$}=G(await this.client.storage.entityMessageGetThread({path:{parent_type:"channel",parent_id:this.channelId,id:this.rootId}}));return $.map((O)=>e.from(this.client,this.channelId,O))}async reply($){let O=await Wj(this.client,this,O$($));return e.byId(this.client,this.channelId,O)}}class e extends z${channelId;mentions;entityType="channel_message";constructor($,O,j,x=[],S){super($,j,S);this.channelId=O;this.mentions=x}get path(){return{parent_type:"channel",parent_id:this.channelId,id:this.id}}async fetch(){return G(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j,x=[]){return new e($,O,j,x)}static from($,O,j){return new e($,O,j.id,j.mentions,j)}content=this.field("content");createdAt=this.field("created_at");editedAt=this.field("edited_at");updatedAt=this.field("updated_at");async author(){return M.byId(this.client,(await this.detail.get()).sender_id)}channel(){return b.byId(this.client,this.channelId)}thread(){return new h$(this.client,this.channelId,this.id)}async react($){return await this.mutate((O)=>O.storage.entityMessageReact({path:this.path,body:{add:!0,emoji:$}})),this}async unreact($){return await this.mutate((O)=>O.storage.entityMessageReact({path:this.path,body:{add:!1,emoji:$}})),this}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}async reply($){return this.thread().reply($)}}class Lj{client;channel;record;constructor($,O,j){this.client=$;this.channel=O;this.record=j}agent(){return I$.byId(this.client,this.record.botId)}sessions(){return this.record.sessions.map(($)=>({session:i.byId(this.client,$.sessionId),isCurrent:$.isCurrent,createdAt:$.createdAt}))}turns(){return this.record.turns.map(($)=>new vx(this.client,this,$))}async startFresh($){G(await this.client.agentHarness.startFreshAgentConversation({path:{channel_id:this.channel.id,bot_id:this.record.botId},body:{sessionId:$.id}}))}toJSON(){return{channelId:this.channel.id,agentId:this.record.botId}}}class vx{client;conversation;record;constructor($,O,j){this.client=$;this.conversation=O;this.record=j}source(){return e.byId(this.client,this.conversation.channel.id,this.record.sourceMessageId)}session(){return i.byId(this.client,this.record.sessionId)}async retry($){G(await this.client.agentHarness.retryAgentConversationTurn({path:{channel_id:this.conversation.channel.id,bot_id:this.conversation.agent().id,source:this.record.sourceMessageId},body:{actionId:$}}))}toJSON(){return{channelId:this.conversation.channel.id,sourceMessageId:this.record.sourceMessageId}}}class L$ extends P{parent;toJSON(){return{...super.toJSON(),parentType:this.parent.type,parentId:this.parent.entity.id}}constructor($,O,j){super($,j);this.parent=O}static byId($,O,j){return new L$($,O,j)}get path(){return{parent_type:this.parent.type,parent_id:this.parent.entity.id,id:this.id}}async fetch(){return G(await this.client.storage.entityMessageGetThread({path:this.path})).state}resolved=this.field("resolved");async update($){let O={resolved:$.resolved,detach_anchor:$.detachAnchor,nonce:$.nonce};await this.mutate((j)=>j.storage.entityMessagePatchThread({path:this.path,body:O}))}async delete($){await this.mutate((O)=>O.storage.entityMessageDeleteThread({path:this.path,query:{nonce:$}}))}}async function w$($,O,j,x){for(let K of[...x?.messages??[],...x?.around?[x.around]:[]]){let Z="channelId"in K?{type:"channel",id:K.channelId}:("documentId"in K)?{type:"document",id:K.documentId}:("callId"in K)?{type:"call",id:K.callId}:K.parent;if(Z.type!==O.type||Z.id!==O.entity.id)throw Error("Timeline message belongs to another resource")}let S=G(await $.storage.messageTimelineEntries({path:{parent_type:O.type,parent_id:O.entity.id},query:{selection:x?JSON.stringify({cursor:x.cursor,around:x.around?.id,ids:x.messages?.map((K)=>K.id),activity_after:x.activityAfter,activity_before:x.activityBefore,anchored:x.anchored,direction:x.direction,include_deleted_threads:x.includeDeletedThreads,limit:x.limit}):void 0}}));return{entries:S.entries.map((K)=>{if(K.type==="activity")return{type:"activity",activity:{...K.activity,actor:M.byId($,K.activity.actor_id)}};return{type:"message",message:j(K.message)}}),nextCursor:S.next_cursor??void 0,previousCursor:S.previous_cursor??void 0}}var m6=50;function x$($){let{filters:O,type:j,make:x,includeCrm:S}=$;return(K,Z,X)=>{let Y=X?.searchOn??"name_content",L=X?.pageSize??m6;return u(async(Q)=>{let{results:J,next_cursor:I}=G(await K.search.unifiedSearch({body:{query:Z,match_type:"partial",search_on:Y,...O?{filters:O}:{},...S?{include_crm:!0}:{}},query:{page_size:L,...Q?{cursor:Q}:{}}}));return{items:J.filter((B)=>B.type===j).map((B)=>x(K,B)),nextCursor:I}})}}class JO{client;channel;record;constructor($,O,j){this.client=$;this.channel=O;this.record=j}get id(){return this.record.id}user(){return M.byId(this.client,this.record.user_id)}createdAt(){return this.record.created_at}async recordInteraction($){return new JO(this.client,this.channel,G(await this.client.storage.postActivity({body:{activity_type:$,channel_id:this.channel.id}})))}toJSON(){return this.record}}class b extends X${async recordActivity($){return new JO(this.client,this,G(await this.client.storage.postActivity({body:{activity_type:$,channel_id:this.id}})))}async setPicture($){await this.mutate((O)=>O.storage.setChannelPicture({path:{channel_id:this.id},body:{profile_picture_id:$?.id??null}}))}messageThreadById($){return L$.byId(this.client,{type:"channel",entity:this},$)}timelinePage($){return w$(this.client,{type:"channel",entity:this},(O)=>e.from(this.client,this.id,O),$)}async agentConversations(){return G(await this.client.agentHarness.listAgentConversations({path:{channel_id:this.id}})).conversations.map(($)=>new Lj(this.client,this,$))}entityType="channel";propertyEntityType="CHANNEL";async fetch(){return G(await this.client.storage.getChannel({path:{channel_id:this.id}}))}static byId($,O){return new b($,O)}static async dm($,O){let{channel_id:j}=G(await $.storage.getOrCreateDm({body:{recipient_id:O.id}}));return new b($,j)}static async private($,O){let{channel_id:j}=G(await $.storage.getOrCreatePrivate({body:{recipients:O.map((x)=>x.id)}}));return new b($,j)}static async create($,O){let{id:j}=G(await $.storage.createChannel({body:{channel_type:O.type,name:O.name??null,participants:(O.participants??[]).map((x)=>x.id),team_id:O.team?.id??null}}));return new b($,j)}name=this.field("channel_name");type=this.field("channel_type");async send($,O){let j=await Wj(this.client,O?.thread??this,O$($));return e.byId(this.client,this.id,j)}messages($){return this.timeline({limit:$?.pageSize})}messagesAfter($,O){return this.timeline({activity_after:$ instanceof Date?$.toISOString():$,limit:O?.pageSize})}timeline($){return u(async(O)=>{let j=G(await this.client.storage.messageTimeline({path:{parent_type:"channel",parent_id:this.id},query:{selection:JSON.stringify({...$,cursor:O})}}));return{items:j.items.map((x)=>e.from(this.client,this.id,x)),nextCursor:j.next_cursor}})}message($){return e.byId(this.client,this.id,$)}async rename($){await this.mutate((O)=>O.storage.patchChannel({path:{channel_id:this.id},body:{channel_name:$}}))}async delete(){await this.mutate(($)=>$.storage.deleteChannel({path:{channel_id:this.id}}))}async join(){await this.mutate(($)=>$.storage.joinChannel({path:{channel_id:this.id}}))}async joinCode(){let{join_code:$}=G(await this.client.storage.getChannelJoinLink({path:{channel_id:this.id}}));return $}async leave(){await this.mutate(($)=>$.storage.leaveChannel({path:{channel_id:this.id}}))}async participants(){return G(await this.client.storage.getChannelParticipants({path:{channel_id:this.id}}))}async addParticipants($){await this.mutate((O)=>O.storage.addParticipants({path:{channel_id:this.id},body:{participants:$.map((j)=>j.id)}}))}async removeParticipants($){await this.mutate((O)=>O.storage.removeParticipants({path:{channel_id:this.id},body:{participants:$.map((j)=>j.id)}}))}async typing($,O){G(await this.client.storage.entityMessageTyping({path:{parent_type:"channel",parent_id:this.id},body:{active:$==="start",thread_id:O?.thread?.rootId??null}}))}attachments($){return u(async(O)=>{let j=G(await this.client.storage.getChannelAttachments({path:{channel_id:this.id},query:{...$?.pageSize?{limit:$.pageSize}:{},...$?.type?{attachment_type:$.type}:{},...O?{cursor:O}:{}}}));return{items:j.items,nextCursor:j.next_cursor}})}webUrl(){return`${this.client.webAppUrl}/app/channel/${this.id}`}static search=x$({type:"channel",make:($,O)=>new b($,O.channel_id)})}class M extends X${entityType="user";propertyEntityType="USER";async fetch(){let{names:$}=G(await this.client.auth.getUserNamesWithEmail({body:{user_ids:[this.id]}})),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`user ${this.id} not found`);return O}static byId($,O){return new M($,O)}static fromName($,O){return new M($,O.id,O)}static async me($){let{user_id:O}=G(await $.auth.getUserInfo());return new M($,O)}async name(){let $=await this.detail.get();return[$.first_name,$.last_name].filter(Boolean).join(" ")||void 0}email(){let $=this.id.startsWith("macro|")?this.id.slice(6):void 0;return $?.includes("@")?$:void 0}dm(){return b.dm(this.client,this)}toMention(){return{tag:a$("m-user-mention",{userId:this.id}),mention:{entity_type:"user",entity_id:this.id}}}}class o{client;entityType;entity;constructor($,O,j){this.client=$;this.entityType=O;this.entity=j}get path(){return{entity_type:this.entityType,entity_id:this.entity.id}}async state($){let O=G(await this.client.storage.accessRequestsState({path:this.path,query:{offset:$}}));return{accessLevel:O.accessLevel??void 0,canReview:O.canReview,owner:O.owner?M.byId(this.client,O.owner):void 0,pendingCount:O.pendingCount,supportedLevels:O.supportedLevels,nextOffset:O.nextOffset??void 0,mine:O.mine?TO.from(this.client,this,O.mine):void 0,requests:O.requests.map((j)=>TO.from(this.client,this,j))}}async submit($,O){return TO.from(this.client,this,G(await this.client.storage.accessRequestsSubmit({path:this.path,body:{requestedLevel:$,revision:O}})))}async cancel($){G(await this.client.storage.accessRequestsCancel({path:this.path,query:{revision:$}}))}async direct(){return G(await this.client.storage.accessRequestsDirect({path:this.path})).map(($)=>({user:M.byId(this.client,$.userId),accessLevel:$.accessLevel}))}async grant($,O){G(await this.client.storage.accessRequestsSetDirect({path:{...this.path,user_id:$.id},body:{accessLevel:O}}))}async remove($){G(await this.client.storage.accessRequestsRemoveDirect({path:{...this.path,user_id:$.id}}))}async resolve($,O){let j=$.access.toJSON();if(j.entity_type!==this.entityType||j.entity_id!==this.entity.id)throw Error("Access request belongs to another entity");return G(await this.client.storage.accessRequestsResolve({path:{...this.path,request_id:$.id},body:O}))}toJSON(){return this.path}}class TO extends P{access;resolvedRecord;constructor($,O,j){super($,j.id,j);this.access=O}static from($,O,j){return new TO($,O,j)}async fetch(){if(this.resolvedRecord)return this.resolvedRecord;let $;do{let O=await this.access.state($),j=[O.mine,...O.requests].find((x)=>x?.id===this.id);if(j)return j.detail.get();$=O.nextOffset}while($!==void 0);throw new E(`Access request ${this.id} is unavailable`)}revision=this.field("revision");status=this.field("status");requestedLevel=this.field("requestedLevel");requester=this.mappedField("requesterId",($)=>M.byId(this.client,$));async resolve($){this.resolvedRecord=await this.access.resolve(this,{revision:await this.revision(),grantedLevel:$}),this.detail.clear()}}function i$($){return{...$,channelSharePermissions:$.channelSharePermissions===void 0||$.channelSharePermissions===null?$.channelSharePermissions:$.channelSharePermissions.map((O)=>({channelId:O.channel.id,accessLevel:O.accessLevel,operation:O.operation}))}}class N$ extends P{parent;constructor($,O,j,x){super($,j,x);this.parent=O}static byId($,O,j){return new N$($,O,j)}static fromRecord($,O,j){return new N$($,O,j.id,j)}static async create($,O,j){return N$.createForSession($,O.session(),j,O)}static async createForSession($,O,j,x){let S=G(await $.agentHarness.createSessionReview({path:{session_id:O.id},body:{...j,executionId:x?.id??null}}));return N$.fromRecord($,O,S)}static async list($,O){return G(await $.agentHarness.listExecutionReviews({path:{session_id:O.session().id,execution_id:O.id}})).map((x)=>N$.fromRecord($,O.session(),x))}async fetch(){return G(await this.client.agentHarness.getSessionReview({path:{session_id:this.parent.id,review_id:this.id}}))}title=this.field("title");kind=this.field("kind");session(){return this.parent}async reference(){return{kind:await this.kind(),id:this.id}}async items(){return(await this.detail.get()).items.map(($)=>new hx($,{edit:(O)=>this.decide({action:"edit",item:$.id,draft:O}),submit:()=>this.decide({action:"submit",items:[$.id]}),dismiss:()=>this.decide({action:"dismiss",items:[$.id]})}))}async refresh(){return this.detail.clear(),await this.detail.get(),this}async submitAll(){await this.decide({action:"submit",items:[]})}async dismissAll(){await this.decide({action:"dismiss",items:[]})}async decide($){let O=(await this.detail.get()).revision;await this.mutate((j)=>j.agentHarness.decideSessionReview({path:{session_id:this.parent.id,review_id:this.id},body:{...$,revision:O}}))}}class hx{snapshot;actions;constructor($,O){this.snapshot=$;this.actions=O}get id(){return this.snapshot.id}get status(){return this.snapshot.status}get draft(){return this.snapshot.draft}get result(){return this.snapshot.result}async edit($){await this.actions.edit($)}async submit(){await this.actions.submit()}async dismiss(){await this.actions.dismiss()}}class dO extends P{parent;constructor($,O,j){super($,O);this.parent=j}static byId($,O,j){return new dO($,j,O)}async fetch(){return G(await this.client.agentHarness.getCodeExecution({path:{session_id:this.parent.id,execution_id:this.id}}))}reviews={create:($)=>N$.create(this.client,this,$),list:()=>N$.list(this.client,this)};session(){return this.parent}status=this.field("status");source=this.field("source");calls=this.field("calls");error=this.field("error");async result(){return(await this.detail.get()).result}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class Nj{client;sessionId;dto;constructor($,O,j){this.client=$;this.sessionId=O;this.dto=j}static from($,O,j){return new Nj($,O,j)}get actionId(){return this.dto.actionId}get kind(){return this.dto.kind}get prompt(){return this.dto.prompt??void 0}get attachments(){return this.dto.attachments??[]}get actorUserId(){return this.dto.actorUserId??void 0}get createdAt(){return this.dto.createdAt}async edit($){return G(await this.client.agentHarness.editQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId},body:{prompt:$}})),this.dto={...this.dto,prompt:$},this}async steer(){G(await this.client.agentHarness.steerQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}async remove(){G(await this.client.agentHarness.removeQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}}class lO{client;session;id;constructor($,O,j){this.client=$;this.session=O;this.id=j}static byId($,O,j){return new lO($,O,j)}async answer($){return G(await this.client.agentHarness.answerAgentSessionToolApproval({path:{session_id:this.session.id,approval_id:this.id},body:{answer:$}}))}toJSON(){return{id:this.id,sessionId:this.session.id}}}class i extends P{access=new o(this.client,"agent_session",this);toolApprovalById($){return lO.byId(this.client,this,$)}async sharePermissions(){return G(await this.client.agentHarness.getAgentSessionPermissions({path:{session_id:this.id}}))}async updateSharePermissions($){return this.mutate((O)=>O.agentHarness.updateAgentSessionPermissions({path:{session_id:this.id},body:i$($)}))}static byId($,O){return new i($,O)}static async createManaged($,O){let{session:j}=G(await $.agentHarness.createAgentSession({body:{prompt:O?.prompt,instructions:O?.instructions,model:O?.model,repoUrl:O?.repoUrl,repoBranch:O?.repoBranch}}));return new i($,j.id,j)}static async repositories($){let{repositories:O}=G(await $.agentHarness.listAgentRepositories());return O.map((j)=>({url:j.url,defaultBranch:j.defaultBranch??void 0}))}static async repositoryBranches($,O){let{branches:j}=G(await $.agentHarness.listAgentRepositoryBranches({query:{repoUrl:O}}));return j}async fetch(){return G(await this.client.agentHarness.getAgentSession({path:{session_id:this.id}}))}name=this.field("name");isArchived=this.field("isArchived");model=this.field("model");harness=this.field("harness");repoUrl=this.field("repoUrl");workspace=this.field("workspace");instructions=this.field("instructions");status=this.field("status");sandboxSize=this.field("sandboxSize");createdAt=this.field("createdAt");modifiedAt=this.field("modifiedAt");static async forPullRequest($,O){let{sessionIds:j}=G(await $.agentHarness.agentSessionsForPullRequest({body:{url:O}}));return j.map((x)=>i.byId($,x))}async pullRequests(){let{pullRequests:$}=G(await this.client.agentHarness.listAgentSessionPullRequests({path:{session_id:this.id}}));return $.map((O)=>({githubKey:O.githubKey,url:O.url,source:O.source,linkedBy:O.linkedBy?M.byId(this.client,O.linkedBy):void 0,createdAt:O.createdAt}))}async linkPullRequest($){G(await this.client.agentHarness.linkAgentSessionPullRequest({path:{session_id:this.id},body:{url:$}}))}async unlinkPullRequest($){G(await this.client.agentHarness.unlinkAgentSessionPullRequest({path:{session_id:this.id},query:{url:$}}))}async rename($){await this.mutate((O)=>O.agentHarness.renameAgentSession({path:{session_id:this.id},body:{name:$}}))}async archive(){await this.setArchived(!0)}async unarchive(){await this.setArchived(!1)}async setArchived($){await this.mutate((O)=>O.agentHarness.setAgentSessionArchived({path:{session_id:this.id},body:{isArchived:$}}))}async setSandboxSize($){let{size:O}=await this.mutate((j)=>j.agentHarness.putAgentSessionSandboxSize({path:{session_id:this.id},body:{size:$}}));return O}static async defaultSandboxSize($){return G(await $.agentHarness.getAgentSandboxSize()).size}static async setDefaultSandboxSize($,O){return G(await $.agentHarness.putAgentSandboxSize({body:{size:O}})).size}static async codingPreferences($){return G(await $.agentHarness.getAgentCodingPreferences())}static async setCodingPreferences($,O){return G(await $.agentHarness.putAgentCodingPreferences({body:O}))}async control($){return this.mutate((O)=>O.agentHarness.controlAgentSession({path:{session_id:this.id},body:$}))}prompt($,O){return this.control({type:"prompt",prompt:$,...O&&O.length>0?{attachments:O}:{}})}async queue(){let{entries:$}=G(await this.client.agentHarness.getAgentSessionQueue({path:{session_id:this.id}}));return $.map((O)=>Nj.from(this.client,this.id,O))}async changes(){return G(await this.client.agentHarness.getAgentSessionChanges({path:{session_id:this.id}}))}async changesPatch(){return G(await this.client.agentHarness.getAgentSessionChangesPatch({path:{session_id:this.id}})).patch}async refreshChanges(){return this.mutate(($)=>$.agentHarness.refreshAgentSessionChanges({path:{session_id:this.id}}))}async foldedLog(){let{bot:$,messages:O}=G(await this.client.agentHarness.getAgentSessionFoldedLog({path:{session_id:this.id}}));return{bot:$,messages:O}}async log(){return G(await this.client.agentHarness.getAgentSessionLog({path:{session_id:this.id}}))}reviews={create:($)=>N$.createForSession(this.client,this,$),byId:($)=>N$.byId(this.client,this,$)};codeExecutions={byId:($)=>dO.byId(this.client,this,$)};async delete(){await this.mutate(($)=>$.agentHarness.deleteAgentSession({path:{session_id:this.id}}))}}class mx{client;constructor($){this.client=$}byId($){return i.byId(this.client,$)}createManaged($){return i.createManaged(this.client,$)}repositories(){return i.repositories(this.client)}repositoryBranches($){return i.repositoryBranches(this.client,$)}forPullRequest($){return i.forPullRequest(this.client,$)}defaultSandboxSize(){return i.defaultSandboxSize(this.client)}setDefaultSandboxSize($){return i.setDefaultSandboxSize(this.client,$)}codingPreferences(){return i.codingPreferences(this.client)}setCodingPreferences($){return i.setCodingPreferences(this.client,$)}}class cx{client;constructor($){this.client=$}byId($){return I$.byId(this.client,$)}async list(){return G(await this.client.storage.listAgents()).map(($)=>I$.from(this.client,$))}async create($){return I$.from(this.client,G(await this.client.storage.createAgent({body:yx($)})))}}class ux{client;async usage($={}){let{users:O,...j}=$;return G(await this.client.cognition.getUsageHandler({body:{...j,include_users:O?.map((x)=>x.id)}}))}constructor($){this.client=$}async structuredCompletion($){return G(await this.client.cognition.structuredCompletion({body:$}))}async decide($){return G(await this.client.cognition.decisions({body:$}))}}class n$ extends P{static byId($,O){return new n$($,O)}static from($,O){return new n$($,O.id,{id:O.id,name:O.name,createdAt:O.createdAt})}async fetch(){let $=G(await this.client.storage.listUserApiKeys()).keys.find((O)=>O.id===this.id);if(!$)throw new E(`API key ${this.id} is unavailable`);return $}name=this.field("name");createdAt=this.field("createdAt");async delete(){await this.mutate(($)=>$.storage.deleteUserApiKey({path:{id:this.id}}))}}class dx{client;constructor($){this.client=$}byId($){return n$.byId(this.client,$)}async list(){return G(await this.client.storage.listUserApiKeys()).keys.map(($)=>n$.from(this.client,$))}async create($){let O=G(await this.client.storage.createUserApiKey({body:{name:$}}));return{key:n$.from(this.client,O),secret:O.key}}async tokenForEmail($){return G(await this.client.auth.macroApiToken({query:{email:$}}))}}class rO{client;constructor($){this.client=$}async me(){if(this.client.authConfig.type!=="bot")throw new f("bots.me() requires bot auth — a user API key has no bot identity");return G(await this.client.storage.getSelfBot())}async channels(){if(this.client.authConfig.type!=="bot")throw new f("bots.channels() requires bot auth — a user API key has no bot identity");let $=await this.me();return G(await this.client.storage.listBotChannels({path:{bot_id:$.id}}))}async myPrincipalId(){if(this.client.authConfig.type!=="bot")throw new f("bots.myPrincipalId() requires bot auth — a user API key has no bot identity");return this.client.myPrincipalId()}}class S$ extends P{async fetch(){let O=G(await this.client.auth.getUserTeams()).find((j)=>j.id===this.id);if(!O)throw new E(`team ${this.id} not found`);return O}static byId($,O){return new S$($,O)}static async current($){let O=G(await $.auth.getTeam());if(!O)throw new E("caller has no current team");return new S$($,O.team.id,O.team)}static async list($){return G(await $.auth.getUserTeams()).map((j)=>new S$($,j.id,j))}name=this.field("name");slug=this.field("slug");defaultLinkShare=this.field("default_link_share");owner=this.mappedField("owner_id",($)=>M.byId(this.client,$));async members(){let $=G(await this.client.auth.getTeam());if(!$||$.team.id!==this.id)throw new f("members are only available for the current team (see Team.current)");return $.members.map((O)=>({user:M.byId(this.client,O.user_id),role:O.role}))}}class T$ extends P{async fetch(){let{links:$}=G(await this.client.email.listLinks()),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`email link ${this.id} not found`);return O}static byId($,O){return new T$($,O)}static async list($){let{links:O}=G(await $.email.listLinks());return O.map((j)=>new T$($,j.id,j))}emailAddress=this.field("email_address");provider=this.field("provider");isPrimary=this.field("is_primary");isSyncActive=this.field("is_sync_active");syncStatus=this.field("sync_status");needsReauth=this.field("needs_reauth");photoUrl=this.field("photo_url");async settingsOperations(){return G(await this.client.email.mailboxSettingsOperations({headers:{"X-Email-Link-Id":this.id}}))}}class m$ extends P{async setContributesToAvailability($){await this.mutate((O)=>O.calendar.setAvailabilityCalendar({path:{calendar_id:this.id},body:{contributesToAvailability:$}}))}async fetch(){let{calendars:$}=G(await this.client.calendar.listCalendars()),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`calendar ${this.id} not found`);return O}static byId($,O){return new m$($,O)}static async list($){let{calendars:O}=G(await $.calendar.listCalendars());return O.map((j)=>new m$($,j.id,j))}name=this.field("name");emailAddress=this.field("emailAddress");isPrimary=this.field("isPrimary");isWritable=this.field("isWritable");isSubscription=this.field("isSubscription");color=this.field("color");syncError=this.field("syncError");emailLink=this.mappedField("emailLinkId",($)=>T$.byId(this.client,$))}class pO{client;id;constructor($,O){this.client=$;this.id=O}async status(){return G(await this.client.calendar.calendarReplacementStatus({path:{operation_id:this.id}}))}async confirm(){return G(await this.client.calendar.confirmCalendarReplacement({path:{operation_id:this.id}}))}async discard(){G(await this.client.calendar.discardCalendarReplacement({path:{operation_id:this.id}}))}}class $$ extends P{async notes($){return this.requireOwnOccurrence($),G(await this.client.calendar.eventNotes({path:{event_id:this.id},query:{occurrenceKey:$.occurrenceKey}})).map((j)=>q$.fromRecord(this.client,this,$,j))}async linkNote($,O,j={}){return this.requireOwnOccurrence(O),G(await this.client.calendar.linkEventNote({path:{event_id:this.id,document_id:$.id},query:{occurrenceKey:O.occurrenceKey},body:{teamId:j.team?.id??null}})),q$.forDocument(this.client,this,O,$)}requireOwnOccurrence($){if($.eventId!==this.id)throw new f("The occurrence belongs to a different event")}async fetch(){throw new f(`calendar event ${this.id} has no fetch-by-id endpoint; read the record returned by calendar.createEvent / event.update / event.rsvp instead`)}static byId($,O){return new $$($,O)}static fromRecord($,O){return new $$($,O.id,O)}title=this.field("title");description=this.field("description");location=this.field("location");time=this.field("time");status=this.field("status");attendees=this.field("attendees");transparency=this.field("transparency");isReadOnly=this.field("isReadOnly");recurrenceLines=this.field("recurrenceLines");guestPolicy=this.field("guestPolicy");viewerCan=this.field("viewerCan");calendar=this.mappedField("calendarId",($)=>$?m$.byId(this.client,$):void 0);record(){return this.detail.get()}async update($){let O=await this.mutate((j)=>j.calendar.updateCalendarEvent({path:{event_id:this.id},body:c6($)}));return $$.fromRecord(this.client,O)}async delete($={}){await this.mutate((O)=>O.calendar.deleteCalendarEvent({path:{event_id:this.id},query:{calendarId:$.calendar?.id,scope:$.scope,recurrenceId:$.recurrenceId,inbox:$.inbox}}))}async prepareReplacement($){let O=G(await this.client.calendar.prepareCalendarReplacement({path:{event_id:this.id},body:{removeConference:$.removeConference,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}));return new pO(this.client,O.operationId)}async providerUrl($={}){return G(await this.client.calendar.calendarEventProviderUrl({path:{event_id:this.id},query:{recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}})).url??void 0}async inviteGuests($){let O=await this.mutate((j)=>j.calendar.inviteCalendarEventGuests({path:{event_id:this.id},body:{guests:$.guests,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id,inbox:$.inbox}}));return $$.fromRecord(this.client,O)}async addToCalendar($={}){let O=await this.mutate((j)=>j.calendar.copyCalendarEvent({path:{event_id:this.id},body:{calendarId:$.calendar?.id}}));return $$.fromRecord(this.client,O)}async ics(){return G(await this.client.storage.eventIcs({path:{event_id:this.id}}))}async rsvp($){let O=await this.mutate((j)=>j.calendar.rsvpCalendarEvent({path:{event_id:this.id},body:{response:$.response,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}));return $$.fromRecord(this.client,O)}}function c6($){return{title:$.title,description:$.description,location:$.location,time:$.time,attendees:$.attendees,recurrenceLines:$.recurrenceLines,visibility:$.visibility,transparency:$.transparency,reminders:$.reminders,conference:$.conference,outOfOffice:$.outOfOffice,guestPolicy:$.guestPolicy,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id,inbox:$.inbox}}class q$ extends P{event;occurrence;fromDocument;constructor($,O,j,x,S,K=!1){super($,x.id,S);this.event=O;this.occurrence=j;this.fromDocument=K;if(j.eventId!==O.id)throw new f("Choose an occurrence belonging to this event")}static fromDocumentLink($,O,j){return new q$($,$$.byId($,j.eventId),j,O,{documentId:O.id,name:j.documentName,team:j.team,canManage:!0},!0)}static forDocument($,O,j,x){return new q$($,O,j,x)}static fromRecord($,O,j,x){return new q$($,O,j,w.byId($,x.documentId),x)}async fetch(){if(this.fromDocument){let x=G(await this.client.calendar.documentNoteLinks({path:{document_id:this.id}})).find((S)=>S.eventId===this.event.id&&S.occurrenceKey===this.occurrence.occurrenceKey);if(!x)throw new E("This meeting link has been removed");return{documentId:this.id,name:x.documentName,team:x.team,canManage:!0}}let O=G(await this.client.calendar.eventNotes({path:{event_id:this.event.id},query:{occurrenceKey:this.occurrence.occurrenceKey}})).find((j)=>j.documentId===this.id);if(!O)throw new E("This document is no longer linked to the meeting");return O}document=this.mappedField("documentId",($)=>w.byId(this.client,$));name=this.field("name");team=this.mappedField("team",($)=>$?S$.byId(this.client,$.id):void 0);canManage=this.field("canManage");async setTeam($){await this.mutate((O)=>O.calendar.linkEventNote({path:{event_id:this.event.id,document_id:this.id},query:{occurrenceKey:this.occurrence.occurrenceKey},body:{teamId:$?.id??null}}))}async unlink(){await this.mutate(($)=>$.calendar.unlinkEventNote({path:{event_id:this.event.id,document_id:this.id},query:{occurrenceKey:this.occurrence.occurrenceKey}}))}}class n extends X${async sharePermissions(){return G(await this.client.storage.getProjectPermissionsV2({path:{id:this.id}}))}async accessLevel(){return G(await this.client.storage.getProjectUserAccessLevel({path:{id:this.id}}))}access=new o(this.client,"project",this);entityType="project";propertyEntityType="PROJECT";async fetch(){let{data:$}=G(await this.client.storage.getProjectHandler({path:{id:this.id}}));return $.projectMetadata}static byId($,O){return new n($,O)}static async create($,O){let{data:j}=G(await $.storage.createProjectHandler({body:{name:O.name,projectParentId:O.parent?.id??null}}));return new n($,j.id,j)}name=this.field("name");parent=this.mappedField("parentId",($)=>$?n.byId(this.client,$):void 0);createdAt=this.field("createdAt");async items(){let{data:$}=G(await this.client.storage.getProjectContentHandler({path:{id:this.id}}));return $.map((O)=>O.item)}async rename($){await this.mutate((O)=>O.storage.editProjectV2({path:{id:this.id},body:{name:$}}))}async delete($){await this.mutate((O)=>$?.permanent?O.storage.permanentlyDeleteProject({path:{id:this.id}}):O.storage.deleteProjectHandler({path:{id:this.id}}))}async restore(){await this.mutate(($)=>$.storage.revertDeleteProject({path:{id:this.id}}))}static search=x$({filters:{project_filters:{}},type:"project",make:($,O)=>new n($,O.id)})}class VO extends P{document;toJSON(){return{...super.toJSON(),documentId:this.document.id}}constructor($,O,j,x){super($,j,x);this.document=O}static byId($,O,j){return new VO($,O,j)}static from($,O,j){return new VO($,O,j.uuid,j)}async fetch(){let $=G(await this.client.storage.getDocumentAnchors({path:{document_id:this.document.id}})).data.find((O)=>O.uuid===this.id);if(!$)throw new E(`Annotation ${this.id} is unavailable`);return $}kind=this.field("anchorType");page=this.field("page");async edit($){if(await this.kind()!=="placeable")throw Error("Only placeable comment annotations can be edited");await this.mutate((O)=>O.storage.editAnchor({body:{...$,uuid:this.id,anchorType:"free-comment",fileType:"pdf"}}))}async delete(){if(await this.kind()!=="highlight")throw Error("Only standalone highlights can be deleted with this endpoint");await this.mutate(($)=>$.storage.deleteAnchor({body:{uuid:this.id,anchorType:"highlight",fileType:"pdf"}}))}}class c$ extends P{documentId;constructor($,O,j,x){super($,j,x);this.documentId=O}get path(){return{parent_type:"document",parent_id:this.documentId,id:this.id}}async fetch(){return G(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new c$($,O,j)}static from($,O,j){return new c$($,O,j.id,j)}text=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");async threadId(){return(await this.detail.get()).thread_id??this.id}document(){return w.byId(this.client,this.documentId)}async author(){return M.byId(this.client,(await this.detail.get()).sender_id)}async reply($){return this.document().comment($,{threadId:await this.threadId()})}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}class aO{client;document;id;detail;constructor($,O,j){this.client=$;this.document=O;this.id=j;this.detail=new B$(async()=>G(await this.client.storage.getDocumentVersion({path:{document_id:O.id,document_version_id:j}})).data)}static byId($,O,j){return new aO($,O,j)}read(){return this.detail.get()}toJSON(){return{id:this.id,documentId:this.document.id}}}var u6=8;class w extends X${async meetingNotes(){return G(await this.client.calendar.documentNoteLinks({path:{document_id:this.id}})).map((O)=>({note:q$.fromDocumentLink(this.client,this,O),eventTitle:O.eventTitle}))}async anchors(){return G(await this.client.storage.getDocumentAnchors({path:{document_id:this.id}})).data.map(($)=>VO.from(this.client,this,$))}async createHighlight($){return VO.from(this.client,this,G(await this.client.storage.createAnchor({path:{document_id:this.id},body:{...$,fileType:"pdf",anchorType:"highlight"}})))}version($){return aO.byId(this.client,this,$)}async sharePermissions(){return G(await this.client.storage.getDocumentPermissionsV2({path:{document_id:this.id}})).documentPermissions}async permissionsToken(){return G(await this.client.storage.getDocumentPermissionsToken({path:{document_id:this.id}})).token}async prepareSave($){return G(await this.client.storage.presaveDocumentHandler({path:{document_id:this.id},body:{newBom:$}})).data}async save($){return(await this.mutate((O)=>O.storage.saveDocumentHandler({path:{document_id:this.id},body:$}))).data}async simpleSave(){return(await this.mutate(($)=>$.storage.simpleSave({path:{document_id:this.id}}))).data}messageThreadById($){return L$.byId(this.client,{type:"document",entity:this},$)}timelinePage($){return w$(this.client,{type:"document",entity:this},(O)=>c$.from(this.client,this.id,O),$)}access=new o(this.client,"document",this);async fetch(){let{data:$}=G(await this.client.storage.getDocument({path:{document_id:this.id}}));return $.documentMetadata}static byId($,O){return new w($,O)}static async create($,O){let{documentId:j}=G(await $.storage.createMarkdownHandler({body:{documentName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new w($,j)}static async createSnippet($,O){let{documentId:j}=G(await $.storage.createSnippetHandler({body:{snippetName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new w($,j)}static async createSkill($,O){let{documentId:j}=G(await $.storage.createSkillHandler({body:{skillName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new w($,j)}static recent($,O){let j=O?.pageSize??50;return u(async(x)=>{let S=G(await $.storage.getUserDocumentsHandler({query:{limit:j,offset:x?Number(x):0,...O?.fileType!==void 0?{file_type:O.fileType}:{}}})),K=S.data?.next_offset;return{items:(S.data?.documents??[]).map((Z)=>new w($,Z.documentId)),nextCursor:K!=null?String(K):null}})}static async recentlyDeleted($){let{data:O}=G(await $.storage.recentlyDeleted({}));return O.items.filter((j)=>j.type==="document").map((j)=>new w($,j.id))}entityType="document";propertyEntityType="DOCUMENT";name=this.field("documentName");fileType=this.field("fileType");project=this.mappedField("projectId",($)=>$?n.byId(this.client,$):void 0);owner=this.mappedField("owner",($)=>M.byId(this.client,$));branchedFrom=this.mappedField("branchedFromId",($)=>$?w.byId(this.client,$):void 0);createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");deletedAt=this.field("deletedAt");async content(){let{text:$}=G(await this.client.storage.getDocumentTextContent({path:{document_id:this.id}}));if($!==null)return $;let{presigned_url:O}=G(await this.client.storage.exportDocument({path:{document_id:this.id}})),j=await fetch(O);if(!j.ok)throw new QO(j.status,{message:"failed to download document content"});return j.text()}async rename($){await this.mutate((O)=>O.storage.editDocument({path:{document_id:this.id},body:{documentName:$}}))}async move($){await this.mutate((O)=>O.storage.editDocument({path:{document_id:this.id},body:{projectId:$?.id??""}}))}async delete($){await this.mutate((O)=>$?.permanent?O.storage.permanentlyDeleteDocument({path:{document_id:this.id}}):O.storage.deleteDocument({path:{document_id:this.id}}))}async restore(){await this.mutate(($)=>$.storage.revertDeleteDocument({path:{document_id:this.id}}))}async copy($){let{data:O}=G(await this.client.storage.copyDocument({path:{document_id:this.id},query:$.versionId!==void 0?{version_id:$.versionId}:void 0,body:{documentName:$.name}}));return new w(this.client,O.documentMetadata.documentId)}async comments(){let $={parent_type:"document",parent_id:this.id},O=u(async(x)=>{let S=G(await this.client.storage.messageTimeline({path:$,query:{selection:JSON.stringify({limit:100,cursor:x})}}));return{items:S.items,nextCursor:S.next_cursor}}),j=[];for await(let x of O)j.push(x);return uO(j,u6,async(x)=>{let{state:S,root:K,replies:Z}=G(await this.client.storage.entityMessageGetThread({path:{...$,id:x.id}}));return{thread:S,comments:[K,...Z].map((X)=>c$.from(this.client,this.id,X))}})}async comment($,O){let j=await this.mutate((x)=>x.storage.entityMessageCreate({path:{parent_type:"document",parent_id:this.id},body:{...O$($),thread_id:O?.threadId??null}}));return c$.from(this.client,this.id,j)}async shortId(){return G(await this.client.storage.getDocumentShortId({path:{document_id:this.id}}))}async teamShare(){return G(await this.client.storage.getDocumentTeamShare({path:{document_id:this.id}}))}async setTeamShare($){await this.mutate((O)=>O.storage.setDocumentTeamShare({path:{document_id:this.id},body:{shareWithTeam:$}}))}async githubPullRequests(){let{pullRequests:$}=G(await this.client.storage.getDocumentGithubPullRequests({path:{document_id:this.id}}));return $}async branchName(){let{branchName:$}=G(await this.client.storage.getDocumentBranchName({path:{document_id:this.id}}));return $}webUrl(){return`${this.client.webAppUrl}/app/md/${this.id}`}static search=x$({filters:{document_filters:{}},type:"document",make:($,O)=>new w($,O.document_id)});toMention(){let $=this.detail.peek();return{tag:a$("m-document-mention",{documentId:this.id,documentName:$?.documentName??"",blockName:$?.fileType??"md"}),mention:{entity_type:"document",entity_id:this.id}}}}class lx{client;async noteDocuments($=""){let O=G(await this.client.calendar.noteDocuments({query:{query:$}}));return{documents:O.documents.map((j)=>({document:w.byId(this.client,j.documentId),name:j.name})),teams:O.teams.map((j)=>({team:S$.byId(this.client,j.id),name:j.name}))}}async availabilityCalendars(){return G(await this.client.calendar.getAvailabilityCalendars()).calendars.map(($)=>({calendar:m$.byId(this.client,$.calendarId),name:$.name,isPrimary:$.isPrimary,contributesToAvailability:$.contributesToAvailability}))}async teamSharing(){return G(await this.client.calendar.getTeamSharing()).sharing}async setTeamSharing($){return G(await this.client.calendar.setTeamSharing({body:{sharing:$}})).sharing}occurrences($){let O;return u(async(j)=>{let x=G(await this.client.storage.listOccurrences({query:{...$,cursor:j}}));O??=l6(this.client);let S=await O;return{items:x.items.map((K)=>({event:$$.fromRecord(this.client,K.event),occurrence:K.occurrence,inbox:K.event.calendarId?S.get(K.event.calendarId):void 0,role:r6(K.event)})),nextCursor:x.nextCursor}})}async teamPage($){let O=G(await this.client.storage.listTeamCalendar({query:$}));return{items:O.items.map(({ownerId:j,...x})=>({...x,owner:M.byId(this.client,j)})),members:O.members.map((j)=>({user:M.byId(this.client,j.userId),sharing:j.sharing,coverage:j.coverage})),nextCursor:O.nextCursor??void 0}}async teamOutOfOffice($){let O=G(await this.client.storage.listTeamOutOfOffice({query:$}));return{items:O.items.map((j)=>({event:$$.byId(this.client,j.eventId),owner:M.byId(this.client,j.ownerId),occurrenceKey:j.occurrenceKey,time:j.time,title:j.title??void 0})),hasMore:O.hasMore}}constructor($){this.client=$}calendars(){return m$.list(this.client)}calendar($){return m$.byId(this.client,$)}event($){return $$.byId(this.client,$)}replacement($){return new pO(this.client,$)}async createEvent($){let O=G(await this.client.calendar.createCalendarEvent({body:d6($)}));return $$.fromRecord(this.client,O)}}function d6($){return{title:$.title,time:$.time,description:$.description,location:$.location,attendees:$.attendees,recurrenceLines:$.recurrenceLines,visibility:$.visibility,transparency:$.transparency,reminders:$.reminders,conference:$.conference,macroCall:$.macroCall,outOfOffice:$.outOfOffice,guestPolicy:$.guestPolicy,calendarId:$.calendar?.id,emailLinkId:$.emailLink?.id}}async function l6($){let{calendars:O}=G(await $.calendar.listCalendars());return new Map(O.map((j)=>[j.id,j.emailAddress]))}function r6($){let O=$.attendees.find((j)=>j.isSelf);if($.viewerCan.organize||O?.isOrganizer)return"organizer";return O?"guest":void 0}class H$ extends P{lookupToken;constructor($,O,j){super($,O,j);this.lookupToken=j?.shareToken}static byId($,O){return new H$($,O)}static from($,O){return new H$($,O.id,O)}async fetch(){if(this.lookupToken)return G(await this.client.storage.meetingLookup({path:{token:this.lookupToken}}));let $=G(await this.client.storage.meetingList()).meetings.find((O)=>O.id===this.id);if(!$)throw new E(`Meeting ${this.id} is unavailable`);return this.lookupToken=$.shareToken,$}title=this.field("title");scheduledStart=this.field("scheduledStart");scheduledEnd=this.field("scheduledEnd");channel=this.mappedField("channelId",($)=>$?b.byId(this.client,$):void 0);call=this.mappedField("callId",($)=>$?Q$.byId(this.client,$):void 0);async update($){await this.mutate((O)=>O.storage.meetingUpdate({path:{meeting_id:this.id},body:$}))}async cancel(){await this.mutate(($)=>$.storage.meetingCancel({path:{meeting_id:this.id}}))}async invitePermissions(){return G(await this.client.storage.meetingInvitePermissions({path:{token:(await this.detail.get()).shareToken}}))}async invite($){G(await this.client.storage.meetingInvite({path:{token:(await this.detail.get()).shareToken},body:{email:$}}))}async inviteUsers($){G(await this.client.storage.meetingInviteUsers({path:{token:(await this.detail.get()).shareToken},body:{userIds:$.map((O)=>O.id)}}))}async webUrl(){return`${this.client.webAppUrl}/app/meet/join/${encodeURIComponent((await this.detail.get()).shareToken)}`}}class u$ extends P{callId;constructor($,O,j,x){super($,j,x);this.callId=O}get path(){return{parent_type:"call",parent_id:this.callId,id:this.id}}async fetch(){return G(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new u$($,O,j)}static from($,O,j){return new u$($,O,j.id,j)}content=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");call(){return Q$.byId(this.client,this.callId)}async author(){return M.byId(this.client,(await this.detail.get()).sender_id)}async reply($){let O=G(await this.client.storage.entityMessageCreate({path:{parent_type:"call",parent_id:this.callId},body:{...O$($),thread_id:this.callId}}));return u$.from(this.client,this.callId,O)}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}class Q$ extends z${messageThreadById($){return L$.byId(this.client,{type:"call",entity:this},$)}timelinePage($){return w$(this.client,{type:"call",entity:this},(O)=>u$.from(this.client,this.id,O),$)}access=new o(this.client,"call",this);async meeting(){return H$.from(this.client,G(await this.client.storage.meetingShare({path:{call_id:this.id}})))}async editTranscript($){await this.mutate((O)=>O.storage.editCallTranscript({path:{call_id:this.id},body:{assignments:$}}))}async toggleTeamShare(){return this.mutate(($)=>$.storage.toggleShareWithTeam({path:{call_id:this.id}}))}entityType="call";async fetch(){return G(await this.client.storage.getCallRecord({path:{call_id:this.id}}))}static byId($,O){return new Q$($,O)}message($){return u$.byId(this.client,this.id,$)}name=this.field("customName");channel=this.mappedField("channelId",($)=>$?b.byId(this.client,$):void 0);channelName=this.field("channelName");creator=this.mappedField("createdBy",($)=>M.byId(this.client,$));isActive=this.field("isActive");status=this.field("status");roomName=this.field("roomName");startedAt=this.field("startedAt");endedAt=this.field("endedAt");durationMs=this.field("durationMs");summary=this.field("summary");transcript=this.field("transcript");participants=this.field("participants");guests=this.field("guests");teamShareAccessLevel=this.field("teamShareAccessLevel");shareWithTeam=this.field("shareWithTeam");recordingUrl=this.field("recordingUrl");recordingPreviewUrl=this.field("recordingPreviewUrl");recordingStartedAt=this.field("recordingStartedAt");async rename($){await this.mutate((O)=>O.storage.editCallRecord({path:{call_id:this.id},body:{customName:$??""}}))}async setTeamShare($){await this.mutate((O)=>O.storage.editCallRecord({path:{call_id:this.id},body:{sharePermission:{teamShareAccessLevel:$?"view":null}}}))}async delete(){await this.mutate(($)=>$.storage.deleteCallRecord({path:{call_id:this.id}}))}static search=x$({filters:{call_filters:{}},type:"call",make:($,O)=>new Q$($,O.call_id)})}class rx{client;constructor($){this.client=$}byId($){return Q$.byId(this.client,$)}search($,O){return Q$.search(this.client,$,O)}}class px{client;constructor($){this.client=$}async list(){let{labels:$}=G(await this.client.storage.listChannelLabels());return $}async create($,O=[]){return G(await this.client.storage.createChannelLabel({body:{name:$,channelIds:O.map((j)=>j.id)}}))}async createSmartTag($,O){return G(await this.client.storage.createChannelLabel({body:{name:$,rule:O}}))}async previewSmartTag($){return G(await this.client.storage.previewSmartTag({body:$}))}async updateSmartTag($,O,j){return G(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O,rule:j}}))}async rename($,O){return G(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O}}))}async delete($){G(await this.client.storage.deleteChannelLabel({path:{label_id:$.id}}))}async setLabel($,O){G(await this.client.storage.setChannelLabel({path:{channel_id:$.id},body:{labelId:O?.id??null}}))}}class ax{client;async activity(){return G(await this.client.storage.getActivity()).map(($)=>new JO(this.client,b.byId(this.client,$.channel_id),$))}labels;constructor($){this.client=$;this.labels=new px($)}byId($){return b.byId(this.client,$)}async dm($){return b.dm(this.client,$)}async private($){return b.private(this.client,$)}async create($){return b.create(this.client,$)}async list(){let{items:$}=G(await this.client.storage.getChannels());return $.map((O)=>b.byId(this.client,O.id.toString()))}async*search($,O){if(!O?.searchOn||O.searchOn==="name"){let{items:j}=G(await this.client.storage.getChannels()),x=$.toLowerCase();for(let S of j)if(S.name?.toLowerCase().includes(x))yield b.byId(this.client,S.id.toString())}else yield*b.search(this.client,$,O)}}class iO{client;chat;id;message;constructor($,O,j,x){this.client=$;this.chat=O;this.id=j;this.message=x}static byId($,O,j,x){return new iO($,O,j,x)}async stop(){G(await this.client.cognition.stopChatStream({body:{chat_id:this.chat.id,stream_id:this.id}}))}toJSON(){return{id:this.id,chatId:this.chat.id,messageId:this.message.id}}}class nO extends P{chat;constructor($,O,j){super($,j);this.chat=O}static byId($,O,j){return new nO($,O,j)}async fetch(){let $=G(await this.client.cognition.getChat({path:{chat_id:this.chat.id}})).chat.messages.find((O)=>O.id===this.id);if(!$)throw new E(`Chat message ${this.id} is not yet available`);return $}content=this.field("content");role=this.field("role");async refresh(){this.detail.clear(),await this.detail.get()}toJSON(){return{...super.toJSON(),chatId:this.chat.id}}}class K$ extends X${async send($){let{attachments:O,additionalInstructions:j,...x}=$,S=await this.mutate((Z)=>Z.cognition.sendChatMessage({body:{...x,chat_id:this.id,additional_instructions:j,attachments:O?.map((X)=>({entity_id:X.entity.id,entity_type:X.type}))}})),K=K$.byId(this.client,S.chat_id);return iO.byId(this.client,K,S.stream_id,nO.byId(this.client,K,S.message_id))}access=new o(this.client,"chat",this);entityType="chat";propertyEntityType="CHAT";async fetch(){let{chat:$}=G(await this.client.cognition.getChat({path:{chat_id:this.id}}));return $}static byId($,O){return new K$($,O)}static async create($,O){let{id:j}=G(await $.cognition.createChat({body:{name:O?.name??null,projectId:O?.project?.id??null}}));return new K$($,j)}name=this.field("name");model=this.field("model");project=this.mappedField("projectId",($)=>$?n.byId(this.client,$):void 0);createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");messages=this.field("messages");async rename($){await this.mutate((O)=>O.cognition.patchChat({path:{chat_id:this.id},body:{name:$}}))}async delete($){await this.mutate((O)=>$?.permanent?O.cognition.permanentlyDeleteChat({path:{chat_id:this.id}}):O.cognition.deleteChat({path:{chat_id:this.id}}))}async copy(){let{id:$}=await this.mutate((O)=>O.cognition.copyChat({path:{chat_id:this.id}}));return new K$(this.client,$)}async restore(){await this.mutate(($)=>$.cognition.revertDeleteChat({path:{chat_id:this.id}}))}async history(){let{conversation:$}=G(await this.client.cognition.getChatHistoryHandler({path:{chat_id:this.id}}));return $}webUrl(){return`${this.client.webAppUrl}/app/chat/${this.id}`}static search=x$({filters:{chat_filters:{}},type:"chat",make:($,O)=>new K$($,O.chat_id)});toMention(){return{tag:a$("m-document-mention",{documentId:this.id,documentName:this.detail.peek()?.name??"",blockName:"chat",blockParams:{}}),mention:{entity_type:"chat",entity_id:this.id}}}}class ix{client;constructor($){this.client=$}byId($){return K$.byId(this.client,$)}create($){return K$.create(this.client,$)}search($,O){return K$.search(this.client,$,O)}}var p6=8;class P$ extends P{parent;constructor($,O,j,x){super($,j,x);this.parent=O}get path(){return{parent_type:this.parent.type,parent_id:this.parent.id,id:this.id}}async fetch(){return G(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new P$($,O,j)}static from($,O,j){return new P$($,O,j.id,j)}text=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");deletedAt=this.field("deleted_at");async threadId(){return(await this.detail.get()).thread_id??this.id}async author(){return M.byId(this.client,(await this.detail.get()).sender_id)}async reply($){return sO(this.client,this.parent,$,{threadId:await this.threadId()})}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}async function Uj($,O){let j={parent_type:O.type,parent_id:O.id},x=u(async(K)=>{let Z=G(await $.storage.messageTimeline({path:j,query:{selection:JSON.stringify({limit:100,cursor:K})}}));return{items:Z.items,nextCursor:Z.next_cursor}}),S=[];for await(let K of x)S.push(K);return uO(S,p6,async(K)=>{let{state:Z,root:X,replies:Y}=G(await $.storage.entityMessageGetThread({path:{...j,id:K.id}}));return{thread:Z,comments:[X,...Y].map((L)=>P$.from($,O,L))}})}async function sO($,O,j,x){let S=G(await $.storage.entityMessageCreate({path:{parent_type:O.type,parent_id:O.id},body:{...O$(j),thread_id:x?.threadId??null}}));return P$.from($,O,S)}class f$ extends z${messageThreadById($){return L$.byId(this.client,{type:"crm_contact",entity:this},$)}timelinePage($){return w$(this.client,{type:"crm_contact",entity:this},(O)=>P$.from(this.client,{type:"crm_contact",id:this.id},O),$)}entityType="crm_contact";async fetch(){return G(await this.client.storage.getContact({path:{contact_id:this.id}}))}static byId($,O){return new f$($,O)}static from($,O){return new f$($,O.id,O)}name=this.field("name");email=this.field("email");company=this.mappedField("companyId",($)=>b$.byId(this.client,$));hidden=this.field("hidden");createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");firstInteraction=this.field("firstInteraction");lastInteraction=this.field("lastInteraction");async hide(){await this.setHidden(!0)}async unhide(){await this.setHidden(!1)}async setHidden($){await this.mutate((O)=>O.storage.setContactHidden({path:{contact_id:this.id},body:{hidden:$}}))}async rename($){await this.mutate((O)=>O.storage.setCrmContactName({path:{contact_id:this.id},body:{name:$}}))}get commentParent(){return{type:"crm_contact",id:this.id}}async comments(){return Uj(this.client,this.commentParent)}async comment($,O){return sO(this.client,this.commentParent,$,O)}commentById($){return P$.byId(this.client,this.commentParent,$)}}class b$ extends X${messageThreadById($){return L$.byId(this.client,{type:"crm_company",entity:this},$)}timelinePage($){return w$(this.client,{type:"crm_company",entity:this},(O)=>P$.from(this.client,{type:"crm_company",id:this.id},O),$)}entityType="crm_company";propertyEntityType="COMPANY";async fetch(){return G(await this.client.storage.getCompany({path:{company_id:this.id}}))}static byId($,O){return new b$($,O)}static from($,O){return new b$($,O.id,O)}name=this.field("name");description=this.field("description");hidden=this.field("hidden");emailSync=this.field("emailSync");team=this.mappedField("teamId",($)=>S$.byId(this.client,$));createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");async domain(){let{domains:$}=await this.detail.get();return $[0]?.domain}async domains(){let{domains:$}=await this.detail.get();return $.map((O)=>O.domain)}async contacts(){return G(await this.client.storage.listCompanyContacts({path:{company_id:this.id}})).map((O)=>f$.from(this.client,O))}static search=x$({filters:{crm_company_filters:{}},type:"company",includeCrm:!0,make:($,O)=>new b$($,O.id)});async hide(){await this.setHidden(!0)}async unhide(){await this.setHidden(!1)}async setHidden($){await this.mutate((O)=>O.storage.setCompanyHidden({path:{company_id:this.id},body:{hidden:$}}))}async setEmailSync($){await this.mutate((O)=>O.storage.setEmailSync({path:{company_id:this.id},body:{email_sync:$}}))}async rename($){await this.mutate((O)=>O.storage.setCrmCompanyName({path:{company_id:this.id},body:{name:$}}))}async createContact($){let O=await this.mutate((j)=>j.storage.createCrmContact({path:{company_id:this.id},body:$}));return f$.from(this.client,O)}get commentParent(){return{type:"crm_company",id:this.id}}async comments(){return Uj(this.client,this.commentParent)}async comment($,O){return sO(this.client,this.commentParent,$,O)}commentById($){return P$.byId(this.client,this.commentParent,$)}}class s$ extends P{tableDetail=new B$(async()=>G(await this.client.storage.getCrmPipelineTable({path:{id:this.id}})));static byId($,O){return new s$($,O)}static from($,O){return new s$($,O.id,O)}async fetch(){return G(await this.client.storage.getCrmPipeline({path:{id:this.id}}))}name=this.field("name");recordType=this.field("recordType");accessLevel=this.field("grant");sharing=this.field("sharing");owner=this.mappedField("userId",($)=>M.byId(this.client,$));team=this.mappedField("teamId",($)=>S$.byId(this.client,$));async rename($){await this.mutate((O)=>O.storage.renameCrmPipeline({path:{id:this.id},body:{name:$}}))}async setSharing($){if($===void 0)throw Error("Sharing is required");await this.mutate((O)=>O.storage.shareCrmPipeline({path:{id:this.id},body:{sharing:$}}))}async setTrashed($){await this.mutate((O)=>O.storage.trashCrmPipeline({path:{id:this.id},body:{trashed:$}}))}async sharePermissions(){return G(await this.client.storage.getCrmPipelinePermissions({path:{id:this.id}}))}async updateSharePermissions($){return this.mutate((O)=>O.storage.updateCrmPipelinePermissions({path:{id:this.id},body:i$($)}))}async table(){return zj.from(this.client,this,await this.tableRecord())}tableRecord(){return this.tableDetail.get()}rows(){return u(async($)=>{let O=G(await this.client.storage.getCrmPipelineRows({path:{id:this.id},query:{after:$}}));return{items:O.rows.map((j)=>BO.from(this.client,this,j)),nextCursor:O.next}})}queryRows($={}){if($.rows?.some((O)=>O.pipeline.id!==this.id))throw Error("Rows belong to another pipeline");return u(async(O)=>{let j=G(await this.client.storage.queryCrmPipelineRows({path:{id:this.id},body:{after:O,query:$.query,rowIds:$.rows?.map((x)=>x.id)}}));return{items:j.rows.map((x)=>BO.from(this.client,this,x)),nextCursor:j.next}})}async applyOps($,O){if(O?.baseVersions?.some((S)=>S.table.pipeline.id!==this.id))throw Error("Table belongs to another pipeline");let j={ops:$,baseVersions:O?.baseVersions?Object.fromEntries(O.baseVersions.map((S)=>[S.table.id,S.version])):void 0},x=await this.mutate((S)=>S.storage.applyCrmPipelineOps({path:{id:this.id},body:j}));return this.tableDetail.clear(),x}}class zj extends P{pipeline;toJSON(){return{...super.toJSON(),pipelineId:this.pipeline.id}}constructor($,O,j){super($,j.table.id,j);this.pipeline=O}static from($,O,j){return new zj($,O,j)}fetch(){return this.pipeline.tableRecord()}async columns(){return(await this.pipeline.tableRecord()).columns.map(($)=>Ij.from(this.client,this,$))}async version(){return(await this.pipeline.tableRecord()).table.version}rowById($){return BO.byId(this.client,this.pipeline,$)}rows(){return this.pipeline.rows()}}class BO extends P{pipeline;toJSON(){return{...super.toJSON(),pipelineId:this.pipeline.id}}constructor($,O,j,x){super($,j,x);this.pipeline=O}static byId($,O,j){return new BO($,O,j)}static from($,O,j){return new BO($,O,j.rowId,j)}async fetch(){for await(let $ of this.pipeline.queryRows({rows:[this]}))if($.id===this.id)return $.detail.get();throw new E(`Pipeline row ${this.id} is unavailable`)}cells=this.field("cells");async refresh(){this.detail.clear(),await this.detail.get()}}class Ij extends P{table;toJSON(){return{...super.toJSON(),pipelineId:this.table.pipeline.id,tableId:this.table.id}}constructor($,O,j){super($,j.column.id,j);this.table=O}static from($,O,j){return new Ij($,O,j)}async fetch(){let $=(await this.table.pipeline.tableRecord()).columns.find((O)=>O.column.id===this.id);if(!$)throw new E(`Pipeline column ${this.id} is unavailable`);return $}async writable(){return(await this.fetch()).writable}async name(){return(await this.fetch()).column.display_name??(await this.fetch()).definition.definition.display_name}}class nx{client;constructor($){this.client=$}byId($){return s$.byId(this.client,$)}async list(){return G(await this.client.storage.listCrmPipelines()).map(($)=>s$.from(this.client,$))}async create($){return s$.from(this.client,G(await this.client.storage.createCrmPipeline({body:$})))}}class sx{client;pipelines;constructor($){this.client=$;this.pipelines=new nx($)}companyById($){return b$.byId(this.client,$)}contactById($){return f$.byId(this.client,$)}async contactByEmail($){let{contact:O}=G(await this.client.storage.getContactByEmail({query:{email:$}}));return O?f$.from(this.client,O):void 0}async searchContacts($,O={}){let{contacts:j}=G(await this.client.storage.searchContacts({query:{query:$,limit:O.limit}}));return j.map((x)=>f$.from(this.client,x))}async createCompany($){return b$.from(this.client,G(await this.client.storage.createCrmCompany({body:$})))}async settings(){return G(await this.client.storage.getCrmTeamSettings())}async updateSettings($){return G(await this.client.storage.putCrmTeamSettings({body:$}))}async setStages($){return G(await this.client.storage.putCrmTeamStages({body:$}))}async resetStages(){G(await this.client.storage.resetCrmTeamStages())}searchCompanies($){return b$.search(this.client,$)}}var G$=Symbol.for("@ts-pattern/matcher"),m1=Symbol.for("@ts-pattern/isVariadic");var tx=($)=>Boolean($&&typeof $=="object"),Tj=($)=>$&&!!$[G$],s=($,O,j)=>{if(Tj($)){let x=$[G$](),{matched:S,selections:K}=x.match(O);return S&&K&&Object.keys(K).forEach((Z)=>j(Z,K[Z])),S}if(tx($)){if(!tx(O))return!1;if(Array.isArray($)){if(!Array.isArray(O))return!1;let x=[],S=[],K=[];for(let Z of $.keys()){let X=$[Z];Tj(X)&&X[m1]?K.push(X):K.length?S.push(X):x.push(X)}if(K.length){if(K.length>1)throw Error("Pattern error: Using `...P.array(...)` several times in a single pattern is not allowed.");if(O.length<x.length+S.length)return!1;let Z=O.slice(0,x.length),X=S.length===0?[]:O.slice(-S.length),Y=O.slice(x.length,S.length===0?1/0:-S.length);return x.every((L,Q)=>s(L,Z[Q],j))&&S.every((L,Q)=>s(L,X[Q],j))&&(K.length===0||s(K[0],Y,j))}return $.length===O.length&&$.every((Z,X)=>s(Z,O[X],j))}return Reflect.ownKeys($).every((x)=>{let S=$[x];return((x in O)||Tj(K=S)&&K[G$]().matcherType==="optional")&&s(S,O[x],j);var K})}return Object.is(O,$)},Y$=($)=>{var O,j,x;return tx($)?Tj($)?(O=(j=(x=$[G$]()).getSelectionKeys)==null?void 0:j.call(x))!=null?O:[]:Array.isArray($)?tO($,Y$):tO(Object.values($),Y$):[]},tO=($,O)=>$.reduce((j,x)=>j.concat(O(x)),[]);function a6(...$){if($.length===1){let[O]=$;return(j)=>s(O,j,()=>{})}if($.length===2){let[O,j]=$;return s(O,j,()=>{})}throw Error(`isMatching wasn't given the right number of arguments: expected 1 or 2, received ${$.length}.`)}function t($){return Object.assign($,{optional:()=>$0($),and:(O)=>d($,O),or:(O)=>c1($,O),select:(O)=>O===void 0?eO($):eO(O,$)})}function ex($){return Object.assign(((O)=>Object.assign(O,{[Symbol.iterator](){let j=0,x=[{value:Object.assign(O,{[m1]:!0}),done:!1},{done:!0,value:void 0}];return{next:()=>{var S;return(S=x[j++])!=null?S:x.at(-1)}}}}))($),{optional:()=>ex($0($)),select:(O)=>ex(O===void 0?eO($):eO(O,$))})}function $0($){return t({[G$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return O===void 0?(Y$($).forEach((S)=>x(S,void 0)),{matched:!0,selections:j}):{matched:s($,O,x),selections:j}},getSelectionKeys:()=>Y$($),matcherType:"optional"})})}var i6=($,O)=>{for(let j of $)if(!O(j))return!1;return!0},n6=($,O)=>{for(let[j,x]of $.entries())if(!O(x,j))return!1;return!0},s6=($,O)=>{let j=Reflect.ownKeys($);for(let x of j)if(!O(x,$[x]))return!1;return!0};function d(...$){return t({[G$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return{matched:$.every((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>tO($,Y$),matcherType:"and"})})}function c1(...$){return t({[G$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return tO($,Y$).forEach((S)=>x(S,void 0)),{matched:$.some((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>tO($,Y$),matcherType:"or"})})}function m($){return{[G$]:()=>({match:(O)=>({matched:Boolean($(O))})})}}function eO(...$){let O=typeof $[0]=="string"?$[0]:void 0,j=$.length===2?$[1]:typeof $[0]=="string"?void 0:$[0];return t({[G$]:()=>({match:(x)=>{let S={[O!=null?O:"@ts-pattern/anonymous-select-key"]:x};return{matched:j===void 0||s(j,x,(K,Z)=>{S[K]=Z}),selections:S}},getSelectionKeys:()=>[O!=null?O:"@ts-pattern/anonymous-select-key"].concat(j===void 0?[]:Y$(j))})})}function u1($){return!0}function k$($){return typeof $=="number"}function t$($){return typeof $=="string"}function e$($){return typeof $=="bigint"}var d1=t(m(u1)),t6=t(m(u1)),e6=d1,o$=($)=>Object.assign(t($),{startsWith:(O)=>{return o$(d($,(j=O,m((x)=>t$(x)&&x.startsWith(j)))));var j},endsWith:(O)=>{return o$(d($,(j=O,m((x)=>t$(x)&&x.endsWith(j)))));var j},minLength:(O)=>o$(d($,((j)=>m((x)=>t$(x)&&x.length>=j))(O))),length:(O)=>o$(d($,((j)=>m((x)=>t$(x)&&x.length===j))(O))),maxLength:(O)=>o$(d($,((j)=>m((x)=>t$(x)&&x.length<=j))(O))),includes:(O)=>{return o$(d($,(j=O,m((x)=>t$(x)&&x.includes(j)))));var j},regex:(O)=>{return o$(d($,(j=O,m((x)=>t$(x)&&Boolean(x.match(j))))));var j}}),h1=o$(m(t$)),g$=($)=>Object.assign(t($),{between:(O,j)=>g$(d($,((x,S)=>m((K)=>k$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>g$(d($,((j)=>m((x)=>k$(x)&&x<j))(O))),gt:(O)=>g$(d($,((j)=>m((x)=>k$(x)&&x>j))(O))),lte:(O)=>g$(d($,((j)=>m((x)=>k$(x)&&x<=j))(O))),gte:(O)=>g$(d($,((j)=>m((x)=>k$(x)&&x>=j))(O))),int:()=>g$(d($,m((O)=>k$(O)&&Number.isInteger(O)))),finite:()=>g$(d($,m((O)=>k$(O)&&Number.isFinite(O)))),positive:()=>g$(d($,m((O)=>k$(O)&&O>0))),negative:()=>g$(d($,m((O)=>k$(O)&&O<0)))}),o6=g$(m(k$)),$O=($)=>Object.assign(t($),{between:(O,j)=>$O(d($,((x,S)=>m((K)=>e$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>$O(d($,((j)=>m((x)=>e$(x)&&x<j))(O))),gt:(O)=>$O(d($,((j)=>m((x)=>e$(x)&&x>j))(O))),lte:(O)=>$O(d($,((j)=>m((x)=>e$(x)&&x<=j))(O))),gte:(O)=>$O(d($,((j)=>m((x)=>e$(x)&&x>=j))(O))),positive:()=>$O(d($,m((O)=>e$(O)&&O>0))),negative:()=>$O(d($,m((O)=>e$(O)&&O<0)))}),$7=$O(m(e$)),O7=t(m(function($){return typeof $=="boolean"})),j7=t(m(function($){return typeof $=="symbol"})),x7=t(m(function($){return $==null})),S7=t(m(function($){return $!=null})),Z$={__proto__:null,matcher:G$,optional:$0,array:function(...$){return ex({[G$]:()=>({match:(O)=>{if(!Array.isArray(O))return{matched:!1};if($.length===0)return{matched:!0};let j=$[0],x={};if(O.length===0)return Y$(j).forEach((K)=>{x[K]=[]}),{matched:!0,selections:x};let S=(K,Z)=>{x[K]=(x[K]||[]).concat([Z])};return{matched:O.every((K)=>s(j,K,S)),selections:x}},getSelectionKeys:()=>$.length===0?[]:Y$($[0])})})},set:function(...$){return t({[G$]:()=>({match:(O)=>{if(!(O instanceof Set))return{matched:!1};let j={};if(O.size===0)return{matched:!0,selections:j};if($.length===0)return{matched:!0};let x=(K,Z)=>{j[K]=(j[K]||[]).concat([Z])},S=$[0];return{matched:i6(O,(K)=>s(S,K,x)),selections:j}},getSelectionKeys:()=>$.length===0?[]:Y$($[0])})})},map:function(...$){return t({[G$]:()=>({match:(O)=>{if(!(O instanceof Map))return{matched:!1};let j={};if(O.size===0)return{matched:!0,selections:j};let x=(X,Y)=>{j[X]=(j[X]||[]).concat([Y])};if($.length===0)return{matched:!0};var S;if($.length===1)throw Error(`\`P.map\` wasn't given enough arguments. Expected (key, value), received ${(S=$[0])==null?void 0:S.toString()}`);let[K,Z]=$;return{matched:n6(O,(X,Y)=>{let L=s(K,Y,x),Q=s(Z,X,x);return L&&Q}),selections:j}},getSelectionKeys:()=>$.length===0?[]:[...Y$($[0]),...Y$($[1])]})})},record:function(...$){return t({[G$]:()=>({match:(O)=>{if(O===null||typeof O!="object"||Array.isArray(O))return{matched:!1};var j;if($.length===0)throw Error(`\`P.record\` wasn't given enough arguments. Expected (value) or (key, value), received ${(j=$[0])==null?void 0:j.toString()}`);let x={},S=(X,Y)=>{x[X]=(x[X]||[]).concat([Y])},[K,Z]=$.length===1?[h1,$[0]]:$;return{matched:s6(O,(X,Y)=>{let L=typeof X!="string"||Number.isNaN(Number(X))?null:Number(X),Q=L!==null&&s(K,L,S),J=s(K,X,S),I=s(Z,Y,S);return(J||Q)&&I}),selections:x}},getSelectionKeys:()=>$.length===0?[]:[...Y$($[0]),...Y$($[1])]})})},intersection:d,union:c1,not:function($){return t({[G$]:()=>({match:(O)=>({matched:!s($,O,()=>{})}),getSelectionKeys:()=>[],matcherType:"not"})})},when:m,select:eO,any:d1,unknown:t6,_:e6,string:h1,number:o6,bigint:$7,boolean:O7,symbol:j7,nullish:x7,nonNullable:S7,instanceOf:function($){return t(m(function(O){return(j)=>j instanceof O}($)))},shape:function($){return t(m(a6($)))}};class l1 extends Error{constructor($){let O;try{O=JSON.stringify($)}catch(j){O=$}super(`Pattern matching error: no pattern matches value ${O}`),this.input=void 0,this.input=$}}var ox={matched:!1,value:void 0};function c($){return new Hj($,ox)}class Hj{constructor($,O){this.input=void 0,this.state=void 0,this.input=$,this.state=O}with(...$){if(this.state.matched)return this;let O=$[$.length-1],j=[$[0]],x;$.length===3&&typeof $[1]=="function"?x=$[1]:$.length>2&&j.push(...$.slice(1,$.length-1));let S=!1,K={},Z=(Y,L)=>{S=!0,K[Y]=L},X=!j.some((Y)=>s(Y,this.input,Z))||x&&!Boolean(x(this.input))?ox:{matched:!0,value:O(S?"@ts-pattern/anonymous-select-key"in K?K["@ts-pattern/anonymous-select-key"]:K:this.input,this.input)};return new Hj(this.input,X)}when($,O){if(this.state.matched)return this;let j=Boolean($(this.input));return new Hj(this.input,j?{matched:!0,value:O(this.input,this.input)}:ox)}otherwise($){return this.state.matched?this.state.value:$(this.input)}exhaustive($=Z7){return this.state.matched?this.state.value:$(this.input)}run(){return this.exhaustive()}returnType(){return this}narrow(){return this}}function Z7($){throw new l1($)}var O0,X7=new Uint8Array(16);function Rj(){if(!O0){if(typeof crypto>"u"||!crypto.getRandomValues)throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");O0=crypto.getRandomValues.bind(crypto)}return O0(X7)}var j$=[];for(let $=0;$<256;++$)j$.push(($+256).toString(16).slice(1));function r1($,O=0){return(j$[$[O+0]]+j$[$[O+1]]+j$[$[O+2]]+j$[$[O+3]]+"-"+j$[$[O+4]]+j$[$[O+5]]+"-"+j$[$[O+6]]+j$[$[O+7]]+"-"+j$[$[O+8]]+j$[$[O+9]]+"-"+j$[$[O+10]]+j$[$[O+11]]+j$[$[O+12]]+j$[$[O+13]]+j$[$[O+14]]+j$[$[O+15]]).toLowerCase()}var j0={};function K7($,O,j){let x;if($)x=p1($.random??$.rng?.()??Rj(),$.msecs,$.seq,O,j);else{let S=Date.now(),K=Rj();Y7(j0,S,K),x=p1(K,j0.msecs,j0.seq,O,j)}return O??r1(x)}function Y7($,O,j){if($.msecs??=-1/0,$.seq??=0,O>$.msecs)$.seq=j[6]<<23|j[7]<<16|j[8]<<8|j[9],$.msecs=O;else if($.seq=$.seq+1|0,$.seq===0)$.msecs++;return $}function p1($,O,j,x,S=0){if($.length<16)throw Error("Random bytes length must be >= 16");if(!x)x=new Uint8Array(16),S=0;else if(S<0||S+16>x.length)throw RangeError(`UUID byte range ${S}:${S+15} is out of buffer bounds`);return O??=Date.now(),j??=$[6]*127<<24|$[7]<<16|$[8]<<8|$[9],x[S++]=O/1099511627776&255,x[S++]=O/4294967296&255,x[S++]=O/16777216&255,x[S++]=O/65536&255,x[S++]=O/256&255,x[S++]=O&255,x[S++]=112|j>>>28&15,x[S++]=j>>>20&255,x[S++]=128|j>>>14&63,x[S++]=j>>>6&255,x[S++]=j<<2&255|$[10]&3,x[S++]=$[11],x[S++]=$[12],x[S++]=$[13],x[S++]=$[14],x[S++]=$[15],x}var d$=K7;class A${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new A$($,O)}async detail(){let{columns:$}=await this.table.detail(),O=$.find((j)=>j.column.id===this.id);if(!O)throw new E(`column ${this.id} is not on table ${this.table.id}`);return O}async name(){let $=await this.detail();return $.column.display_name??$.definition.definition.display_name}async rename($){return await this.table.database.renameColumn(this,$),this}async inferType($){return await this.table.database.inferColumnType(this,$),this}changeType($){return this.table.database.changeColumnType(this,$)}convertIntoNewColumn($){return this.table.database.convertColumnIntoNewColumn(this,$)}casts(){return this.table.database.columnCasts(this)}async delete(){await this.table.database.deleteColumn(this)}async dataType(){return(await this.detail()).definition.definition.data_type}async isMultiSelect(){return(await this.detail()).definition.definition.is_multi_select}async position(){return(await this.detail()).column.position}async definition(){return(await this.detail()).definition}async config(){return(await this.detail()).column.config??void 0}async addOptions($){return await this.table.database.addColumnOptions(this,$),this}toJSON(){return{id:this.id,tableId:this.table.id}}}class F${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new F$($,O)}history(){return this.table.database.rowHistory(this)}toJSON(){return{id:this.id,tableId:this.table.id}}}class Dj{table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new Dj($,O)}async detail(){let{views:$}=await this.table.detail(),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`view ${this.id} is not on table ${this.table.id}`);return O}async name(){return(await this.detail()).name}async position(){return(await this.detail()).position}async layout(){return(await this.detail()).layout}async query(){return(await this.detail()).query}positions(){return this.table.database.viewPositions(this)}toJSON(){return{id:this.id,tableId:this.table.id}}}class J${database;id;constructor($,O){this.database=$;this.id=O}static byId($,O){return new J$($,O)}async detail(){let{tables:$}=await this.database.schema(),O=$.find((j)=>j.table.id===this.id);if(!O)throw new E(`table ${this.id} is not in database ${this.database.id}`);return O}async name(){return(await this.detail()).table.name}async rename($){return await this.database.renameTable(this,$),this}async version(){return(await this.detail()).table.version}async position(){return(await this.detail()).table.position}async columns(){let{columns:$}=await this.detail();return $.map((O)=>A$.byId(this,O.column.id))}addColumn($){return this.database.addColumn(this,$)}async reorderColumns($){return await this.database.reorderColumns(this,$),this}row($){return F$.byId(this,$)}async views(){let{views:$}=await this.detail();return $.map((O)=>Dj.byId(this,O.id))}createWebhook(){return this.database.createWebhook(this)}async delete(){await this.database.deleteTable(this)}toJSON(){return{id:this.id,databaseId:this.database.id}}}async function _j($,O,j,x={}){let S=G(await $.storage.queryDatabases({body:{sql:j,databaseId:x.database?.id,baseVersions:Object.fromEntries((x.baseVersions??[]).map(({table:Q,version:J})=>[Q.id,J]))}})),K=new Map;for(let Q of[x.database,...(x.baseVersions??[]).map(({table:J})=>J.database)]){if(!Q)continue;let J=K.get(Q.id);if(J)J.add(Q);else K.set(Q.id,new Set([Q]))}let Z=(Q)=>{let J=K.get(Q)?.values().next().value;if(J)return J;let I=O($,Q);return K.set(Q,new Set([I])),I},X=(Q)=>{let J=S.tableDatabases[Q];if(!J)throw Error(`SQL response is missing the owner of table ${Q}`);return J$.byId(Z(J),Q)},Y=new Set(Object.keys(S.newVersions).map((Q)=>X(Q).database.id));if(S.statement.kind==="schema")Y.add(S.statement.databaseId);for(let Q of Y)for(let J of K.get(Q)??[])J.invalidateSchema();let L=c(S.statement).with({kind:"select"},(Q)=>Q).with({kind:"schema"},({databaseId:Q,summary:J})=>({kind:"schema",database:Z(Q),summary:J})).with({kind:"insert"},{kind:"update"},{kind:"delete"},({kind:Q,tableId:J,tableName:I})=>({kind:Q,table:X(J),tableName:I})).with({kind:"alterColumnType"},({tableId:Q,tableName:J,columnId:I,columnName:z,to:B})=>{let V=X(Q);return{kind:"alterColumnType",table:V,tableName:J,column:A$.byId(V,I),columnName:z,to:B}}).exhaustive();return{result:S.result?G7(S.result,X,S.tableDatabases):void 0,changesApplied:S.changesApplied,insertedRows:L.kind==="insert"?S.insertedRowIds.map((Q)=>F$.byId(L.table,Q)):[],newVersions:Object.entries(S.newVersions).map(([Q,J])=>({table:X(Q),version:J})),readVersions:Object.entries(S.readVersions).map(([Q,J])=>({table:X(Q),version:J})),truncatedTables:S.truncatedTables,statement:L}}function G7($,O,j){let x=$.sourceTable&&j[$.sourceTable]?O($.sourceTable):void 0;return{columns:$.columns.map(({relatedTable:S,...K})=>({...K,relatedTable:S&&j[S]?O(S):void 0})),rows:$.rows,sourceTable:x,rowHandles:x?$.rowIds.map((S)=>F$.byId(x,S)):[]}}class Cj{table;id;createdBy;record;constructor($,O,j,x){this.table=$;this.id=O;this.createdBy=j;this.record=x}static fromRecord($,O,j){return new Cj($,j.id,O,j)}get tokenPrefix(){return this.record.tokenPrefix}get createdAt(){return this.record.createdAt}delete(){return this.table.database.deleteWebhook(this)}toJSON(){return{id:this.id,tableId:this.table.id,tokenPrefix:this.tokenPrefix}}}class Z0 extends QO{op;row;column;taken;constructor($,O){super($,O);this.name="MacroOpRefusedError",this.message=O.message,this.op=O.op,this.row=O.row,this.column=O.column,this.taken=O.taken}}function Mj($){return c($).with({type:"relation"},({table:O})=>({type:"relation",database:O.database.id,table:O.id})).with({type:Z$.not("relation")},(O)=>O).exhaustive()}var Q7={USER:"People",DOCUMENT:"Documents",TASK:"Tasks",COMPANY:"Companies",CONTACT:"Contacts",CALL_RECORD:"Calls",CHANNEL:"Channels",CHAT:"Chats",PROJECT:"Projects",THREAD:"Emails",CALENDAR_EVENT:"Events",INITIATIVE:"Initiatives"};function J7($){return c($).with({type:"text"},()=>"Text").with({type:"number"},()=>"Number").with({type:"boolean"},()=>"Checkbox").with({type:"date"},()=>"Date").with({type:"link"},()=>"URL").with({type:"select",multi:!0},()=>"Multi-select").with({type:"select",multi:!1},()=>"Select").with({type:"select_number",multi:!0},()=>"Multi-number select").with({type:"select_number",multi:!1},()=>"Number select").with({type:"tag"},()=>"Tag").with({type:"entity"},({target:O})=>Q7[O]).with({type:"relation"},()=>"Relation").exhaustive(()=>"Column")}function x0($){return $.map((O)=>({id:d$(),label:O}))}function a1($,O,j){return $?.kind===O&&"change"in $&&$.change.kind===j}function S0($){return c($).with({kind:"reorder_tables"},({kind:O})=>O).with({kind:Z$.union("table","column","rows","view")},({kind:O,change:j})=>`${O}.${j.kind}`).exhaustive(()=>"unknown")}function l$($,O,j){let[x]=$;if($.length!==1||!a1(x,O,j))throw new f(`expected one ${O}.${j} result, got ${$.map(S0).join(", ")||"none"}`);return x}class V$ extends P{access=new o(this.client,"database",this);async fetch(){return G(await this.client.storage.getDatabase({path:{id:this.id}}))}assertOwns($,O){if(O.id!==this.id)throw new f(`${$} does not belong to database ${this.id}`)}static byId($,O){return new V$($,O)}static async create($,O){let j=G(await $.storage.createDatabase({body:{name:O.name}}));return new V$($,j.id)}static async list($){return G(await $.storage.listDatabases()).map((j)=>new V$($,j.database.id))}query($,O){return _j(this.client,V$.byId,$,{...O,database:this})}invalidateSchema(){this.detail.clear()}schema(){return this.detail.get()}name=this.mappedField("database",($)=>$.name);owner=this.mappedField("database",($)=>M.byId(this.client,$.owner_id));createdAt=this.mappedField("database",($)=>$.created_at);trashedAt=this.mappedField("database",($)=>$.trashed_at??void 0);grant=this.field("grant");tables=this.mappedField("tables",($)=>$.map((O)=>J$.byId(this,O.table.id)));async table($){let{tables:O}=await this.schema(),j=O.find((x)=>x.table.name===$);return j?J$.byId(this,j.table.id):void 0}async createTable($){let{table:O}=l$(await this.applyOps([{kind:"table",table:d$(),change:{kind:"create",name:$.name}}]),"table","created");return J$.byId(this,O)}async applyOps($,O={}){let j={ops:$};if(O.baseVersions!==void 0){for(let{table:S}of O.baseVersions)this.assertOwns(`table ${S.id}`,S.database);j.baseVersions=Object.fromEntries(O.baseVersions.map(({table:S,version:K})=>[S.id,K]))}let{results:x}=await this.mutate(async(S)=>{let K=await S.storage.applyDatabaseOps({path:{id:this.id},body:j});if(K.error!==void 0&&"op"in K.error)throw new Z0(K.response?.status??0,K.error);return K});return x}async reorderTables($){for(let x of $)this.assertOwns(`table ${x.id}`,x.database);let O=await this.applyOps([{kind:"reorder_tables",order:$.map((x)=>x.id)}]),[j]=O;if(O.length!==1||j?.kind!=="reorder_tables")throw new f(`expected one reorder_tables result, got ${O.map(S0).join(", ")||"none"}`);return j.tables.map(({table:x})=>J$.byId(this,x))}async deleteTable($){this.assertOwns(`table ${$.id}`,$.database),l$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"delete"}}]),"table","deleted")}async columnCasts($){return this.assertOwns(`column ${$.id}`,$.table.database),G(await this.client.storage.listDatabaseColumnCasts({path:{id:this.id,table_id:$.table.id,column_id:$.id}}))}async viewPositions($){this.assertOwns(`view ${$.id}`,$.table.database);let{positions:O}=G(await this.client.storage.getDatabaseViewPositions({path:{id:this.id,view_id:$.id}}));return O}async rowHistory($){this.assertOwns(`row ${$.id}`,$.table.database);let{changes:O}=G(await this.client.storage.getDatabaseRowHistory({path:{id:this.id,table_id:$.table.id,row_id:$.id}}));return O}async importTable($){let O=await this.mutate((j)=>j.storage.importDatabaseTable({path:{id:this.id},body:$}));return J$.byId(this,O.id)}webhookOf($){return Cj.fromRecord(J$.byId(this,$.tableId),M.byId(this.client,$.createdBy),$)}async webhooks(){let{webhooks:$}=G(await this.client.storage.listDatabaseWebhooks({path:{id:this.id}}));return $.map((O)=>this.webhookOf(O))}async createWebhook($){this.assertOwns("table",$.database);let O=G(await this.client.storage.createDatabaseWebhook({path:{id:this.id},body:{tableId:$.id}}));return{webhook:this.webhookOf(O.webhook),token:O.token}}async deleteWebhook($){this.assertOwns("webhook",$.table.database),G(await this.client.storage.deleteDatabaseWebhook({path:{id:this.id,webhook_id:$.id}}))}async sharePermissions(){return G(await this.client.storage.getDatabasePermissions({path:{id:this.id}}))}updateSharePermissions($){return this.mutate((O)=>O.storage.updateDatabasePermissions({path:{id:this.id},body:$}))}async changeColumnType($,O){this.assertOwns(`column ${$.id}`,$.table.database);let j=await $.table.version();return l$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"change_type",to:Mj(O.to)}}],{baseVersions:[{table:$.table,version:j}]}),"column","type_changed")}async columnConversion($,O){return this.assertOwns(`column ${$.id}`,$.table.database),G(await this.client.storage.convertDatabaseColumn({path:{id:this.id,table_id:$.table.id,column_id:$.id},body:{to:Mj(O)}}))}async convertColumnIntoNewColumn($,O){let j=await this.columnConversion($,O.to),x=O.name??`${await $.name()} (${J7(O.to)})`,S=d$(),K=[{kind:"column",table:$.table.id,column:S,change:{kind:"create",definition:{source:"new",name:x,type:Mj(O.to),options:x0(j.options)},after:$.id}}];if(j.cells.length>0)K.push({kind:"rows",table:$.table.id,change:{kind:"update",changes:{kind:"per_row",rows:j.cells.map(({row:X,value:Y})=>({row:X,cells:[{column:S,value:Y}]}))}}});let[Z]=await this.applyOps(K,{baseVersions:[{table:$.table,version:j.tableVersion}]});if(!a1(Z,"column","created"))throw new f(`expected a column.created result, got ${Z?S0(Z):"none"}`);return A$.byId($.table,Z.column)}async deleteColumn($){this.assertOwns(`column ${$.id}`,$.table.database);let O=await $.table.version(),{tableVersion:j}=l$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"delete"}}],{baseVersions:[{table:$.table,version:O}]}),"column","deleted");return j}async reorderColumns($,O){this.assertOwns(`table ${$.id}`,$.database);for(let S of O)if(S.table.id!==$.id)throw new f(`column ${S.id} does not belong to table ${$.id}`);let j=await $.version(),{tableVersion:x}=l$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"reorder_columns",order:O.map((S)=>S.id)}}],{baseVersions:[{table:$,version:j}]}),"table","columns_reordered");if(x===void 0)throw new f(`table ${$.id} reordered its columns without a version`);return x}async renameTable($,O){this.assertOwns(`table ${$.id}`,$.database);let j=await $.name(),{tableVersion:x}=l$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"rename",name:O,previousName:j}}]),"table","renamed");if(x===void 0)throw new f(`table ${$.id} was renamed without a version`);return x}async renameColumn($,O){this.assertOwns(`column ${$.id}`,$.table.database);let j=await $.name(),{tableVersion:x}=l$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"rename",name:O,previousName:j}}]),"column","renamed");return x}async inferColumnType($,O){return this.assertOwns(`column ${$.id}`,$.table.database),this.mutate((j)=>j.storage.inferDatabaseColumnType({path:{id:this.id,table_id:$.table.id,column_id:$.id},body:{dataType:O.dataType,baseVersion:O.baseVersion,...O.specificEntityType!==void 0?{specificEntityType:O.specificEntityType}:{}}}))}async addColumn($,O){if(this.assertOwns(`table ${$.id}`,$.database),O.after!==void 0&&O.after.table.id!==$.id)throw new f(`column ${O.after.id} does not belong to table ${$.id}`);let j="property"in O?{source:"existing",property:O.property.id}:{source:"new",name:O.name,type:Mj(O.type),...O.options!==void 0?{options:x0(O.options)}:{},...O.inferType!==void 0?{inferType:O.inferType}:{}},{column:x}=l$(await this.applyOps([{kind:"column",table:$.id,column:d$(),change:{kind:"create",definition:j,...O.after!==void 0?{after:O.after.id}:{}}}]),"column","created");return A$.byId($,x)}async addColumnOptions($,O){return this.assertOwns(`column ${$.id}`,$.table.database),l$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"add_options",options:x0(O)}}]),"column","options_added")}}class X0{client;constructor($){this.client=$}query($,O){return _j(this.client,V$.byId,$,O)}byId($){return V$.byId(this.client,$)}create($){return V$.create(this.client,$)}list(){return V$.list(this.client)}}class Pj{id;name;constructor($,O){this.id=$;this.name=O}static async list($){let{skills:O}=G(await $.storage.getSystemSkillsHandler());return O.map((j)=>new Pj(j.id,j.name))}}class K0{client;async byTeamSlug($){let O=G(await this.client.storage.getDocumentByTeamSlug({path:{slug:$}}));if(typeof O!=="object"||O===null||!("data"in O)||typeof O.data!=="object"||O.data===null||!("documentMetadata"in O.data)||typeof O.data.documentMetadata!=="object"||O.data.documentMetadata===null||!("documentId"in O.data.documentMetadata)||typeof O.data.documentMetadata.documentId!=="string")throw Error("Invalid team task document response");return w.byId(this.client,O.data.documentMetadata.documentId)}async validatePermissionsToken($){let O=G(await this.client.storage.validateDocumentPermissionsToken({body:{token:$}}));return{document:w.byId(this.client,O.document_id),user:O.user_id?M.byId(this.client,O.user_id):void 0,accessLevel:O.access_level,expiresAt:O.exp,issuer:O.iss}}async createUpload($){let O={documentName:$.name,sha:$.sha,fileType:$.fileType,mimeType:$.mimeType,projectId:$.project?.id,teamId:$.team?.id,branchedFromId:$.branchedFrom?.id,emailAttachmentId:$.attachment?.id,isTask:$.isTask},j=G(await this.client.storage.createDocument({body:O})).data;return{document:w.byId(this.client,j.documentMetadata.documentId),uploadUrl:j.presignedUrl??void 0,contentType:j.contentType,content:j.documentMetadata.content}}constructor($){this.client=$}byId($){return w.byId(this.client,$)}create($){return w.create(this.client,$)}async createCanvas($){let O=G(await this.client.storage.createCanvasHandler({body:{documentName:$.name,projectId:$.project?.id}}));return w.byId(this.client,O.documentId)}createSnippet($){return w.createSnippet(this.client,$)}createSkill($){return w.createSkill(this.client,$)}systemSkills(){return Pj.list(this.client)}search($,O){return w.search(this.client,$,O)}recent($){return w.recent(this.client,$)}recentlyDeleted(){return w.recentlyDeleted(this.client)}}class WO extends P{async fetch(){let{attachment:$}=G(await this.client.email.getAttachment({path:{id:this.id}}));return $}static byId($,O){return new WO($,O)}static from($,O){return new WO($,O.db_id,O)}filename=this.field("filename");mimeType=this.field("mime_type");size=this.field("size_bytes");dataUrl=this.field("data_url");sfsId=this.field("sfs_id");contentId=this.field("content_id");async toDocument(){let{document_id:$}=G(await this.client.email.getAttachmentDocumentId({path:{id:this.id}}));return w.byId(this.client,$)}}class R$ extends X${access=new o(this.client,"email_thread",this);async followup(){return G(await this.client.storage.getEmailFollowup({path:{thread_id:this.id}}))}async setFollowup($){return G(await this.client.storage.setEmailFollowup({path:{thread_id:this.id},body:$}))}async calendarInvitations(){return G(await this.client.email.getThreadCalendarInvitations({path:{thread_id:this.id}}))}async addEventToCalendar($,O,j={}){let x=G(await this.client.email.copyThreadCalendarInvitation({path:{thread_id:this.id,message_id:$.id,invitation_id:O.id},body:{calendarId:j.calendar?.id}}));return $$.fromRecord(this.client,x)}async update($){await this.mutate((O)=>O.storage.editThreadV2({path:{thread_id:this.id},body:{projectId:$.project===void 0?void 0:$.project?.id??null,sharePermission:$.sharePermission?i$($.sharePermission):void 0}}))}entityType="email_thread";propertyEntityType="THREAD";async fetch(){let{thread:$}=G(await this.client.email.getThread({path:{thread_id:this.id},query:{limit:100}}));return $}static byId($,O){return new R$($,O)}createdAt=this.field("created_at");updatedAt=this.field("updated_at");isRead=this.field("is_read");inboxVisible=this.field("inbox_visible");accessLevel=this.field("access_level");providerId=this.field("provider_id");link=this.mappedField("link_id",($)=>T$.byId(this.client,$));project=this.mappedField("project_id",($)=>$?n.byId(this.client,$):void 0);latestInboundAt=this.field("latest_inbound_message_ts");latestOutboundAt=this.field("latest_outbound_message_ts");latestNonSpamAt=this.field("latest_non_spam_message_ts");async subject(){let{messages:$}=await this.detail.get();for(let O of $)if(O.subject)return O.subject;return}async participants(){let{messages:$}=await this.detail.get(),O=new Map;for(let j of $)for(let x of[j.from,...j.to,...j.cc,...j.bcc])if(x&&!O.has(x.email))O.set(x.email,x);return[...O.values()]}async messages($){return G(await this.client.email.getThreadMessagesHandler({path:{id:this.id},query:{...$?.since?{since:$.since}:{},...$?.limit?{limit:$.limit}:{}}})).map((j)=>D$.from(this.client,j))}async attachments(){let{messages:$}=await this.detail.get();return $.flatMap((O)=>O.attachments.map((j)=>WO.from(this.client,j)))}async reply($){let O=$.subject??await this.subject()??"",{message:j}=await this.mutate((x)=>x.email.sendMessage({body:{message:{thread_db_id:this.id,replying_to_id:$.replyingTo?.id??null,to:$.to,cc:$.cc??null,bcc:$.bcc??null,subject:O,body_text:$.bodyText}}}));return j.db_id?D$.byId(this.client,j.db_id):void 0}async archive($=!0){await this.mutate((O)=>O.email.archiveThread({path:{id:this.id},body:{value:$}}))}async updateState($){await this.mutate((O)=>O.email.updateThreadState({path:{id:this.id},body:$}))}async operations(){return G(await this.client.email.threadOperations({path:{id:this.id}}))}async markSeen(){await this.mutate(($)=>$.email.threadSeen({path:{id:this.id}}))}async addLabel($){await this.mutate((O)=>O.email.addRemoveThreadLabel({path:{id:this.id},body:{label_id:$.id,value:!0}}))}async removeLabel($){await this.mutate((O)=>O.email.addRemoveThreadLabel({path:{id:this.id},body:{label_id:$.id,value:!1}}))}async moveToProject($){await this.mutate((O)=>O.email.updateThreadProject({path:{thread_id:this.id},body:{projectId:$?.id??null}}))}static search=x$({filters:{email_filters:{}},type:"email",make:($,O)=>new R$($,O.thread_id)})}class D$ extends P{async fetch(){return G(await this.client.email.getMessage({path:{id:this.id}}))}static byId($,O){return new D$($,O)}static from($,O){return new D$($,O.db_id,O)}static async send($,O){let{message:j}=G(await $.email.sendMessage({body:{message:{to:O.to,cc:O.cc??null,bcc:O.bcc??null,subject:O.subject,body_text:O.bodyText}}}));return j.db_id?D$.byId($,j.db_id):void 0}subject=this.field("subject");from=this.field("from");to=this.field("to");cc=this.field("cc");bcc=this.field("bcc");body=this.field("body_parsed");sentAt=this.field("internal_date_ts");labels=this.field("labels");link=this.mappedField("link_id",($)=>T$.byId(this.client,$));async operationStatus(){return G(await this.client.email.messageOperationStatus({path:{id:this.id}}))}async resolveOperation($){await this.mutate((O)=>O.email.resolveMessageOperation({path:{id:this.id},body:$}))}async completeDraftAttachment($,O=0){let j=await this.link();await this.mutate((x)=>x.email.completeDraftAttachment({path:{id:this.id,attachment_id:$},query:{draft_generation:O},headers:{"X-Email-Link-Id":j.id}}))}async transferDraft($){let O=await this.detail.get();return this.mutate((j)=>j.email.transferDraft({path:{id:this.id},body:{...$,draft_generation:$.draft_generation??O.draft_generation??0},headers:{"X-Email-Link-Id":O.link_id}}))}async addLabel($){await this.mutate((O)=>O.email.addRemoveLabel({body:{label_id:$.id,message_ids:[this.id],value:!0}}))}async removeLabel($){await this.mutate((O)=>O.email.addRemoveLabel({body:{label_id:$.id,message_ids:[this.id],value:!1}}))}async thread(){return R$.byId(this.client,(await this.detail.get()).thread_db_id)}}class LO extends D${async draftContext(){let $=await this.detail.get();return{headers:{"X-Email-Link-Id":$.link_id},query:{draft_generation:$.draft_generation??0}}}static byId($,O){return new LO($,O)}draftGeneration=this.field("draft_generation");async update($){let{headers:O,query:j}=await this.draftContext();await this.mutate((x)=>x.email.createDraft({headers:O,body:{draft:{...Y0($),db_id:this.id,draft_generation:$.draftGeneration??j.draft_generation}}}))}async delete(){let{headers:$,query:O}=await this.draftContext();await this.mutate((j)=>j.email.deleteDraft({path:{id:this.id},headers:$,query:O}))}async schedule($,O){let{headers:j,query:x}=await this.draftContext();await this.mutate((S)=>S.email.upsertScheduledMessage({path:{id:this.id},headers:j,query:x,body:{send_time:$,include_signature:O?.includeSignature}}))}async unschedule(){let{headers:$,query:O}=await this.draftContext();await this.mutate((j)=>j.email.deleteScheduledDraft({path:{message_id:this.id},headers:$,query:O}))}async addAttachment($){let O={file_name:$.fileName,sha:$.sha,size:$.size,upload_id:$.uploadId},{headers:j,query:x}=await this.draftContext(),S=await this.mutate((K)=>K.email.addDraftAttachment({path:{id:this.id},headers:j,query:x,body:O}));return{attachment:oO.byId(this.client,this,S.attachment_id,!1,x.draft_generation),uploadUrl:S.upload_url,contentType:S.content_type}}async forwardAttachment($){let{headers:O,query:j}=await this.draftContext(),x=await this.mutate((S)=>S.email.addForwardedAttachment({path:{id:this.id},headers:O,query:j,body:{attachment_id:$.id}}));return oO.byId(this.client,this,x.attachment_id,!0,j.draft_generation)}async removeAttachment($){if($.draft.id!==this.id)throw Error("Attachment belongs to another draft");let{headers:O}=await this.draftContext(),j={draft_generation:$.draftGeneration};if($.forwarded)await this.mutate((x)=>x.email.removeForwardedAttachment({path:{id:this.id,attachment_id:$.id},headers:O,query:j}));else await this.mutate((x)=>x.email.removeDraftAttachment({path:{id:this.id,attachment_id:$.id},headers:O,query:j}))}async verifyAttachment($){if($.draft.id!==this.id||$.forwarded)throw Error("Expected an uploaded attachment on this draft");await this.completeDraftAttachment($.id,$.draftGeneration)}}class oO{draft;id;forwarded;draftGeneration;constructor($,O,j,x){this.draft=$;this.id=O;this.forwarded=j;this.draftGeneration=x}static byId($,O,j,x=!1,S=0){return new oO(O,j,x,S)}complete(){return this.draft.verifyAttachment(this)}remove(){return this.draft.removeAttachment(this)}toJSON(){return{id:this.id,draftId:this.draft.id,forwarded:this.forwarded,draftGeneration:this.draftGeneration}}}function Y0($){let{bodyText:O,bodyHtml:j,bodyMacro:x,headers:S,includeSignature:K,draftGeneration:Z,thread:X,replyingTo:Y,...L}=$;return{...L,body_text:O,body_html:j===void 0?void 0:btoa(Array.from(new TextEncoder().encode(j),(Q)=>String.fromCharCode(Q)).join("")).replaceAll("+","-").replaceAll("/","_").replaceAll("=",""),body_macro:x,headers_json:S,include_signature:K,draft_generation:Z,thread_db_id:X?.id,replying_to_id:Y?.id}}class NO extends P{inbox;constructor($,O,j,x){super($,O,j);this.inbox=x}get headers(){return this.inbox?{"X-Email-Link-Id":this.inbox.id}:void 0}static byId($,O,j){return new NO($,O,void 0,j)}static from($,O,j){return new NO($,O.id,O,j)}async fetch(){let $=G(await this.client.email.listEmailFilters({headers:this.headers})).filters.find((O)=>O.id===this.id);if(!$)throw new E(`Email filter ${this.id} is unavailable`);return $}emailAddress=this.field("email_address");emailDomain=this.field("email_domain");isImportant=this.field("is_important");async setImportant($){let O=await this.detail.get();await this.mutate((j)=>j.email.upsertEmailFilter({headers:this.headers,body:{email_address:O.email_address,email_domain:O.email_domain,is_important:$}}))}async delete(){await this.mutate(($)=>$.email.deleteEmailFilter({path:{id:this.id},headers:this.headers}))}}class OO extends P{async fetch(){let{labels:$}=G(await this.client.email.listLabels()),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`label ${this.id} not found`);return O}static byId($,O){return new OO($,O)}static async list($){let{labels:O}=G(await $.email.listLabels());return O.map((j)=>new OO($,j.id,j))}static async create($,O){let{label:j}=G(await $.email.createLabel({body:{label_name:O}}));if(!j.id)throw new f("created label has no id");return new OO($,j.id)}async delete(){G(await this.client.email.deleteLabel({path:{id:this.id}}))}name=this.field("name");linkId=this.field("linkId");type=this.field("type");createdAt=this.field("createdAt");labelListVisibility=this.field("labelListVisibility");messageListVisibility=this.field("messageListVisibility")}class G0{client;async createDraft($,O){let j=G(await this.client.email.createDraft({body:{draft:Y0($)},headers:O?{"X-Email-Link-Id":O.id}:void 0}));if(!j.draft.db_id)throw Error("Draft response has no message id");return LO.byId(this.client,j.draft.db_id)}draftById($){return LO.byId(this.client,$)}async*scheduled($){let O=$?.pageSize??100;if(!Number.isInteger(O)||O<1)throw Error("pageSize must be positive");let j=Math.min(O,1000);for(let x=0;;x+=j){let S=G(await this.client.email.getScheduledMessages({query:{offset:x,limit:j},headers:$?.inbox?{"X-Email-Link-Id":$.inbox.id}:void 0}));for(let K of S.messages)yield LO.byId(this.client,K.db_id);if(S.messages.length<j)return}}async filters($){return G(await this.client.email.listEmailFilters({headers:$?{"X-Email-Link-Id":$.id}:void 0})).filters.map((O)=>NO.from(this.client,O,$))}async upsertFilter($,O){return NO.from(this.client,G(await this.client.email.upsertEmailFilter({headers:O?{"X-Email-Link-Id":O.id}:void 0,body:{email_address:$.emailAddress,email_domain:$.emailDomain,is_important:$.isImportant}})).filter,O)}async contacts(){return G(await this.client.email.listContacts()).contacts}reminders($){let{inboxes:O,...j}=$??{};return u(async(x)=>{let S=G(await this.client.storage.listEmailReminders({query:{...j,inboxIds:O?.map((K)=>K.id),cursor:x}}));return{items:S.items.map(({threadId:K,...Z})=>({...Z,thread:R$.byId(this.client,K)})),nextCursor:S.nextCursor}})}constructor($){this.client=$}byId($){return R$.byId(this.client,$)}message($){return D$.byId(this.client,$)}attachment($){return WO.byId(this.client,$)}link($){return T$.byId(this.client,$)}links(){return T$.list(this.client)}async connectionProviders(){return G(await this.client.auth.emailConnectionProviders())}async recoverDraftTransfer($){return G(await this.client.email.recoverDraftTransfer({path:{id:$}}))}send($){return D$.send(this.client,$)}search($,O){return R$.search(this.client,$,O)}inbox($){return u(async(O)=>{let j=G(await this.client.email.previewsInboxCursor({path:{view:"inbox"},query:{...$?.pageSize?{limit:$.pageSize}:{},...$?.sort?{sort_method:$.sort}:{},...O?{cursor:O}:{}}}));return{items:j.items.map((x)=>R$.byId(this.client,x.id)),nextCursor:j.next_cursor}})}label($){return OO.byId(this.client,$)}labels(){return OO.list(this.client)}createLabel($){return OO.create(this.client,$)}async deleteLabel($){G(await this.client.email.deleteLabel({path:{id:$.id}}))}async blockSender($){G(await this.client.email.blockSender({body:{email_address:$}}))}async unblockSender($){G(await this.client.email.unblockSender({body:{email_address:$}}))}async blockedSenders(){return G(await this.client.email.listBlockedSenders()).blocked_emails}}class HO{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new HO($,O)}async delete(){G(await this.client.storage.deleteEntityMention({path:{mention_id:this.id}}))}toJSON(){return{id:this.id}}}class Q0{client;constructor($){this.client=$}byId($){return HO.byId(this.client,$)}async create($,O){let j=G(await this.client.storage.createEntityMention({body:{source_entity_id:$.entity.id,source_entity_type:$.type,entity_id:O.entity.id,entity_type:O.type}}));return HO.byId(this.client,j.id)}}class J0{client;constructor($){this.client=$}async list($={}){let{favorites:O}=G(await this.client.storage.listFavorites({query:{entityType:$.entityTypes,entityId:$.entityIds}}));return O}async add($){return G(await this.client.storage.addFavorite({body:{entityId:$.id,entityType:$.entityType}}))}async remove($){G(await this.client.storage.removeFavoriteByEntity({path:{entity_type:$.entityType,entity_id:$.id}}))}async reorder($){G(await this.client.storage.reorderFavorites({body:{favorites:$}}))}}class jO extends z${entityType="foreign_entity";async fetch(){return G(await this.client.storage.getForeignEntity({path:{id:this.id}}))}static byId($,O){return new jO($,O)}static fromRecord($,O){return new jO($,O.id,O)}foreignEntityId=this.field("foreignEntityId");source=this.field("foreignEntitySource");storedForId=this.field("storedForId");storedForAuthEntity=this.field("storedForAuthEntity");createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");async metadata(){return(await this.detail.get()).metadata}}function i1({login:$,...O}){return{...O,login:$??void 0}}class V0{client;constructor($){this.client=$}byId($){return jO.byId(this.client,$)}async bySource($,O){return jO.fromRecord(this.client,G(await this.client.storage.getForeignEntityBySource({path:{source:$,foreign_entity_id:O}})))}async githubPullRequestFacets(){let{repositories:$,authors:O,assignees:j,labels:x}=G(await this.client.storage.getGithubPullRequestFacets());return{repositories:$,authors:O.map(i1),assignees:j.map(i1),labels:x.map(({color:S,...K})=>({...K,color:S??void 0}))}}}class r${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new r$($,O)}async detail(){let O=(await this.form.schema()).sections.flatMap((j)=>j.kind==="questions"?j.questions:[]).find((j)=>j.id===this.id);if(!O)throw new E(`question ${this.id} is not on form ${this.form.id}`);return O}async title(){return(await this.detail()).title}async column(){return A$.byId(await this.form.table(),(await this.detail()).column)}async options(){return(await this.detail()).options.map(($)=>UO.byId(this,$.id))}}class UO{question;id;constructor($,O){this.question=$;this.id=O}static byId($,O){return new UO($,O)}async detail(){let $=(await this.question.detail()).options.find((O)=>O.id===this.id);if(!$)throw new E(`option ${this.id} is not on question ${this.question.id}`);return $}async label(){return(await this.detail()).label}async color(){return(await this.detail()).color??void 0}}class RO{form;id;detail;constructor($,O,j){this.form=$;this.id=O;this.detail=new B$(()=>this.load(),j)}async load(){let $=await this.form.myResponse();if($.response.id!==this.id)throw new E(`response ${this.id} is not your current response`);return $}static byId($,O,j){return new RO($,O,j)}async status(){return(await this.detail.get()).status}async row(){return(await this.detail.get()).row}async answers(){return(await this.detail.get()).answers}async booking(){return(await this.detail.get()).booking}async refresh(){let $=await this.load();return this.detail=new B$(()=>this.load(),$),this}}class p${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new p$($,O)}async detail(){let $=(await this.form.schema()).sections.find((O)=>O.id===this.id);if(!$)throw new E(`section ${this.id} is not on form ${this.form.id}`);return $}async title(){return(await this.detail()).title}async questions(){let $=await this.detail();return $.kind==="questions"?$.questions.map((O)=>r$.byId(this.form,O.id)):[]}}class Aj{entityType;id;constructor($,O){this.entityType=$;this.id=O}static byId($,O){return new Aj($,O)}}class y$ extends P{async fetch(){return G(await this.client.storage.getForm({path:{id:this.id}}))}static byId($,O){return new y$($,O)}static async create($,O){let j=G(await $.storage.createForm({body:{name:O.name,source:O.table?{kind:"table",databaseId:O.table.database.id,tableId:O.table.id}:{kind:"new"}}}));return new y$($,j.form.id,j)}static async list($,O){if(!O)return G(await $.storage.listAccessibleForms()).map(({form:S})=>new y$($,S.id));return G(await $.storage.listForms({query:{databaseId:O.id}})).map((x)=>new y$($,x.id))}schema(){return this.detail.get()}name=this.mappedField("form",($)=>$.name);description=this.mappedField("form",($)=>$.description);owner=this.mappedField("form",($)=>M.byId(this.client,$.ownerId));database=this.mappedField("form",($)=>V$.byId(this.client,$.databaseId));table=this.mappedField("form",($)=>J$.byId(V$.byId(this.client,$.databaseId),$.tableId));audience=this.mappedField("form",($)=>$.audience);status=this.mappedField("form",($)=>$.status);closesAt=this.mappedField("form",($)=>$.closesAt??void 0);access=this.field("access");async sections(){return(await this.detail.get()).sections.map(($)=>p$.byId(this,$.id))}async questions(){return(await this.detail.get()).sections.flatMap(($)=>$.kind==="questions"?$.questions.map((O)=>r$.byId(this,O.id)):[])}async update($){return await this.mutate((O)=>O.storage.updateForm({path:{id:this.id},body:$})),this}assertOwns($){if($.form.id!==this.id)throw new f(`question or section does not belong to form ${this.id}`)}async replaceLayout($){let O=await this.table(),j=(Z)=>{if(Z.table.id!==O.id||Z.table.database.id!==O.database.id)throw new f(`column does not belong to form ${this.id}'s table`);return Z.id},x=(Z)=>({conjunction:Z.conjunction,conditions:Z.conditions.map((X)=>c(X).with({kind:"group"},(Y)=>({kind:"group",...x(Y)})).with({kind:"condition"},(Y)=>({kind:"condition",column:j(Y.column),test:c(Y.test).with({kind:"options"},(L)=>({...L,options:L.options.map((Q)=>Q.id)})).with({kind:"entities"},(L)=>({...L,entities:L.entities.map((Q)=>Q.id)})).with({kind:Z$.union("presence","text","number","date","checkbox")},(L)=>L).exhaustive()})).exhaustive())}),S={sections:$.map((Z)=>{if(Z.section)this.assertOwns(Z.section);let X={id:Z.section?.id??d$(),title:Z.title,description:Z.description??""};return c(Z).with({kind:"booking"},(Y)=>({...X,kind:"booking",target:Y.target})).with({kind:"gate"},(Y)=>({...X,kind:"gate",rules:x(Y.rules),message:Y.message})).with({kind:"questions"},(Y)=>({...X,kind:"questions",questions:Y.questions.map((L)=>{if(L.question)this.assertOwns(L.question);return{id:L.question?.id??d$(),column:j(L.column),helpText:L.helpText??"",required:L.required??!1,widget:L.widget??null}})})).exhaustive()})},K=await this.mutate((Z)=>Z.storage.putFormLayout({path:{id:this.id},body:S}));return{form:this,publicationError:K.publicationError}}wireAnswers($){return $.map(({question:O,value:j})=>{this.assertOwns(O);let x=c(j).with({type:"rows"},(S)=>({type:"rows",value:S.value.map((K)=>K.id)})).with({type:"options"},(S)=>({type:"options",value:S.value.map((K)=>{if(K.question.id!==O.id||K.question.form.id!==this.id)throw new f("option does not belong to the answered question");return{id:K.id}})})).with({type:"entities"},(S)=>({type:"entities",value:S.value.map(({entityType:K,entity:Z})=>({entityType:K,entityId:Z.id}))})).with({type:Z$.union("text","number","boolean","date","link","clear")},(S)=>S).exhaustive();return{question:O.id,value:x}})}unlockedBooking($){return $?{...$,section:p$.byId(this,$.section)}:void 0}async outcome($,O){return c($).with({outcome:"stopped"},(j)=>({...j,section:p$.byId(this,j.section)})).with({outcome:"submitted"},async(j)=>{let x=F$.byId(await this.table(),j.row),S=this.unlockedBooking(j.booking);return{outcome:"submitted",response:RO.byId(this,j.response,{status:"submitted",row:x,answers:O,booking:S}),row:x,...S?{booking:S}:{}}}).exhaustive()}async submit($){let O={answers:this.wireAnswers($)};return this.outcome(G(await this.client.storage.submitFormResponse({path:{id:this.id},body:O})),$)}async editResponse($){let O={answers:this.wireAnswers($)};return this.outcome(G(await this.client.storage.editMyFormResponse({path:{id:this.id},body:O})),$)}async myResponse(){let $=G(await this.client.storage.getMyFormResponse({path:{id:this.id}})),O=await this.table(),j=await Promise.all($.answers.map(async(K)=>{let Z=r$.byId(this,K.question),X=await c(K.value).with({type:"options"},(Y)=>({type:"options",value:Y.value.map((L)=>{if(!("id"in L))throw new f("stored form answers must reference options by id");return UO.byId(Z,L.id)})})).with({type:"entities"},(Y)=>({type:"entities",value:Y.value.map((L)=>({entityType:L.entityType,entity:Aj.byId(L.entityType,L.entityId)}))})).with({type:"rows"},async(Y)=>{let L=await Z.detail();if(L.kind.type!=="relation")throw new f("row answer requires a relation question");let Q=J$.byId(V$.byId(this.client,L.kind.database),L.kind.table);return{type:"rows",value:Y.value.map((J)=>F$.byId(Q,J))}}).with({type:Z$.union("text","number","boolean","date","link","clear")},(Y)=>Y).exhaustive(()=>{throw new f(`answer to question ${Z.id} has a type this SDK doesn't know`)});return{question:Z,value:X}})),x=$.response.row?F$.byId(O,$.response.row):void 0,S=this.unlockedBooking($.booking);return{...S?{booking:S}:{},response:RO.byId(this,$.response.id,{status:$.response.status,row:x,answers:j,booking:S}),status:$.response.status,stoppedAtSection:$.response.stoppedAtSection?p$.byId(this,$.response.stoppedAtSection):void 0,row:x,submittedAt:$.response.submittedAt,updatedAt:$.response.updatedAt,answers:j}}async responseSummary(){let $=G(await this.client.storage.getFormResponseSummary({path:{id:this.id}}));return{...$,stoppedBySection:$.stoppedBySection.map((O)=>({section:p$.byId(this,O.section),count:O.count}))}}async tally(){return G(await this.client.storage.getFormTally({path:{id:this.id}})).questions.map((O)=>{let j=r$.byId(this,O.question);return{question:j,responses:O.responses,buckets:O.buckets.flatMap((x)=>c(x.value).with({kind:"option"},(S)=>[{count:x.count,value:{kind:"option",option:UO.byId(j,S.option)}}]).with({kind:"checkbox"},(S)=>[{count:x.count,value:S}]).exhaustive((S)=>{return console.warn("macro sdk: unknown form tally bucket",S),[]}))}})}async sharePermissions(){return G(await this.client.storage.getFormPermissions({path:{id:this.id}}))}updateSharePermissions($){return this.mutate((O)=>O.storage.updateFormPermissions({path:{id:this.id},body:$}))}webUrl(){return`${this.client.webAppUrl}/app/form/${this.id}`}respondUrl(){return`${this.client.webAppUrl}/app/form/${this.id}/respond`}}class B0{client;constructor($){this.client=$}byId($){return y$.byId(this.client,$)}create($){return y$.create(this.client,$)}list($){return y$.list(this.client,$)}}class DO extends P{static byId($,O){return new DO($,O)}async fetch(){return G(await this.client.storage.getGithubPullRequest({path:{id:this.id}}))}title=this.field("title");url=this.field("url");status=this.field("status");async changes(){let $=G(await this.client.storage.getGithubPullRequestChanges({path:{id:this.id}}));return{changeset:$.changeset?new W0(this.client,this,$.changeset):void 0,error:$.error??void 0}}}class W0{client;pullRequest;record;constructor($,O,j){this.client=$;this.pullRequest=O;this.record=j}get id(){return this.record.id}async patch(){return G(await this.client.storage.getGithubPullRequestChangesPatch({path:{id:this.pullRequest.id},query:{changeset:this.id}})).patch}toJSON(){return{pullRequestId:this.pullRequest.id,...this.record}}}class L0{client;constructor($){this.client=$}byId($){return DO.byId(this.client,$)}forEntity($){return DO.byId(this.client,$.id)}}class _O extends P{static byId($,O){return new _O($,O)}async fetch(){return G(await this.client.storage.getHarnessPairing({path:{code:this.id}}))}name=this.field("requested_name");expiresAt=this.field("expires_at");async approve($){let O={name:$?.name,team_id:$?.team?.id,allow_permission_bypass:$?.allowPermissionBypass};return W$.from(this.client,await this.mutate((j)=>j.storage.approveHarnessPairing({path:{code:this.id},body:O})))}}class $j{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new $j($,O)}async claim($){let O=G(await this.client.storage.claimHarnessPairing({path:{pairing_id:this.id},body:{device_secret:$}}));return"harness"in O?{harness:W$.from(this.client,O.harness),token:O.token}:void 0}toJSON(){return{id:this.id}}}class N0{client;constructor($){this.client=$}byId($){return W$.byId(this.client,$)}async list(){return G(await this.client.storage.listHarnesses()).map(($)=>W$.from(this.client,$))}async me(){return W$.from(this.client,G(await this.client.storage.getSelfHarness()))}async deleteSelf(){G(await this.client.storage.deleteSelfHarness())}async agents(){return G(await this.client.storage.listHarnessAgents()).map(($)=>I$.byId(this.client,$.bot_id))}async sessions(){return G(await this.client.storage.listHarnessSessions()).map(($)=>i.byId(this.client,$.session_id))}pairing($){return _O.byId(this.client,$)}async createPairing($){let O=G(await this.client.storage.createHarnessPairing({body:$}));return{pairing:_O.byId(this.client,O.code),device:$j.byId(this.client,O.pairing_id),deviceSecret:O.device_secret,expiresAt:O.expires_at,pollIntervalSeconds:O.poll_interval_seconds}}}var V7="00000001-0000-0000-0000-000000000002",B7="00000001-0000-0000-0002-000000000004";function W7($){let O=$.match(/^https:\/\/github\.com\/([^/]+)\/([^/]+)\/pull\/([1-9][0-9]*)\/?(?:[?#].*)?$/i);if(!O)throw Error(`Expected a GitHub pull request URL like https://github.com/owner/repo/pull/1, got ${$}`);return`${O[1]}/${O[2]}/pull/${O[3]}`}class _$ extends w{static byId($,O){return new _$($,O)}static async create($,O){let{documentId:j}=G(await $.storage.createTaskHandler({body:{taskName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null,teamId:O.team?.id??null,shareWithTeam:O.shareWithTeam??!0}}));return new _$($,j)}static async forPullRequest($,O){let j=W7(O),{pullRequests:x}=G(await $.storage.getGithubPullRequestTasks({body:{githubKeys:[j]}}));return(x[0]?.taskIds??[]).map((S)=>new _$($,S))}async completed(){let{subType:$}=await this.detail.get();if($!=="task")return;let j=(await this.properties()).find((x)=>x.definition.id===V7)?.value;return j?.type==="SelectOption"&&j.value.includes(B7)}webUrl(){return`${this.client.webAppUrl}/app/task/${this.id}`}static search=x$({filters:{document_filters:{sub_types:["task"],task_filters:{}}},type:"document",make:($,O)=>new _$($,O.document_id)})}class xO extends P{access=new o(this.client,"initiative",this);static byId($,O){return new xO($,O)}static from($,O){return new xO($,O.id,O)}async fetch(){return G(await this.client.storage.getInitiative({path:{initiative_id:this.id}}))}name=this.field("name");owner=this.mappedField("ownerId",($)=>M.byId(this.client,$));members=this.mappedField("memberIds",($)=>$.map((O)=>M.byId(this.client,O)));tasks=this.mappedField("taskIds",($)=>$.map((O)=>_$.byId(this.client,O)));accessLevel=this.field("userAccessLevel");sharePermissions=this.field("sharePermission");async update($){await this.mutate((O)=>O.storage.updateInitiative({path:{initiative_id:this.id},body:{name:$.name,memberIds:$.members?.map((j)=>j.id),sharePermission:$.sharePermission?i$($.sharePermission):void 0}}))}async delete(){await this.mutate(($)=>$.storage.deleteInitiative({path:{initiative_id:this.id}}))}}class U0{client;constructor($){this.client=$}byId($){return xO.byId(this.client,$)}async list(){return G(await this.client.storage.listInitiatives()).initiatives.map(($)=>xO.byId(this.client,$.id))}async create($){return xO.from(this.client,G(await this.client.storage.createInitiative({body:{name:$.name,description:$.description,memberIds:$.members?.map((O)=>O.id),shareWithTeam:$.shareWithTeam,propertyValues:$.propertyValues}})))}}class z0{client;constructor($){this.client=$}byId($){return H$.byId(this.client,$)}async create($){return H$.from(this.client,G(await this.client.storage.meetingCreate({body:$})))}async list(){return G(await this.client.storage.meetingList()).meetings.map(($)=>H$.from(this.client,$))}async active(){return G(await this.client.storage.meetingListActive()).meetings.map(($)=>H$.from(this.client,$))}async lookup($){return H$.from(this.client,G(await this.client.storage.meetingLookup({path:{token:$}})))}}class zO extends P{async fetch(){return G(await this.client.notification.getTypedNotificationById({path:{notification_id:this.id}}))}static byId($,O){return new zO($,O)}static from($,O){return new zO($,O.id,O)}static list($,O){return u(async(j)=>{let x=G(await $.notification.listTypedNotifications({query:{...O?.pageSize?{limit:O.pageSize}:{},...O?.states!==void 0?{states:O.states.join(",")}:{},...j?{cursor:j}:{}}}));return{items:x.items.map((S)=>zO.from($,S)),nextCursor:x.next_cursor}})}type=this.field("notification_event_type");createdAt=this.field("created_at");updatedAt=this.field("updated_at");state=this.field("state");done=this.mappedField("state",($)=>$==="done");sent=this.field("sent");viewedAt=this.field("viewed_at");deletedAt=this.field("deleted_at");owner=this.mappedField("owner_id",($)=>M.byId(this.client,$));sender=this.mappedField("sender_id",($)=>$?M.byId(this.client,$):void 0);metadata=this.field("notification_metadata");async seen(){return await this.state()!=="unseen"}async markSeen(){await this.mutate(($)=>$.notification.bulkMarkNotificationsSeen({body:{notificationIds:[this.id]}}))}async markDone(){await this.mutate(($)=>$.notification.bulkMarkNotificationsDone({body:{notificationIds:[this.id]}}))}async markUndone(){await this.mutate(($)=>$.notification.bulkMarkNotificationsUndone({body:{notificationIds:[this.id]}}))}async delete(){await this.mutate(($)=>$.notification.deleteUserNotificationV2({path:{notification_id:this.id}}))}}class I0{client;constructor($){this.client=$}byId($){return zO.byId(this.client,$)}list($){return zO.list(this.client,$)}async markSeen($){G(await this.client.notification.bulkMarkNotificationsSeen({body:{notificationIds:$}}))}async markDone($){G(await this.client.notification.bulkMarkNotificationsDone({body:{notificationIds:$}}))}async delete($){G(await this.client.notification.bulkDeleteUserNotificationsV2({body:{notificationIds:$}}))}async preferences(){return G(await this.client.notification.getNotificationTypePreferences())}async enableType($){G(await this.client.notification.enableNotificationType({path:{notification_event_type:$}}))}async disableType($){G(await this.client.notification.disableNotificationType({path:{notification_event_type:$}}))}}class T0{client;constructor($){this.client=$}async list(){let{data:$}=G(await this.client.storage.getPinsHandler({}));return $?.recent??[]}async add($,O){G(await this.client.storage.addPinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType,pinIndex:O.index}}))}async remove($){G(await this.client.storage.removePinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType}}))}async reorder($){G(await this.client.storage.reorderPinsHandler({body:$}))}}class H0{client;constructor($){this.client=$}byId($){return n.byId(this.client,$)}create($){return n.create(this.client,$)}search($,O){return n.search(this.client,$,O)}}class CO{client;definitionId;id;record;constructor($,O,j,x){this.client=$;this.definitionId=O;this.id=j;this.record=x}static from($,O,j){return new CO($,O,j.id,j)}get value(){return this.record.value}get color(){return this.record.color??void 0}get displayOrder(){return this.record.display_order}get createdAt(){return this.record.created_at}get updatedAt(){return this.record.updated_at}async update($){return this.record=G(await this.client.properties.updatePropertyOption({path:{definition_id:this.definitionId,option_id:this.id},body:$})),this}async delete(){G(await this.client.properties.deletePropertyOption({path:{definition_id:this.definitionId,option_id:this.id}}))}}class SO{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new B$(()=>this.fetch(),j)}async fetch(){return G(await this.client.properties.getPropertyDefinition({path:{definition_id:this.id}}))}static async create($,O){let j=G(await $.properties.createPropertyDefinition({body:{display_name:O.displayName,scope:O.scope,data_type:O.dataType}}));return new SO($,j.id,j)}static byId($,O){return new SO($,O)}static fromRecord($,O){return new SO($,O.id,O)}get displayName(){return this.detail.get().then(($)=>$.display_name)}get dataType(){return this.detail.get().then(($)=>$.data_type)}get owner(){return this.detail.get().then(($)=>$.owner)}get isSystem(){return this.detail.get().then(($)=>$.is_system)}get isMultiSelect(){return this.detail.get().then(($)=>$.is_multi_select)}get createdAt(){return this.detail.get().then(($)=>$.created_at)}get updatedAt(){return this.detail.get().then(($)=>$.updated_at)}async delete(){return G(await this.client.properties.deletePropertyDefinition({path:{definition_id:this.id}}))}async options(){return G(await this.client.properties.getPropertyOptions({path:{definition_id:this.id}})).map((O)=>CO.from(this.client,this.id,O))}async addOption($){let O=G(await this.client.properties.addPropertyOption({path:{definition_id:this.id},body:$}));return CO.from(this.client,this.id,O)}async updateOption($,O){let j=G(await this.client.properties.updatePropertyOption({path:{definition_id:this.id,option_id:$.id},body:O}));return CO.from(this.client,this.id,j)}async deleteOption($){return G(await this.client.properties.deletePropertyOption({path:{definition_id:this.id,option_id:$.id}}))}}class R0{client;constructor($){this.client=$}async list($){return G(await this.client.properties.listProperties({query:{scope:$?.scope??"all",...$?.forEntityType!==void 0?{for_entity_type:$.forEntityType}:{}}})).map((j)=>{let x="definition"in j?j.definition:j;return SO.fromRecord(this.client,x)})}create($){return SO.create(this.client,$)}definition($){return SO.byId(this.client,$)}async bulkEntityProperties($){return G(await this.client.properties.getBulkEntityProperties({body:$}))}async updateEntityPropertyOptions($,O){return G(await this.client.properties.bulkUpdateEntitiesPropertyOptions({body:{entities:$.map((x)=>x.propertyReference()),property_id:O.property.id,...O.add?{add_option_ids:O.add.map((x)=>x.id)}:{},...O.remove?{remove_option_ids:O.remove.map((x)=>x.id)}:{}}})).results}async addEntityPropertyOption($){return G(await this.client.properties.addEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async removeEntityPropertyOption($){return G(await this.client.properties.removeEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async tags(){return G(await this.client.properties.listTags({}))}}function D0($){return c($).with({type:"cron"},(O)=>O).with({type:"events"},(O)=>({type:"events",filters:O.filters.map(({entities:j,...x})=>({...x,ids:j?.map((S)=>S.entity.id)}))})).exhaustive()}function L7($){return c($).with({type:"multiple"},(O)=>({type:"multiple",triggers:O.triggers.map(D0)})).with({type:"cron"},D0).with({type:"events"},D0).exhaustive()}class ZO extends P{static byId($,O){return new ZO($,O)}static from($,O){if(!O.id)throw Error("Routine response has no id");return new ZO($,O.id,O)}async fetch(){return G(await this.client.scheduledAction.getScheduledAction({path:{id:this.id}}))}name=this.field("name");trigger=this.field("trigger");enabled=this.field("enabled");runVisibility=this.field("run_visibility");nextRunAt=this.field("next_run_at");revision=this.field("configuration_revision");owner=this.mappedField("owner",($)=>M.byId(this.client,$));async update($){await this.mutate((O)=>O.scheduledAction.updateScheduledAction({path:{id:this.id},body:C0($)}))}async setEnabled($){await this.mutate((O)=>O.scheduledAction.setScheduledActionEnabled({path:{id:this.id},body:{enabled:$}}))}async execute(){let $=G(await this.client.scheduledAction.executeScheduledActionNow({path:{id:this.id}}));if($.resource)return c($.resource).with({type:"agent"},(O)=>i.byId(this.client,O.id)).with({type:"chat"},(O)=>K$.byId(this.client,O.id)).exhaustive();return $.chat_id?K$.byId(this.client,$.chat_id):void 0}async history(){return G(await this.client.scheduledAction.listScheduledActionHistory({path:{id:this.id}})).map(($)=>new _0(this,$))}async delete(){await this.mutate(($)=>$.scheduledAction.deleteScheduledAction({path:{id:this.id}}))}}class _0{routine;record;constructor($,O){this.routine=$;this.record=O}get id(){return this.record.id??void 0}toJSON(){return{routine:this.routine.id,...this.record}}}function C0($){let O={prompt:$.prompt,user_prompt:$.userPrompt,model:$.model,agent:$.agent?{bot_id:$.agent.id}:void 0};return{kind:"Agent",name:$.name,enabled:$.enabled,run_visibility:$.runVisibility,trigger:L7($.trigger),task:{...O}}}class M0{client;constructor($){this.client=$}byId($){return ZO.byId(this.client,$)}async create($){return ZO.from(this.client,G(await this.client.scheduledAction.createScheduledAction({body:{...C0($),enabled:$.enabled??!0}})))}async list($){return G(await this.client.scheduledAction.listScheduledActions({query:{include_events:$?.includeEvents}})).map((O)=>ZO.from(this.client,O))}}class P0{client;constructor($){this.client=$}byId($){return _$.byId(this.client,$)}create($){return _$.create(this.client,$)}forPullRequest($){return _$.forPullRequest(this.client,$)}search($,O){return _$.search(this.client,$,O)}}class A0{client;constructor($){this.client=$}byId($){return S$.byId(this.client,$)}current(){return S$.current(this.client)}list(){return S$.list(this.client)}}class F0{client;constructor($){this.client=$}async get($){return G(await this.client.unfurl.getUnfurl({query:{url:$}}))}async bulk($){return G(await this.client.unfurl.getUnfurlBulk({body:{url_list:$}}))}}class E0{client;constructor($){this.client=$}byId($){return M.byId(this.client,$)}me(){return M.me(this.client)}async search($){let O=$.trim().toLocaleLowerCase();if(!O)throw Error("A person search needs a name or email.");let j=await this.client.contacts.getContacts();if(j.response?.status===404)return[];let{contacts:x}=G(j),S=[...new Set(x)],K=[];for(let Z=0;Z<S.length;Z+=100){let X=S.slice(Z,Z+100),{names:Y}=G(await this.client.auth.getUserNamesWithEmail({body:{user_ids:X}})),L=new Map(Y.map((Q)=>[Q.id,Q]));for(let Q of X){let J=L.get(Q)??{id:Q};if(`${[J.first_name,J.last_name].filter(Boolean).join(" ")} ${Q}`.toLocaleLowerCase().includes(O))K.push(M.fromName(this.client,J))}}return K}}class XO extends P{signingSecret;constructor($,O,j,x){super($,O,j);this.signingSecret=x}async fetch(){return G(await this.client.storage.getWebhook({path:{webhook_id:this.id}}))}static async create($,O){let j=G(await $.storage.createWebhook({body:{endpoint_url:O.url,namespace:O.namespace,name:O.name,filters:O.filters,scope:O.scope??"user",...O.headers!==void 0?{headers:O.headers}:{}}}));return new XO($,j.id,j,j.signing_secret)}static byId($,O){return new XO($,O)}static fromRecord($,O){return new XO($,O.id,O)}name=this.field("name");namespace=this.field("namespace");endpointUrl=this.field("endpoint_url");status=this.field("status");isValid=this.field("is_valid");filters=this.field("filters");createdAt=this.field("created_at");workspaceId=this.field("workspace_id");createdBy=this.mappedField("created_by_user_id",($)=>M.byId(this.client,$));async scope(){let $=await this.detail.get();return $.workspace_id===$.created_by_user_id?"user":"team"}async update($){await this.mutate((O)=>O.storage.patchWebhook({path:{webhook_id:this.id},body:$}))}async rename($){await this.update({name:$})}async setUrl($){await this.update({endpoint_url:$})}async setFilters($){await this.update({filters:$})}async pause(){await this.update({status:"paused"})}async resume(){await this.update({status:"active"})}async delete(){await this.mutate(($)=>$.storage.deleteWebhook({path:{webhook_id:this.id}}))}async validate(){return this.mutate(($)=>$.storage.validateWebhook({path:{webhook_id:this.id}}))}}class w0{client;constructor($){this.client=$}create($){return XO.create(this.client,$)}byId($){return XO.byId(this.client,$)}async list(){let{webhooks:$}=G(await this.client.storage.listWebhooks());return $.map((O)=>XO.fromRecord(this.client,O))}}class MO extends P{static byId($,O){return new MO($,O)}static from($,O){return new MO($,O.id,O)}async fetch(){let{account:$}=G(await this.client.storage.linkedAccount());if($?.id!==this.id)throw new E("WhatsApp account is not available");return $}state=this.field("state");identity=this.field("identity_jid");owner=this.mappedField("user_id",($)=>M.byId(this.client,$));async refresh(){return this.detail.clear(),await this.detail.get(),this}}class C$ extends P{group;constructor($,O,j,x){super($,j,x);this.group=O}static byId($,O,j){return new C$($,O,j)}static from($,O,j){return new C$($,O,j.id,j)}async fetch(){for await(let $ of this.group.messages({limit:100}))if($.id===this.id)return $.detail.get();throw new E("WhatsApp message is not available")}body=this.field("body");sender=this.field("sender");sentAt=this.field("sent_at");editedAt=this.field("edited_at");deleted=this.field("deleted");reactions=this.field("reactions");deliveryState=this.field("delivery_state");kind=this.field("kind");forwarded=this.field("forwarded");viewOnce=this.field("view_once");mentions=this.field("mentions");rich=this.field("rich");replyTo=this.mappedField("reply_to",($)=>$?C$.byId(this.client,this.group,$):void 0);attachments=this.mappedField("attachments",($)=>$.map((O)=>({ordinal:O.ordinal,state:O.state,fileName:O.file_name,mime:O.mime,size:O.size,width:O.width??void 0,height:O.height??void 0,durationSeconds:O.duration_seconds??void 0,presentation:O.presentation??void 0,document:O.document_id?w.byId(this.client,O.document_id):void 0})))}class KO{group;id;record;constructor($,O,j){this.group=$;this.id=O;this.record=j}static byId($,O){return new KO($,O)}static from($,O){return new KO($,O.jid,O)}get displayName(){return this.record?.displayName??void 0}get mentionToken(){return this.id.split("@")[0]??this.id}get admin(){return this.record?.admin}toJSON(){return{id:this.id,group:this.group.id,displayName:this.displayName,admin:this.admin}}}class YO{id;group;filename;kind;constructor($,O,j,x){this.id=$;this.group=O;this.filename=j;this.kind=x}static byId($,O){return new YO(O,$)}static from($,O){return new YO(O.upload_id,$,O.filename,O.kind)}toJSON(){return{id:this.id,group:this.group.id,filename:this.filename,kind:this.kind}}}class GO extends P{group;constructor($,O,j,x){super($,j,x);this.group=O}static byId($,O,j){return new GO($,O,j)}static from($,O,j){return new GO($,O,j.id,j)}async fetch(){let O=G(await this.client.storage.linkedDelivery({path:{group_id:this.group.id},body:[this.id]})).find((j)=>j.id===this.id);if(!O)throw new E("WhatsApp send is not available");return O}state=this.field("state");errorCode=this.field("error_code");createdAt=this.field("created_at");message=this.mappedField("message_id",($)=>$?C$.byId(this.client,this.group,$):void 0);async request(){let{payload:$}=await this.detail.get(),O=$.message,j=c(O).returnType().with({type:"media"},(x)=>({type:"media",upload:YO.byId(this.group,x.upload_id),caption:x.caption??void 0})).with({type:"mutation"},(x)=>({type:"mutation",message:C$.byId(this.client,this.group,x.message_id),operation:x.operation,text:x.text??void 0})).with({type:"text"},(x)=>({type:"text",text:x.text,mentions:(x.mentions??[]).map((S)=>KO.byId(this.group,S))})).exhaustive();return{idempotencyKey:$.idempotency_key,message:j,replyTo:$.reply_to?C$.byId(this.client,this.group,$.reply_to):void 0}}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class v$ extends z${entityType="whatsapp_group";static byId($,O){return new v$($,O)}async fetch(){return G(await this.client.storage.whatsappGroup({path:{group_id:this.id}}))}name=this.field("name");kind=this.field("kind");canSend=this.field("can_send");sendReason=this.field("send_reason");sendingIdentity=this.field("sending_identity");unreadCount=this.field("unread_count");backfill=this.field("backfill");limits=this.field("limits");roster=this.field("roster");participants=this.mappedField("roster",($)=>($?.participants??[]).map((O)=>KO.from(this,O)));disappearingSeconds=this.field("disappearing_seconds");community=this.mappedField("community",($)=>$?q0(this.client,$):void 0);owner=this.mappedField("user_id",($)=>M.byId(this.client,$));async*messages($={}){yield*u(async(O)=>{let j=G(await this.client.storage.whatsappGroupMessages({path:{group_id:this.id},query:{before:O,limit:$.limit}}));return{items:j.messages.map((x)=>C$.from(this.client,this,x)),nextCursor:j.next_cursor}})}async markRead($){this.assertGroup($.group),await this.mutate((O)=>O.storage.whatsappGroupRead({path:{group_id:this.id},body:{message_id:$.id}}))}async permissions(){return G(await this.client.storage.whatsappGroupPermissions({path:{group_id:this.id}}))}async updatePermissions($){await this.mutate((O)=>O.storage.whatsappGroupUpdatePermissions({path:{group_id:this.id},body:$}))}async detach(){await this.mutate(($)=>$.storage.linkedDetach({path:{group_id:this.id}}))}async upload($){let O=G(await this.client.storage.linkedUpload({path:{group_id:this.id},body:{file:$}}));return YO.from(this,O)}async reply($,O){if(O.replyTo)this.assertGroup(O.replyTo.group);let j=c($).returnType().with({type:"text"},(S)=>{let K=S.mentions??[];for(let Z of K)this.assertGroup(Z.group);return{type:"text",text:S.text,mentions:K.map((Z)=>Z.id)}}).with({type:"media"},(S)=>{return this.assertGroup(S.upload.group),{type:"media",upload_id:S.upload.id,caption:S.caption}}).with({type:"mutation"},(S)=>{return this.assertGroup(S.message.group),{type:"mutation",message_id:S.message.id,operation:S.operation,text:S.text}}).exhaustive(),x=await this.mutate((S)=>S.storage.linkedReply({path:{group_id:this.id},body:{idempotency_key:O.idempotencyKey,message:j,reply_to:O.replyTo?.id}}));return GO.from(this.client,this,x)}async sends(){return G(await this.client.storage.whatsappGroupSends({path:{group_id:this.id}})).map(($)=>GO.from(this.client,this,$))}async delivery($){for(let O of $)this.assertGroup(O.group);return G(await this.client.storage.linkedDelivery({path:{group_id:this.id},body:$.map((O)=>O.id)})).map((O)=>GO.from(this.client,this,O))}async messageAttachments($){for(let O of $)this.assertGroup(O.group);return G(await this.client.storage.linkedMessageAttachments({path:{group_id:this.id},body:$.map((O)=>O.id)})).map((O)=>({message:C$.byId(this.client,this,O.message_id),attachments:O.linked_attachments.map((j)=>({ordinal:j.ordinal,state:j.state,fileName:j.file_name,mime:j.mime,size:j.size,document:j.document_id?w.byId(this.client,j.document_id):void 0}))}))}async refresh(){return this.detail.clear(),await this.detail.get(),this}assertGroup($){if($.id!==this.id)throw Error("WhatsApp reference belongs to another group")}}function q0($,O){return{chat:IO.byId($,O.id),name:O.name,announcements:O.announcements}}class IO extends P{static byId($,O){return new IO($,O)}static from($,O){return new IO($,O.jid,O)}async fetch(){let{chats:$}=G(await this.client.storage.linkedChats()),O=$.find((j)=>j.jid===this.id);if(!O)throw new E("WhatsApp chat is not available");return O}kind=this.field("kind");name=this.field("name");lastActivityAt=this.field("lastActivityAt");archived=this.field("archived");pinned=this.field("pinned");canAdd=this.field("canAdd");cannotAddReason=this.field("cannotAddReason");community=this.mappedField("community",($)=>$?q0(this.client,$):void 0);group=this.mappedField("group",($)=>$?v$.byId(this.client,$.id):void 0);shared=this.mappedField("shared",($)=>$?v$.byId(this.client,$.id):void 0);async adopt(){let $=await this.mutate((O)=>O.storage.linkedAdopt({body:{group_jid:this.id}}));return v$.byId(this.client,$.group_id)}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class f0{client;constructor($){this.client=$}async account(){let{account:$}=G(await this.client.storage.linkedAccount());return $?MO.from(this.client,$):void 0}async groups(){return G(await this.client.storage.whatsappGroups()).map(($)=>v$.byId(this.client,$.id))}async chats(){return G(await this.client.storage.linkedChats()).chats.map(($)=>IO.from(this.client,$))}byId($){return v$.byId(this.client,$)}}function b0($){if("properties"in $.data)return $.data.properties;if($.tag==="calendarEvent")return $.data.extra.properties;return[]}function n1($,O,j){let x=[];for(let S of b0(O)){if(S.definition.data_type!=="TAG"||S.value?.type!=="SelectOption")continue;for(let K of S.value.value){let Z=j.get(K);if(Z&&!x.some((X)=>X.label===Z.label&&X.scope===Z.scope))x.push(Z)}}switch(O.tag){case"document":return{type:"document",id:O.data.id,entity:w.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name,fileType:O.data.fileType,subType:O.data.subType?.type};case"chat":return{type:"ai_chat",id:O.data.id,entity:K$.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name};case"project":return{type:"project",id:O.data.id,entity:n.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name};case"emailThread":return{type:"email",id:O.data.id,entity:R$.byId($,O.data.id),snapshot:O,tags:x,subject:O.data.name,snippet:O.data.snippet,senderName:O.data.senderName,senderEmail:O.data.senderEmail,inboxVisible:O.data.inboxVisible,isRead:O.data.isRead,isDraft:O.data.isDraft};case"channel":return{type:"channel",id:O.data.channel.id,entity:b.byId($,O.data.channel.id),snapshot:O,tags:x,name:O.data.channel.name};case"channelThread":return{type:"channel_thread",id:O.data.id,entity:new h$($,O.data.channel_id,O.data.id),snapshot:O,tags:x,channelId:O.data.channel_id};case"call":return{type:"call",id:O.data.callId,entity:Q$.byId($,O.data.callId),snapshot:O,tags:x,createdBy:O.data.createdBy};case"calendarEvent":return{type:"calendar_event",id:O.data.id,entity:$$.byId($,O.data.id),snapshot:O,tags:x,title:O.data.title,status:O.data.status,location:O.data.location,conferenceUrl:O.data.conferenceUrl,conferenceProvider:O.data.conferenceProvider,time:O.data.time};case"foreignEntity":return{type:"foreign_entity",id:O.data.id,entity:jO.byId($,O.data.id),snapshot:O,tags:x,foreignEntityId:O.data.foreignEntityId,foreignEntitySource:O.data.foreignEntitySource,metadata:O.data.metadata};default:throw Error(`Unexpected workspace entity type: ${O.tag}`)}}var s1="00000000-0000-0000-0000-000000000000",k0={document:["df","id"],project:["pf","pid"],ai_chat:["cf","cid"],email:["ef","ThreadId"],channel:["chanf","ChannelId"],channel_thread:["cthf","ThreadId"],call:["callf","CallId"],calendar_event:["calf","id"],foreign_entity:["fef","id"]},Fj=($)=>$.replace(/[A-Z]/g,(O)=>O.toLowerCase()),t1=($,O)=>$==null?O:{"&":[$,O]};function g0($,O){if(!$||typeof $!=="object"||Array.isArray($))throw Error(`Invalid workspace ${O}: expected a filter expression.`);let j=Object.entries($),x=j[0];if(j.length!==1||x===void 0)throw Error(`Invalid workspace ${O}: use exactly one of l, &, |, !.`);let[S,K]=x;if(S==="l")return;if(S==="!"){g0(K,`${O}.!`);return}if(S!=="&"&&S!=="|")throw Error(`Invalid workspace ${O}: use l, &, | or !.`);if(!Array.isArray(K)||K.length!==2)throw Error(`Invalid workspace ${O}.${S}: expected exactly two expressions. Use {l: {...}} for a single condition; nest binary operators for three or more.`);K.forEach((Z,X)=>{g0(Z,`${O}.${S}[${X}]`)})}class Ej{client;tagSets;constructor($){this.client=$}sets(){return this.tagSets??=this.client.properties.listTags({}).then(G),this.tagSets}async tagMap(){let $=new Map;for(let O of await this.sets())for(let j of O.options)if(j.value.type==="string")$.set(j.id,{label:j.value.value,scope:O.scope==="user"?"personal":"team"});return $}async body($){for(let[S,K,Z]of[["sortBy",$.sortBy,["recently_viewed","recently_updated","recently_created"]],["emailPreset",$.emailPreset,["signal"]],["tagsMatch",$.tagsMatch,["any","all"]]])if(K!==void 0&&!Z.includes(K))throw Error(`Invalid workspace ${S}: ${K}`);if($.includeTypes!==void 0&&(!Array.isArray($.includeTypes)||$.includeTypes.some((S)=>!Object.hasOwn(k0,S))))throw Error(`Invalid workspace includeTypes. Supported values: ${Object.keys(k0).join(", ")}. Tasks use document with df: {l: {dst: 'task'}}.`);for(let S of["df","pf","cf","ef","chanf","cthf","callf","fef","calf","propf"])if($[S]!=null)g0($[S],S);if($.tags?.some((S)=>S.scope!==void 0&&S.scope!=="personal"&&S.scope!=="team"))throw Error("Invalid workspace tag scope");if($.limit!==void 0&&!Number.isFinite($.limit))throw Error("Workspace limit must be finite");let O={df:$.df,pf:$.pf,cf:$.cf,ef:$.ef,chanf:$.chanf,cthf:$.cthf,callf:$.callf,fef:$.fef,calf:$.calf,propf:$.propf,ccf:{l:{id:s1}},favorites_only:$.favoritesOnly,expand:!0,limit:Math.max(1,Math.min(500,Math.trunc($.limit??50))),sort_method:$.sortBy==="recently_viewed"?"viewed_at":$.sortBy==="recently_created"?"created_at":"updated_at",sort_direction:"desc",emailView:$.emailView??"inbox"};if($.emailPreset==="signal")O.ef={"&":[{l:{Importance:!0}},{l:{Shared:"exclude"}}]};let j=$.inbox?.trim();if(j){let{links:S}=G(await this.client.email.listLinks()),K=S.filter((X)=>Fj(X.email_address)===Fj(j)),Z=K[0];if(!Z)throw Error(`No connected inbox matches "${j}". Connected inboxes: ${S.map((X)=>X.email_address).join(", ")}.`);if(K.length>1)throw Error(`Multiple connected inboxes match "${j}"; cannot pick one.`);O.ef=t1(O.ef,{l:{Owner:Z.id}})}let x=$.includeTypes??($.emailPreset==="signal"?["email"]:void 0);if(x?.length){for(let[S,[K,Z]]of Object.entries(k0))if(!x.includes(S))O[K]={l:{[Z]:s1}}}if($.tags?.length){let S=(await this.sets()).flatMap((Y)=>{let L=Y.definition;if(!L)return[];return Y.options.flatMap((Q)=>Q.value.type==="string"?[{id:Q.id,definitionId:L.id,label:Q.value.value,scope:Y.scope==="user"?"personal":"team"}]:[])}),K=new Map;for(let Y of $.tags){let L=S.filter((Q)=>Fj(Q.label)===Fj(Y.label.trim())&&(!Y.scope||Q.scope===Y.scope));if(!L.length)throw Error(`Unknown tag "${Y.label}". Available tags: ${S.map((Q)=>`${Q.label} (${Q.scope})`).join(", ")}.`);if($.tagsMatch==="all"&&L.length>1)throw Error(`Tag "${Y.label}" is ambiguous; specify personal or team scope.`);for(let Q of L)K.set(Q.id,Q)}let X=[...K.values()].map((Y)=>({l:{pd:Y.definitionId,v:{so:Y.id}}})).reduce((Y,L)=>Y===void 0?L:{[$.tagsMatch==="all"?"&":"|"]:[Y,L]},void 0);O.propf=t1(O.propf,X)}return O}}class y0{client;constructor($){this.client=$}async page($={}){let O=new Ej(this.client);return this.fetch(O,await O.body($),$.cursor)}async*list($={}){let O=new Ej(this.client),j=await O.body($);yield*u((x)=>this.fetch(O,j,x))}async fetch($,O,j){let x=G(await this.client.storage.postItemsSoupAst({body:O,query:j?{cursor:j}:void 0})),K=x.items.some((Z)=>b0(Z).some((X)=>X.definition.data_type==="TAG"))?await $.tagMap():new Map;return{items:x.items.map((Z)=>n1(this.client,Z,K)),nextCursor:x.next_cursor,hasMore:x.next_cursor!=null}}}function e1({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((W)=>setTimeout(W,V)));return{stream:async function*(){let V=K??3000,W=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;W++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:l,value:r}=await H.read();if(l)break;U+=r,U=U.replace(/\r\n?/g,`
+async function uO($,O,j){if(!Number.isInteger(O)||O<1)throw RangeError(`concurrency limit must be a positive integer, got ${O}`);let x=Array($.length),S=0,K=async()=>{while(S<$.length){let X=S;S+=1,x[X]=await j($[X])}},Z=Array.from({length:Math.min(O,$.length)},K);return await Promise.all(Z),x}class B${loader;value;inflight;constructor($,O){this.loader=$;this.value=O}get(){if(this.value!==void 0)return Promise.resolve(this.value);return this.inflight??=this.loader().then(($)=>{return this.value=$,$}),this.inflight}peek(){return this.value}clear(){this.value=void 0,this.inflight=void 0}}async function*u($){let O;do{let j=await $(O),x=j.nextCursor??void 0;if(O!==void 0&&x!==void 0&&JSON.stringify(x)===JSON.stringify(O))throw Error("Pagination cursor did not advance");yield*j.items,O=x}while(O!==void 0)}class f extends Error{constructor($){super($);this.name="MacroError"}}class QO extends f{status;data;constructor($,O){super(`Macro API error ${$}`);this.status=$;this.data=O;this.name="MacroApiError"}}class E extends f{constructor($){super($);this.name="MacroNotFoundError"}}function G($){if($.error!==void 0)throw new QO($.response?.status??0,$.error);return $.data}class P{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new B$(()=>this.fetch(),j)}field($){return async()=>(await this.detail.get())[$]??void 0}mappedField($,O){return async()=>O((await this.detail.get())[$]??void 0)}toJSON(){let $=this.detail.peek();return $===void 0?{id:this.id}:{id:this.id,detail:$}}async mutate($){let O=G(await $(this.client));return this.detail.clear(),O}}class z$ extends P{async permission(){return G(await this.client.storage.getEntityPermission({path:{entity_type:this.entityType,entity_id:this.id}}))}async favorite(){return G(await this.client.storage.addFavorite({body:{entityId:this.id,entityType:this.entityType}})),this}async unfavorite(){return G(await this.client.storage.removeFavoriteByEntity({path:{entity_type:this.entityType,entity_id:this.id}})),this}}class X$ extends z${propertyReference(){return{entity_type:this.propertyEntityType,entity_id:this.id}}async properties($){let{properties:O}=G(await this.client.properties.getEntityProperties({path:{entity_type:this.propertyEntityType,entity_id:this.id},query:$?.includeMetadata!==void 0?{include_metadata:$.includeMetadata}:void 0}));return O}async setProperty($,O){G(await this.client.properties.setEntityProperty({path:{...this.propertyReference(),property_id:$.id},body:{value:O??null}}))}async updatePropertyOptions($){return G(await this.client.properties.bulkUpdateEntityPropertyOptions({path:this.propertyReference(),body:{properties:$.map((O)=>({property_id:O.property.id,...O.add?{add_option_ids:O.add.map((j)=>j.id)}:{},...O.remove?{remove_option_ids:O.remove.map((j)=>j.id)}:{}}))}}))}async deleteProperty($){G(await this.client.properties.deleteEntityProperty({path:{entity_property_id:$.property.id}}))}}var f6={"<":"\\u003c",">":"\\u003e","&":"\\u0026"};function a$($,O){let j=JSON.stringify(O).replace(/[<>&]/g,(x)=>f6[x]??x);return`<${$}>${j}</${$}>`}function b6($){return typeof $==="object"&&$!==null&&typeof $.toMention==="function"}var k6={toMention:()=>({tag:a$("m-group-mention",{groupAlias:"here"}),mention:{entity_type:"group",entity_id:"here"}})};function g6($,...O){let j="",x=[];for(let[S,K]of $.entries()){j+=K;let Z=O[S];if(Z===void 0)continue;if(b6(Z)){let X=Z.toMention();j+=X.tag,x.push(X.mention)}else j+=String(Z)}return{content:j,mentions:y6(x)}}function y6($){let O=new Set;return $.filter((j)=>{let x=`${j.entity_type}:${j.entity_id}`;if(O.has(x))return!1;return O.add(x),!0})}function O$($){return typeof $==="string"?{content:$,mentions:[]}:$}class W$ extends P{static byId($,O){return new W$($,O)}static from($,O){return new W$($,O.id,O)}async fetch(){let $=G(await this.client.storage.listHarnesses()).find((O)=>O.id===this.id);if(!$)throw new E(`Harness ${this.id} is unavailable`);return $}name=this.field("name");connected=this.field("connected");kind=this.field("kind");async delete(){await this.mutate(($)=>$.storage.deleteHarness({path:{harness_id:this.id}}))}}class I$ extends P{static byId($,O){return new I$($,O)}static from($,O){return new I$($,O.bot.id,O)}async fetch(){let $=G(await this.client.storage.listAgents()).find((O)=>O.bot.id===this.id);if(!$)throw new E(`Agent ${this.id} is unavailable`);return $}name=this.mappedField("bot",($)=>$.name);instructions=this.field("instructions");defaultModel=this.field("default_model");channels=this.mappedField("channel_ids",($)=>$.map((O)=>b.byId(this.client,O)));host=this.mappedField("harness_id",($)=>$?W$.byId(this.client,$):void 0);async update($){await this.mutate((O)=>O.storage.updateAgent({path:{agent_id:this.id},body:yx($)}))}}function yx($){let{channels:O,team:j,host:x,autoAcceptPermissions:S,avatarUrl:K,channelScope:Z,defaultModel:X,isCoding:Y,...L}=$;return{...L,channel_ids:O?.map((Q)=>Q.id),team_id:j?.id,harness_id:x?.id,auto_accept_permissions:S,avatar_url:K,channel_scope:Z,default_model:X,is_coding:Y}}async function Wj($,O,j){let{channelId:x,thread:S}=v6(O);if(await h6($)){let{id:Z}=G(await $.storage.entityMessageCreate({path:{parent_type:"channel",parent_id:x},body:{content:j.content,mentions:j.mentions,attachments:[],thread_id:S?.rootId??null,nonce:crypto.randomUUID()}}));return Z}if(S)throw new f("a user-owned bot can only post via the channel webhook endpoint, which "+"does not support threads — use a team-owned bot, or requestedAs(user), "+"to reply in a thread");let{message_id:K}=G(await $.storage.postChannelBotWebhook({path:{channel_id:x},body:{content:j.content},headers:{"x-macro-bot-scope":"user"}}));return K}function v6($){return"rootId"in $?{channelId:$.channelId,thread:$}:{channelId:$.id}}async function h6($){if($.authConfig.type!=="bot"||$.hasActingUser())return!0;let{owner:O}=await $.selfBot();return O?.type==="team"}class h${client;channelId;rootId;constructor($,O,j){this.client=$;this.channelId=O;this.rootId=j}toJSON(){return{channelId:this.channelId,rootId:this.rootId}}channel(){return b.byId(this.client,this.channelId)}root(){return e.byId(this.client,this.channelId,this.rootId)}async replies(){let{replies:$}=G(await this.client.storage.entityMessageGetThread({path:{parent_type:"channel",parent_id:this.channelId,id:this.rootId}}));return $.map((O)=>e.from(this.client,this.channelId,O))}async reply($){let O=await Wj(this.client,this,O$($));return e.byId(this.client,this.channelId,O)}}class e extends z${channelId;mentions;entityType="channel_message";constructor($,O,j,x=[],S){super($,j,S);this.channelId=O;this.mentions=x}get path(){return{parent_type:"channel",parent_id:this.channelId,id:this.id}}async fetch(){return G(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j,x=[]){return new e($,O,j,x)}static from($,O,j){return new e($,O,j.id,j.mentions,j)}content=this.field("content");createdAt=this.field("created_at");editedAt=this.field("edited_at");updatedAt=this.field("updated_at");async author(){return M.byId(this.client,(await this.detail.get()).sender_id)}channel(){return b.byId(this.client,this.channelId)}thread(){return new h$(this.client,this.channelId,this.id)}async react($){return await this.mutate((O)=>O.storage.entityMessageReact({path:this.path,body:{add:!0,emoji:$}})),this}async unreact($){return await this.mutate((O)=>O.storage.entityMessageReact({path:this.path,body:{add:!1,emoji:$}})),this}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}async reply($){return this.thread().reply($)}}class Lj{client;channel;record;constructor($,O,j){this.client=$;this.channel=O;this.record=j}agent(){return I$.byId(this.client,this.record.botId)}sessions(){return this.record.sessions.map(($)=>({session:i.byId(this.client,$.sessionId),isCurrent:$.isCurrent,createdAt:$.createdAt}))}turns(){return this.record.turns.map(($)=>new vx(this.client,this,$))}async startFresh($){G(await this.client.agentHarness.startFreshAgentConversation({path:{channel_id:this.channel.id,bot_id:this.record.botId},body:{sessionId:$.id}}))}toJSON(){return{channelId:this.channel.id,agentId:this.record.botId}}}class vx{client;conversation;record;constructor($,O,j){this.client=$;this.conversation=O;this.record=j}source(){return e.byId(this.client,this.conversation.channel.id,this.record.sourceMessageId)}session(){return i.byId(this.client,this.record.sessionId)}async retry($){G(await this.client.agentHarness.retryAgentConversationTurn({path:{channel_id:this.conversation.channel.id,bot_id:this.conversation.agent().id,source:this.record.sourceMessageId},body:{actionId:$}}))}toJSON(){return{channelId:this.conversation.channel.id,sourceMessageId:this.record.sourceMessageId}}}class L$ extends P{parent;toJSON(){return{...super.toJSON(),parentType:this.parent.type,parentId:this.parent.entity.id}}constructor($,O,j){super($,j);this.parent=O}static byId($,O,j){return new L$($,O,j)}get path(){return{parent_type:this.parent.type,parent_id:this.parent.entity.id,id:this.id}}async fetch(){return G(await this.client.storage.entityMessageGetThread({path:this.path})).state}resolved=this.field("resolved");async update($){let O={resolved:$.resolved,detach_anchor:$.detachAnchor,nonce:$.nonce};await this.mutate((j)=>j.storage.entityMessagePatchThread({path:this.path,body:O}))}async delete($){await this.mutate((O)=>O.storage.entityMessageDeleteThread({path:this.path,query:{nonce:$}}))}}async function w$($,O,j,x){for(let K of[...x?.messages??[],...x?.around?[x.around]:[]]){let Z="channelId"in K?{type:"channel",id:K.channelId}:("documentId"in K)?{type:"document",id:K.documentId}:("callId"in K)?{type:"call",id:K.callId}:K.parent;if(Z.type!==O.type||Z.id!==O.entity.id)throw Error("Timeline message belongs to another resource")}let S=G(await $.storage.messageTimelineEntries({path:{parent_type:O.type,parent_id:O.entity.id},query:{selection:x?JSON.stringify({cursor:x.cursor,around:x.around?.id,ids:x.messages?.map((K)=>K.id),activity_after:x.activityAfter,activity_before:x.activityBefore,anchored:x.anchored,direction:x.direction,include_deleted_threads:x.includeDeletedThreads,limit:x.limit}):void 0}}));return{entries:S.entries.map((K)=>{if(K.type==="activity")return{type:"activity",activity:{...K.activity,actor:M.byId($,K.activity.actor_id)}};return{type:"message",message:j(K.message)}}),nextCursor:S.next_cursor??void 0,previousCursor:S.previous_cursor??void 0}}var m6=50;function x$($){let{filters:O,type:j,make:x,includeCrm:S}=$;return(K,Z,X)=>{let Y=X?.searchOn??"name_content",L=X?.pageSize??m6;return u(async(Q)=>{let{results:J,next_cursor:I}=G(await K.search.unifiedSearch({body:{query:Z,match_type:"partial",search_on:Y,...O?{filters:O}:{},...S?{include_crm:!0}:{}},query:{page_size:L,...Q?{cursor:Q}:{}}}));return{items:J.filter((B)=>B.type===j).map((B)=>x(K,B)),nextCursor:I}})}}class JO{client;channel;record;constructor($,O,j){this.client=$;this.channel=O;this.record=j}get id(){return this.record.id}user(){return M.byId(this.client,this.record.user_id)}createdAt(){return this.record.created_at}async recordInteraction($){return new JO(this.client,this.channel,G(await this.client.storage.postActivity({body:{activity_type:$,channel_id:this.channel.id}})))}toJSON(){return this.record}}class b extends X${async recordActivity($){return new JO(this.client,this,G(await this.client.storage.postActivity({body:{activity_type:$,channel_id:this.id}})))}async setPicture($){await this.mutate((O)=>O.storage.setChannelPicture({path:{channel_id:this.id},body:{profile_picture_id:$?.id??null}}))}messageThreadById($){return L$.byId(this.client,{type:"channel",entity:this},$)}timelinePage($){return w$(this.client,{type:"channel",entity:this},(O)=>e.from(this.client,this.id,O),$)}async agentConversations(){return G(await this.client.agentHarness.listAgentConversations({path:{channel_id:this.id}})).conversations.map(($)=>new Lj(this.client,this,$))}entityType="channel";propertyEntityType="CHANNEL";async fetch(){return G(await this.client.storage.getChannel({path:{channel_id:this.id}}))}static byId($,O){return new b($,O)}static async dm($,O){let{channel_id:j}=G(await $.storage.getOrCreateDm({body:{recipient_id:O.id}}));return new b($,j)}static async private($,O){let{channel_id:j}=G(await $.storage.getOrCreatePrivate({body:{recipients:O.map((x)=>x.id)}}));return new b($,j)}static async create($,O){let{id:j}=G(await $.storage.createChannel({body:{channel_type:O.type,name:O.name??null,participants:(O.participants??[]).map((x)=>x.id),team_id:O.team?.id??null}}));return new b($,j)}name=this.field("channel_name");type=this.field("channel_type");async send($,O){let j=await Wj(this.client,O?.thread??this,O$($));return e.byId(this.client,this.id,j)}messages($){return this.timeline({limit:$?.pageSize})}messagesAfter($,O){return this.timeline({activity_after:$ instanceof Date?$.toISOString():$,limit:O?.pageSize})}timeline($){return u(async(O)=>{let j=G(await this.client.storage.messageTimeline({path:{parent_type:"channel",parent_id:this.id},query:{selection:JSON.stringify({...$,cursor:O})}}));return{items:j.items.map((x)=>e.from(this.client,this.id,x)),nextCursor:j.next_cursor}})}message($){return e.byId(this.client,this.id,$)}async rename($){await this.mutate((O)=>O.storage.patchChannel({path:{channel_id:this.id},body:{channel_name:$}}))}async delete(){await this.mutate(($)=>$.storage.deleteChannel({path:{channel_id:this.id}}))}async join(){await this.mutate(($)=>$.storage.joinChannel({path:{channel_id:this.id}}))}async joinCode(){let{join_code:$}=G(await this.client.storage.getChannelJoinLink({path:{channel_id:this.id}}));return $}async leave(){await this.mutate(($)=>$.storage.leaveChannel({path:{channel_id:this.id}}))}async participants(){return G(await this.client.storage.getChannelParticipants({path:{channel_id:this.id}}))}async addParticipants($){await this.mutate((O)=>O.storage.addParticipants({path:{channel_id:this.id},body:{participants:$.map((j)=>j.id)}}))}async removeParticipants($){await this.mutate((O)=>O.storage.removeParticipants({path:{channel_id:this.id},body:{participants:$.map((j)=>j.id)}}))}async typing($,O){G(await this.client.storage.entityMessageTyping({path:{parent_type:"channel",parent_id:this.id},body:{active:$==="start",thread_id:O?.thread?.rootId??null}}))}attachments($){return u(async(O)=>{let j=G(await this.client.storage.getChannelAttachments({path:{channel_id:this.id},query:{...$?.pageSize?{limit:$.pageSize}:{},...$?.type?{attachment_type:$.type}:{},...O?{cursor:O}:{}}}));return{items:j.items,nextCursor:j.next_cursor}})}webUrl(){return`${this.client.webAppUrl}/app/channel/${this.id}`}static search=x$({type:"channel",make:($,O)=>new b($,O.channel_id)})}class M extends X${entityType="user";propertyEntityType="USER";async fetch(){let{names:$}=G(await this.client.auth.getUserNamesWithEmail({body:{user_ids:[this.id]}})),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`user ${this.id} not found`);return O}static byId($,O){return new M($,O)}static fromName($,O){return new M($,O.id,O)}static async me($){let{user_id:O}=G(await $.auth.getUserInfo());return new M($,O)}async name(){let $=await this.detail.get();return[$.first_name,$.last_name].filter(Boolean).join(" ")||void 0}email(){let $=this.id.startsWith("macro|")?this.id.slice(6):void 0;return $?.includes("@")?$:void 0}dm(){return b.dm(this.client,this)}toMention(){return{tag:a$("m-user-mention",{userId:this.id}),mention:{entity_type:"user",entity_id:this.id}}}}class o{client;entityType;entity;constructor($,O,j){this.client=$;this.entityType=O;this.entity=j}get path(){return{entity_type:this.entityType,entity_id:this.entity.id}}async state($){let O=G(await this.client.storage.accessRequestsState({path:this.path,query:{offset:$}}));return{accessLevel:O.accessLevel??void 0,canReview:O.canReview,owner:O.owner?M.byId(this.client,O.owner):void 0,pendingCount:O.pendingCount,supportedLevels:O.supportedLevels,nextOffset:O.nextOffset??void 0,mine:O.mine?TO.from(this.client,this,O.mine):void 0,requests:O.requests.map((j)=>TO.from(this.client,this,j))}}async submit($,O){return TO.from(this.client,this,G(await this.client.storage.accessRequestsSubmit({path:this.path,body:{requestedLevel:$,revision:O}})))}async cancel($){G(await this.client.storage.accessRequestsCancel({path:this.path,query:{revision:$}}))}async direct(){return G(await this.client.storage.accessRequestsDirect({path:this.path})).map(($)=>({user:M.byId(this.client,$.userId),accessLevel:$.accessLevel}))}async grant($,O){G(await this.client.storage.accessRequestsSetDirect({path:{...this.path,user_id:$.id},body:{accessLevel:O}}))}async remove($){G(await this.client.storage.accessRequestsRemoveDirect({path:{...this.path,user_id:$.id}}))}async resolve($,O){let j=$.access.toJSON();if(j.entity_type!==this.entityType||j.entity_id!==this.entity.id)throw Error("Access request belongs to another entity");return G(await this.client.storage.accessRequestsResolve({path:{...this.path,request_id:$.id},body:O}))}toJSON(){return this.path}}class TO extends P{access;resolvedRecord;constructor($,O,j){super($,j.id,j);this.access=O}static from($,O,j){return new TO($,O,j)}async fetch(){if(this.resolvedRecord)return this.resolvedRecord;let $;do{let O=await this.access.state($),j=[O.mine,...O.requests].find((x)=>x?.id===this.id);if(j)return j.detail.get();$=O.nextOffset}while($!==void 0);throw new E(`Access request ${this.id} is unavailable`)}revision=this.field("revision");status=this.field("status");requestedLevel=this.field("requestedLevel");requester=this.mappedField("requesterId",($)=>M.byId(this.client,$));async resolve($){this.resolvedRecord=await this.access.resolve(this,{revision:await this.revision(),grantedLevel:$}),this.detail.clear()}}function i$($){return{...$,channelSharePermissions:$.channelSharePermissions===void 0||$.channelSharePermissions===null?$.channelSharePermissions:$.channelSharePermissions.map((O)=>({channelId:O.channel.id,accessLevel:O.accessLevel,operation:O.operation}))}}class N$ extends P{parent;constructor($,O,j,x){super($,j,x);this.parent=O}static byId($,O,j){return new N$($,O,j)}static fromRecord($,O,j){return new N$($,O,j.id,j)}static async create($,O,j){return N$.createForSession($,O.session(),j,O)}static async createForSession($,O,j,x){let S=G(await $.agentHarness.createSessionReview({path:{session_id:O.id},body:{...j,executionId:x?.id??null}}));return N$.fromRecord($,O,S)}static async list($,O){return G(await $.agentHarness.listExecutionReviews({path:{session_id:O.session().id,execution_id:O.id}})).map((x)=>N$.fromRecord($,O.session(),x))}async fetch(){return G(await this.client.agentHarness.getSessionReview({path:{session_id:this.parent.id,review_id:this.id}}))}title=this.field("title");kind=this.field("kind");session(){return this.parent}async reference(){return{kind:await this.kind(),id:this.id}}async items(){return(await this.detail.get()).items.map(($)=>new hx($,{edit:(O)=>this.decide({action:"edit",item:$.id,draft:O}),submit:()=>this.decide({action:"submit",items:[$.id]}),dismiss:()=>this.decide({action:"dismiss",items:[$.id]})}))}async refresh(){return this.detail.clear(),await this.detail.get(),this}async submitAll(){await this.decide({action:"submit",items:[]})}async dismissAll(){await this.decide({action:"dismiss",items:[]})}async decide($){let O=(await this.detail.get()).revision;await this.mutate((j)=>j.agentHarness.decideSessionReview({path:{session_id:this.parent.id,review_id:this.id},body:{...$,revision:O}}))}}class hx{snapshot;actions;constructor($,O){this.snapshot=$;this.actions=O}get id(){return this.snapshot.id}get status(){return this.snapshot.status}get draft(){return this.snapshot.draft}get result(){return this.snapshot.result}async edit($){await this.actions.edit($)}async submit(){await this.actions.submit()}async dismiss(){await this.actions.dismiss()}}class dO extends P{parent;constructor($,O,j){super($,O);this.parent=j}static byId($,O,j){return new dO($,j,O)}async fetch(){return G(await this.client.agentHarness.getCodeExecution({path:{session_id:this.parent.id,execution_id:this.id}}))}reviews={create:($)=>N$.create(this.client,this,$),list:()=>N$.list(this.client,this)};session(){return this.parent}status=this.field("status");source=this.field("source");calls=this.field("calls");error=this.field("error");async result(){return(await this.detail.get()).result}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class Nj{client;sessionId;dto;constructor($,O,j){this.client=$;this.sessionId=O;this.dto=j}static from($,O,j){return new Nj($,O,j)}get actionId(){return this.dto.actionId}get kind(){return this.dto.kind}get prompt(){return this.dto.prompt??void 0}get attachments(){return this.dto.attachments??[]}get actorUserId(){return this.dto.actorUserId??void 0}get createdAt(){return this.dto.createdAt}async edit($){return G(await this.client.agentHarness.editQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId},body:{prompt:$}})),this.dto={...this.dto,prompt:$},this}async steer(){G(await this.client.agentHarness.steerQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}async remove(){G(await this.client.agentHarness.removeQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}}class lO{client;session;id;constructor($,O,j){this.client=$;this.session=O;this.id=j}static byId($,O,j){return new lO($,O,j)}async answer($){return G(await this.client.agentHarness.answerAgentSessionToolApproval({path:{session_id:this.session.id,approval_id:this.id},body:{answer:$}}))}toJSON(){return{id:this.id,sessionId:this.session.id}}}class i extends P{access=new o(this.client,"agent_session",this);toolApprovalById($){return lO.byId(this.client,this,$)}async sharePermissions(){return G(await this.client.agentHarness.getAgentSessionPermissions({path:{session_id:this.id}}))}async updateSharePermissions($){return this.mutate((O)=>O.agentHarness.updateAgentSessionPermissions({path:{session_id:this.id},body:i$($)}))}static byId($,O){return new i($,O)}static async createManaged($,O){let{session:j}=G(await $.agentHarness.createAgentSession({body:{prompt:O?.prompt,instructions:O?.instructions,model:O?.model,repoUrl:O?.repoUrl,repoBranch:O?.repoBranch}}));return new i($,j.id,j)}static async repositories($){let{repositories:O}=G(await $.agentHarness.listAgentRepositories());return O.map((j)=>({url:j.url,defaultBranch:j.defaultBranch??void 0}))}static async repositoryBranches($,O){let{branches:j}=G(await $.agentHarness.listAgentRepositoryBranches({query:{repoUrl:O}}));return j}async fetch(){return G(await this.client.agentHarness.getAgentSession({path:{session_id:this.id}}))}name=this.field("name");isArchived=this.field("isArchived");model=this.field("model");harness=this.field("harness");repoUrl=this.field("repoUrl");workspace=this.field("workspace");instructions=this.field("instructions");status=this.field("status");sandboxSize=this.field("sandboxSize");createdAt=this.field("createdAt");modifiedAt=this.field("modifiedAt");static async forPullRequest($,O){let{sessionIds:j}=G(await $.agentHarness.agentSessionsForPullRequest({body:{url:O}}));return j.map((x)=>i.byId($,x))}async pullRequests(){let{pullRequests:$}=G(await this.client.agentHarness.listAgentSessionPullRequests({path:{session_id:this.id}}));return $.map((O)=>({githubKey:O.githubKey,url:O.url,source:O.source,linkedBy:O.linkedBy?M.byId(this.client,O.linkedBy):void 0,createdAt:O.createdAt}))}async linkPullRequest($){G(await this.client.agentHarness.linkAgentSessionPullRequest({path:{session_id:this.id},body:{url:$}}))}async unlinkPullRequest($){G(await this.client.agentHarness.unlinkAgentSessionPullRequest({path:{session_id:this.id},query:{url:$}}))}async rename($){await this.mutate((O)=>O.agentHarness.renameAgentSession({path:{session_id:this.id},body:{name:$}}))}async archive(){await this.setArchived(!0)}async unarchive(){await this.setArchived(!1)}async setArchived($){await this.mutate((O)=>O.agentHarness.setAgentSessionArchived({path:{session_id:this.id},body:{isArchived:$}}))}async setSandboxSize($){let{size:O}=await this.mutate((j)=>j.agentHarness.putAgentSessionSandboxSize({path:{session_id:this.id},body:{size:$}}));return O}static async defaultSandboxSize($){return G(await $.agentHarness.getAgentSandboxSize()).size}static async setDefaultSandboxSize($,O){return G(await $.agentHarness.putAgentSandboxSize({body:{size:O}})).size}static async codingPreferences($){return G(await $.agentHarness.getAgentCodingPreferences())}static async setCodingPreferences($,O){return G(await $.agentHarness.putAgentCodingPreferences({body:O}))}async control($){return this.mutate((O)=>O.agentHarness.controlAgentSession({path:{session_id:this.id},body:$}))}prompt($,O){return this.control({type:"prompt",prompt:$,...O&&O.length>0?{attachments:O}:{}})}async queue(){let{entries:$}=G(await this.client.agentHarness.getAgentSessionQueue({path:{session_id:this.id}}));return $.map((O)=>Nj.from(this.client,this.id,O))}async changes(){return G(await this.client.agentHarness.getAgentSessionChanges({path:{session_id:this.id}}))}async changesPatch(){return G(await this.client.agentHarness.getAgentSessionChangesPatch({path:{session_id:this.id}})).patch}async refreshChanges(){return this.mutate(($)=>$.agentHarness.refreshAgentSessionChanges({path:{session_id:this.id}}))}async foldedLog(){let{bot:$,messages:O}=G(await this.client.agentHarness.getAgentSessionFoldedLog({path:{session_id:this.id}}));return{bot:$,messages:O}}async log(){return G(await this.client.agentHarness.getAgentSessionLog({path:{session_id:this.id}}))}reviews={create:($)=>N$.createForSession(this.client,this,$),byId:($)=>N$.byId(this.client,this,$)};codeExecutions={byId:($)=>dO.byId(this.client,this,$)};async delete(){await this.mutate(($)=>$.agentHarness.deleteAgentSession({path:{session_id:this.id}}))}}class mx{client;constructor($){this.client=$}byId($){return i.byId(this.client,$)}createManaged($){return i.createManaged(this.client,$)}repositories(){return i.repositories(this.client)}repositoryBranches($){return i.repositoryBranches(this.client,$)}forPullRequest($){return i.forPullRequest(this.client,$)}defaultSandboxSize(){return i.defaultSandboxSize(this.client)}setDefaultSandboxSize($){return i.setDefaultSandboxSize(this.client,$)}codingPreferences(){return i.codingPreferences(this.client)}setCodingPreferences($){return i.setCodingPreferences(this.client,$)}}class cx{client;constructor($){this.client=$}byId($){return I$.byId(this.client,$)}async list(){return G(await this.client.storage.listAgents()).map(($)=>I$.from(this.client,$))}async create($){return I$.from(this.client,G(await this.client.storage.createAgent({body:yx($)})))}}class ux{client;async usage($={}){let{users:O,...j}=$;return G(await this.client.cognition.getUsageHandler({body:{...j,include_users:O?.map((x)=>x.id)}}))}constructor($){this.client=$}async structuredCompletion($){return G(await this.client.cognition.structuredCompletion({body:$}))}async decide($){return G(await this.client.cognition.decisions({body:$}))}}class n$ extends P{static byId($,O){return new n$($,O)}static from($,O){return new n$($,O.id,{id:O.id,name:O.name,createdAt:O.createdAt})}async fetch(){let $=G(await this.client.storage.listUserApiKeys()).keys.find((O)=>O.id===this.id);if(!$)throw new E(`API key ${this.id} is unavailable`);return $}name=this.field("name");createdAt=this.field("createdAt");async delete(){await this.mutate(($)=>$.storage.deleteUserApiKey({path:{id:this.id}}))}}class dx{client;constructor($){this.client=$}byId($){return n$.byId(this.client,$)}async list(){return G(await this.client.storage.listUserApiKeys()).keys.map(($)=>n$.from(this.client,$))}async create($){let O=G(await this.client.storage.createUserApiKey({body:{name:$}}));return{key:n$.from(this.client,O),secret:O.key}}async tokenForEmail($){return G(await this.client.auth.macroApiToken({query:{email:$}}))}}class rO{client;constructor($){this.client=$}async me(){if(this.client.authConfig.type!=="bot")throw new f("bots.me() requires bot auth — a user API key has no bot identity");return G(await this.client.storage.getSelfBot())}async channels(){if(this.client.authConfig.type!=="bot")throw new f("bots.channels() requires bot auth — a user API key has no bot identity");let $=await this.me();return G(await this.client.storage.listBotChannels({path:{bot_id:$.id}}))}async myPrincipalId(){if(this.client.authConfig.type!=="bot")throw new f("bots.myPrincipalId() requires bot auth — a user API key has no bot identity");return this.client.myPrincipalId()}}class S$ extends P{async fetch(){let O=G(await this.client.auth.getUserTeams()).find((j)=>j.id===this.id);if(!O)throw new E(`team ${this.id} not found`);return O}static byId($,O){return new S$($,O)}static async current($){let O=G(await $.auth.getTeam());if(!O)throw new E("caller has no current team");return new S$($,O.team.id,O.team)}static async list($){return G(await $.auth.getUserTeams()).map((j)=>new S$($,j.id,j))}name=this.field("name");slug=this.field("slug");defaultLinkShare=this.field("default_link_share");owner=this.mappedField("owner_id",($)=>M.byId(this.client,$));async members(){let $=G(await this.client.auth.getTeam());if(!$||$.team.id!==this.id)throw new f("members are only available for the current team (see Team.current)");return $.members.map((O)=>({user:M.byId(this.client,O.user_id),role:O.role}))}}class T$ extends P{async fetch(){let{links:$}=G(await this.client.email.listLinks()),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`email link ${this.id} not found`);return O}static byId($,O){return new T$($,O)}static async list($){let{links:O}=G(await $.email.listLinks());return O.map((j)=>new T$($,j.id,j))}emailAddress=this.field("email_address");provider=this.field("provider");isPrimary=this.field("is_primary");isSyncActive=this.field("is_sync_active");syncStatus=this.field("sync_status");needsReauth=this.field("needs_reauth");photoUrl=this.field("photo_url");async settingsOperations(){return G(await this.client.email.mailboxSettingsOperations({headers:{"X-Email-Link-Id":this.id}}))}}class m$ extends P{async setContributesToAvailability($){await this.mutate((O)=>O.calendar.setAvailabilityCalendar({path:{calendar_id:this.id},body:{contributesToAvailability:$}}))}async fetch(){let{calendars:$}=G(await this.client.calendar.listCalendars()),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`calendar ${this.id} not found`);return O}static byId($,O){return new m$($,O)}static async list($){let{calendars:O}=G(await $.calendar.listCalendars());return O.map((j)=>new m$($,j.id,j))}name=this.field("name");emailAddress=this.field("emailAddress");isPrimary=this.field("isPrimary");isWritable=this.field("isWritable");isSubscription=this.field("isSubscription");color=this.field("color");syncError=this.field("syncError");emailLink=this.mappedField("emailLinkId",($)=>T$.byId(this.client,$))}class pO{client;id;constructor($,O){this.client=$;this.id=O}async status(){return G(await this.client.calendar.calendarReplacementStatus({path:{operation_id:this.id}}))}async confirm(){return G(await this.client.calendar.confirmCalendarReplacement({path:{operation_id:this.id}}))}async discard(){G(await this.client.calendar.discardCalendarReplacement({path:{operation_id:this.id}}))}}class $$ extends P{async notes($){return this.requireOwnOccurrence($),G(await this.client.calendar.eventNotes({path:{event_id:this.id},query:{occurrenceKey:$.occurrenceKey}})).map((j)=>q$.fromRecord(this.client,this,$,j))}async linkNote($,O,j={}){return this.requireOwnOccurrence(O),G(await this.client.calendar.linkEventNote({path:{event_id:this.id,document_id:$.id},query:{occurrenceKey:O.occurrenceKey},body:{teamId:j.team?.id??null}})),q$.forDocument(this.client,this,O,$)}requireOwnOccurrence($){if($.eventId!==this.id)throw new f("The occurrence belongs to a different event")}async fetch(){throw new f(`calendar event ${this.id} has no fetch-by-id endpoint; read the record returned by calendar.createEvent / event.update / event.rsvp instead`)}static byId($,O){return new $$($,O)}static fromRecord($,O){return new $$($,O.id,O)}title=this.field("title");description=this.field("description");location=this.field("location");time=this.field("time");status=this.field("status");attendees=this.field("attendees");transparency=this.field("transparency");isReadOnly=this.field("isReadOnly");recurrenceLines=this.field("recurrenceLines");guestPolicy=this.field("guestPolicy");viewerCan=this.field("viewerCan");calendar=this.mappedField("calendarId",($)=>$?m$.byId(this.client,$):void 0);record(){return this.detail.get()}async update($){let O=await this.mutate((j)=>j.calendar.updateCalendarEvent({path:{event_id:this.id},body:c6($)}));return $$.fromRecord(this.client,O)}async delete($={}){await this.mutate((O)=>O.calendar.deleteCalendarEvent({path:{event_id:this.id},query:{calendarId:$.calendar?.id,scope:$.scope,recurrenceId:$.recurrenceId,inbox:$.inbox}}))}async prepareReplacement($){let O=G(await this.client.calendar.prepareCalendarReplacement({path:{event_id:this.id},body:{removeConference:$.removeConference,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}));return new pO(this.client,O.operationId)}async providerUrl($={}){return G(await this.client.calendar.calendarEventProviderUrl({path:{event_id:this.id},query:{recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}})).url??void 0}async inviteGuests($){let O=await this.mutate((j)=>j.calendar.inviteCalendarEventGuests({path:{event_id:this.id},body:{guests:$.guests,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id,inbox:$.inbox}}));return $$.fromRecord(this.client,O)}async addToCalendar($={}){let O=await this.mutate((j)=>j.calendar.copyCalendarEvent({path:{event_id:this.id},body:{calendarId:$.calendar?.id}}));return $$.fromRecord(this.client,O)}async ics(){return G(await this.client.storage.eventIcs({path:{event_id:this.id}}))}async rsvp($){let O=await this.mutate((j)=>j.calendar.rsvpCalendarEvent({path:{event_id:this.id},body:{response:$.response,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}));return $$.fromRecord(this.client,O)}}function c6($){return{title:$.title,description:$.description,location:$.location,time:$.time,attendees:$.attendees,recurrenceLines:$.recurrenceLines,visibility:$.visibility,transparency:$.transparency,reminders:$.reminders,conference:$.conference,outOfOffice:$.outOfOffice,guestPolicy:$.guestPolicy,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id,inbox:$.inbox}}class q$ extends P{event;occurrence;fromDocument;constructor($,O,j,x,S,K=!1){super($,x.id,S);this.event=O;this.occurrence=j;this.fromDocument=K;if(j.eventId!==O.id)throw new f("Choose an occurrence belonging to this event")}static fromDocumentLink($,O,j){return new q$($,$$.byId($,j.eventId),j,O,{documentId:O.id,name:j.documentName,team:j.team,canManage:!0},!0)}static forDocument($,O,j,x){return new q$($,O,j,x)}static fromRecord($,O,j,x){return new q$($,O,j,w.byId($,x.documentId),x)}async fetch(){if(this.fromDocument){let x=G(await this.client.calendar.documentNoteLinks({path:{document_id:this.id}})).find((S)=>S.eventId===this.event.id&&S.occurrenceKey===this.occurrence.occurrenceKey);if(!x)throw new E("This meeting link has been removed");return{documentId:this.id,name:x.documentName,team:x.team,canManage:!0}}let O=G(await this.client.calendar.eventNotes({path:{event_id:this.event.id},query:{occurrenceKey:this.occurrence.occurrenceKey}})).find((j)=>j.documentId===this.id);if(!O)throw new E("This document is no longer linked to the meeting");return O}document=this.mappedField("documentId",($)=>w.byId(this.client,$));name=this.field("name");team=this.mappedField("team",($)=>$?S$.byId(this.client,$.id):void 0);canManage=this.field("canManage");async setTeam($){await this.mutate((O)=>O.calendar.linkEventNote({path:{event_id:this.event.id,document_id:this.id},query:{occurrenceKey:this.occurrence.occurrenceKey},body:{teamId:$?.id??null}}))}async unlink(){await this.mutate(($)=>$.calendar.unlinkEventNote({path:{event_id:this.event.id,document_id:this.id},query:{occurrenceKey:this.occurrence.occurrenceKey}}))}}class n extends X${async sharePermissions(){return G(await this.client.storage.getProjectPermissionsV2({path:{id:this.id}}))}async accessLevel(){return G(await this.client.storage.getProjectUserAccessLevel({path:{id:this.id}}))}access=new o(this.client,"project",this);entityType="project";propertyEntityType="PROJECT";async fetch(){let{data:$}=G(await this.client.storage.getProjectHandler({path:{id:this.id}}));return $.projectMetadata}static byId($,O){return new n($,O)}static async create($,O){let{data:j}=G(await $.storage.createProjectHandler({body:{name:O.name,projectParentId:O.parent?.id??null}}));return new n($,j.id,j)}name=this.field("name");parent=this.mappedField("parentId",($)=>$?n.byId(this.client,$):void 0);createdAt=this.field("createdAt");async items(){let{data:$}=G(await this.client.storage.getProjectContentHandler({path:{id:this.id}}));return $.map((O)=>O.item)}async rename($){await this.mutate((O)=>O.storage.editProjectV2({path:{id:this.id},body:{name:$}}))}async delete($){await this.mutate((O)=>$?.permanent?O.storage.permanentlyDeleteProject({path:{id:this.id}}):O.storage.deleteProjectHandler({path:{id:this.id}}))}async restore(){await this.mutate(($)=>$.storage.revertDeleteProject({path:{id:this.id}}))}static search=x$({filters:{project_filters:{}},type:"project",make:($,O)=>new n($,O.id)})}class VO extends P{document;toJSON(){return{...super.toJSON(),documentId:this.document.id}}constructor($,O,j,x){super($,j,x);this.document=O}static byId($,O,j){return new VO($,O,j)}static from($,O,j){return new VO($,O,j.uuid,j)}async fetch(){let $=G(await this.client.storage.getDocumentAnchors({path:{document_id:this.document.id}})).data.find((O)=>O.uuid===this.id);if(!$)throw new E(`Annotation ${this.id} is unavailable`);return $}kind=this.field("anchorType");page=this.field("page");async edit($){if(await this.kind()!=="placeable")throw Error("Only placeable comment annotations can be edited");await this.mutate((O)=>O.storage.editAnchor({body:{...$,uuid:this.id,anchorType:"free-comment",fileType:"pdf"}}))}async delete(){if(await this.kind()!=="highlight")throw Error("Only standalone highlights can be deleted with this endpoint");await this.mutate(($)=>$.storage.deleteAnchor({body:{uuid:this.id,anchorType:"highlight",fileType:"pdf"}}))}}class c$ extends P{documentId;constructor($,O,j,x){super($,j,x);this.documentId=O}get path(){return{parent_type:"document",parent_id:this.documentId,id:this.id}}async fetch(){return G(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new c$($,O,j)}static from($,O,j){return new c$($,O,j.id,j)}text=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");async threadId(){return(await this.detail.get()).thread_id??this.id}document(){return w.byId(this.client,this.documentId)}async author(){return M.byId(this.client,(await this.detail.get()).sender_id)}async reply($){return this.document().comment($,{threadId:await this.threadId()})}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}class aO{client;document;id;detail;constructor($,O,j){this.client=$;this.document=O;this.id=j;this.detail=new B$(async()=>G(await this.client.storage.getDocumentVersion({path:{document_id:O.id,document_version_id:j}})).data)}static byId($,O,j){return new aO($,O,j)}read(){return this.detail.get()}toJSON(){return{id:this.id,documentId:this.document.id}}}var u6=8;class w extends X${async meetingNotes(){return G(await this.client.calendar.documentNoteLinks({path:{document_id:this.id}})).map((O)=>({note:q$.fromDocumentLink(this.client,this,O),eventTitle:O.eventTitle}))}async anchors(){return G(await this.client.storage.getDocumentAnchors({path:{document_id:this.id}})).data.map(($)=>VO.from(this.client,this,$))}async createHighlight($){return VO.from(this.client,this,G(await this.client.storage.createAnchor({path:{document_id:this.id},body:{...$,fileType:"pdf",anchorType:"highlight"}})))}version($){return aO.byId(this.client,this,$)}async sharePermissions(){return G(await this.client.storage.getDocumentPermissionsV2({path:{document_id:this.id}})).documentPermissions}async permissionsToken(){return G(await this.client.storage.getDocumentPermissionsToken({path:{document_id:this.id}})).token}async prepareSave($){return G(await this.client.storage.presaveDocumentHandler({path:{document_id:this.id},body:{newBom:$}})).data}async save($){return(await this.mutate((O)=>O.storage.saveDocumentHandler({path:{document_id:this.id},body:$}))).data}async simpleSave(){return(await this.mutate(($)=>$.storage.simpleSave({path:{document_id:this.id}}))).data}messageThreadById($){return L$.byId(this.client,{type:"document",entity:this},$)}timelinePage($){return w$(this.client,{type:"document",entity:this},(O)=>c$.from(this.client,this.id,O),$)}access=new o(this.client,"document",this);async fetch(){let{data:$}=G(await this.client.storage.getDocument({path:{document_id:this.id}}));return $.documentMetadata}static byId($,O){return new w($,O)}static async create($,O){let{documentId:j}=G(await $.storage.createMarkdownHandler({body:{documentName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new w($,j)}static async createSnippet($,O){let{documentId:j}=G(await $.storage.createSnippetHandler({body:{snippetName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new w($,j)}static async createSkill($,O){let{documentId:j}=G(await $.storage.createSkillHandler({body:{skillName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new w($,j)}static recent($,O){let j=O?.pageSize??50;return u(async(x)=>{let S=G(await $.storage.getUserDocumentsHandler({query:{limit:j,offset:x?Number(x):0,...O?.fileType!==void 0?{file_type:O.fileType}:{}}})),K=S.data?.next_offset;return{items:(S.data?.documents??[]).map((Z)=>new w($,Z.documentId)),nextCursor:K!=null?String(K):null}})}static async recentlyDeleted($){let{data:O}=G(await $.storage.recentlyDeleted({}));return O.items.filter((j)=>j.type==="document").map((j)=>new w($,j.id))}entityType="document";propertyEntityType="DOCUMENT";name=this.field("documentName");fileType=this.field("fileType");project=this.mappedField("projectId",($)=>$?n.byId(this.client,$):void 0);owner=this.mappedField("owner",($)=>M.byId(this.client,$));branchedFrom=this.mappedField("branchedFromId",($)=>$?w.byId(this.client,$):void 0);createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");deletedAt=this.field("deletedAt");async content(){let{text:$}=G(await this.client.storage.getDocumentTextContent({path:{document_id:this.id}}));if($!==null)return $;let{presigned_url:O}=G(await this.client.storage.exportDocument({path:{document_id:this.id}})),j=await fetch(O);if(!j.ok)throw new QO(j.status,{message:"failed to download document content"});return j.text()}async rename($){await this.mutate((O)=>O.storage.editDocument({path:{document_id:this.id},body:{documentName:$}}))}async move($){await this.mutate((O)=>O.storage.editDocument({path:{document_id:this.id},body:{projectId:$?.id??""}}))}async delete($){await this.mutate((O)=>$?.permanent?O.storage.permanentlyDeleteDocument({path:{document_id:this.id}}):O.storage.deleteDocument({path:{document_id:this.id}}))}async restore(){await this.mutate(($)=>$.storage.revertDeleteDocument({path:{document_id:this.id}}))}async copy($){let{data:O}=G(await this.client.storage.copyDocument({path:{document_id:this.id},query:$.versionId!==void 0?{version_id:$.versionId}:void 0,body:{documentName:$.name}}));return new w(this.client,O.documentMetadata.documentId)}async comments(){let $={parent_type:"document",parent_id:this.id},O=u(async(x)=>{let S=G(await this.client.storage.messageTimeline({path:$,query:{selection:JSON.stringify({limit:100,cursor:x})}}));return{items:S.items,nextCursor:S.next_cursor}}),j=[];for await(let x of O)j.push(x);return uO(j,u6,async(x)=>{let{state:S,root:K,replies:Z}=G(await this.client.storage.entityMessageGetThread({path:{...$,id:x.id}}));return{thread:S,comments:[K,...Z].map((X)=>c$.from(this.client,this.id,X))}})}async comment($,O){let j=await this.mutate((x)=>x.storage.entityMessageCreate({path:{parent_type:"document",parent_id:this.id},body:{...O$($),thread_id:O?.threadId??null}}));return c$.from(this.client,this.id,j)}async shortId(){return G(await this.client.storage.getDocumentShortId({path:{document_id:this.id}}))}async teamShare(){return G(await this.client.storage.getDocumentTeamShare({path:{document_id:this.id}}))}async setTeamShare($){await this.mutate((O)=>O.storage.setDocumentTeamShare({path:{document_id:this.id},body:{shareWithTeam:$}}))}async githubPullRequests(){let{pullRequests:$}=G(await this.client.storage.getDocumentGithubPullRequests({path:{document_id:this.id}}));return $}async branchName(){let{branchName:$}=G(await this.client.storage.getDocumentBranchName({path:{document_id:this.id}}));return $}webUrl(){return`${this.client.webAppUrl}/app/md/${this.id}`}static search=x$({filters:{document_filters:{}},type:"document",make:($,O)=>new w($,O.document_id)});toMention(){let $=this.detail.peek();return{tag:a$("m-document-mention",{documentId:this.id,documentName:$?.documentName??"",blockName:$?.fileType??"md"}),mention:{entity_type:"document",entity_id:this.id}}}}class lx{client;async noteDocuments($=""){let O=G(await this.client.calendar.noteDocuments({query:{query:$}}));return{documents:O.documents.map((j)=>({document:w.byId(this.client,j.documentId),name:j.name})),teams:O.teams.map((j)=>({team:S$.byId(this.client,j.id),name:j.name}))}}async availabilityCalendars(){return G(await this.client.calendar.getAvailabilityCalendars()).calendars.map(($)=>({calendar:m$.byId(this.client,$.calendarId),name:$.name,isPrimary:$.isPrimary,contributesToAvailability:$.contributesToAvailability}))}async teamSharing(){return G(await this.client.calendar.getTeamSharing()).sharing}async setTeamSharing($){return G(await this.client.calendar.setTeamSharing({body:{sharing:$}})).sharing}occurrences($){let O;return u(async(j)=>{let x=G(await this.client.storage.listOccurrences({query:{...$,cursor:j}}));O??=l6(this.client);let S=await O;return{items:x.items.map((K)=>({event:$$.fromRecord(this.client,K.event),occurrence:K.occurrence,inbox:K.event.calendarId?S.get(K.event.calendarId):void 0,role:r6(K.event)})),nextCursor:x.nextCursor}})}async teamPage($){let O=G(await this.client.storage.listTeamCalendar({query:$}));return{items:O.items.map(({ownerId:j,...x})=>({...x,owner:M.byId(this.client,j)})),members:O.members.map((j)=>({user:M.byId(this.client,j.userId),sharing:j.sharing,coverage:j.coverage})),nextCursor:O.nextCursor??void 0}}async teamOutOfOffice($){let O=G(await this.client.storage.listTeamOutOfOffice({query:$}));return{items:O.items.map((j)=>({event:$$.byId(this.client,j.eventId),owner:M.byId(this.client,j.ownerId),occurrenceKey:j.occurrenceKey,time:j.time,title:j.title??void 0})),hasMore:O.hasMore}}constructor($){this.client=$}calendars(){return m$.list(this.client)}calendar($){return m$.byId(this.client,$)}event($){return $$.byId(this.client,$)}replacement($){return new pO(this.client,$)}async createEvent($){let O=G(await this.client.calendar.createCalendarEvent({body:d6($)}));return $$.fromRecord(this.client,O)}}function d6($){return{title:$.title,time:$.time,description:$.description,location:$.location,attendees:$.attendees,recurrenceLines:$.recurrenceLines,visibility:$.visibility,transparency:$.transparency,reminders:$.reminders,conference:$.conference,macroCall:$.macroCall,outOfOffice:$.outOfOffice,guestPolicy:$.guestPolicy,calendarId:$.calendar?.id,emailLinkId:$.emailLink?.id}}async function l6($){let{calendars:O}=G(await $.calendar.listCalendars());return new Map(O.map((j)=>[j.id,j.emailAddress]))}function r6($){let O=$.attendees.find((j)=>j.isSelf);if($.viewerCan.organize||O?.isOrganizer)return"organizer";return O?"guest":void 0}class H$ extends P{lookupToken;constructor($,O,j){super($,O,j);this.lookupToken=j?.shareToken}static byId($,O){return new H$($,O)}static from($,O){return new H$($,O.id,O)}async fetch(){if(this.lookupToken)return G(await this.client.storage.meetingLookup({path:{token:this.lookupToken}}));let $=G(await this.client.storage.meetingList()).meetings.find((O)=>O.id===this.id);if(!$)throw new E(`Meeting ${this.id} is unavailable`);return this.lookupToken=$.shareToken,$}title=this.field("title");scheduledStart=this.field("scheduledStart");scheduledEnd=this.field("scheduledEnd");channel=this.mappedField("channelId",($)=>$?b.byId(this.client,$):void 0);call=this.mappedField("callId",($)=>$?Q$.byId(this.client,$):void 0);async update($){await this.mutate((O)=>O.storage.meetingUpdate({path:{meeting_id:this.id},body:$}))}async cancel(){await this.mutate(($)=>$.storage.meetingCancel({path:{meeting_id:this.id}}))}async invitePermissions(){return G(await this.client.storage.meetingInvitePermissions({path:{token:(await this.detail.get()).shareToken}}))}async invite($){G(await this.client.storage.meetingInvite({path:{token:(await this.detail.get()).shareToken},body:{email:$}}))}async inviteUsers($){G(await this.client.storage.meetingInviteUsers({path:{token:(await this.detail.get()).shareToken},body:{userIds:$.map((O)=>O.id)}}))}async webUrl(){return`${this.client.webAppUrl}/app/meet/join/${encodeURIComponent((await this.detail.get()).shareToken)}`}}class u$ extends P{callId;constructor($,O,j,x){super($,j,x);this.callId=O}get path(){return{parent_type:"call",parent_id:this.callId,id:this.id}}async fetch(){return G(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new u$($,O,j)}static from($,O,j){return new u$($,O,j.id,j)}content=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");call(){return Q$.byId(this.client,this.callId)}async author(){return M.byId(this.client,(await this.detail.get()).sender_id)}async reply($){let O=G(await this.client.storage.entityMessageCreate({path:{parent_type:"call",parent_id:this.callId},body:{...O$($),thread_id:this.callId}}));return u$.from(this.client,this.callId,O)}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}class Q$ extends z${messageThreadById($){return L$.byId(this.client,{type:"call",entity:this},$)}timelinePage($){return w$(this.client,{type:"call",entity:this},(O)=>u$.from(this.client,this.id,O),$)}access=new o(this.client,"call",this);async meeting(){return H$.from(this.client,G(await this.client.storage.meetingShare({path:{call_id:this.id}})))}async editTranscript($){await this.mutate((O)=>O.storage.editCallTranscript({path:{call_id:this.id},body:{assignments:$}}))}async toggleTeamShare(){return this.mutate(($)=>$.storage.toggleShareWithTeam({path:{call_id:this.id}}))}entityType="call";async fetch(){return G(await this.client.storage.getCallRecord({path:{call_id:this.id}}))}static byId($,O){return new Q$($,O)}message($){return u$.byId(this.client,this.id,$)}name=this.field("customName");channel=this.mappedField("channelId",($)=>$?b.byId(this.client,$):void 0);channelName=this.field("channelName");creator=this.mappedField("createdBy",($)=>M.byId(this.client,$));isActive=this.field("isActive");status=this.field("status");roomName=this.field("roomName");startedAt=this.field("startedAt");endedAt=this.field("endedAt");durationMs=this.field("durationMs");summary=this.field("summary");transcript=this.field("transcript");participants=this.field("participants");guests=this.field("guests");teamShareAccessLevel=this.field("teamShareAccessLevel");shareWithTeam=this.field("shareWithTeam");recordingUrl=this.field("recordingUrl");recordingPreviewUrl=this.field("recordingPreviewUrl");recordingStartedAt=this.field("recordingStartedAt");async rename($){await this.mutate((O)=>O.storage.editCallRecord({path:{call_id:this.id},body:{customName:$??""}}))}async setTeamShare($){await this.mutate((O)=>O.storage.editCallRecord({path:{call_id:this.id},body:{sharePermission:{teamShareAccessLevel:$?"view":null}}}))}async delete(){await this.mutate(($)=>$.storage.deleteCallRecord({path:{call_id:this.id}}))}static search=x$({filters:{call_filters:{}},type:"call",make:($,O)=>new Q$($,O.call_id)})}class rx{client;constructor($){this.client=$}byId($){return Q$.byId(this.client,$)}search($,O){return Q$.search(this.client,$,O)}}class px{client;constructor($){this.client=$}async list(){let{labels:$}=G(await this.client.storage.listChannelLabels());return $}async create($,O=[]){return G(await this.client.storage.createChannelLabel({body:{name:$,channelIds:O.map((j)=>j.id)}}))}async createSmartTag($,O){return G(await this.client.storage.createChannelLabel({body:{name:$,rule:O}}))}async previewSmartTag($){return G(await this.client.storage.previewSmartTag({body:$}))}async updateSmartTag($,O,j){return G(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O,rule:j}}))}async rename($,O){return G(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O}}))}async delete($){G(await this.client.storage.deleteChannelLabel({path:{label_id:$.id}}))}async setLabel($,O){G(await this.client.storage.setChannelLabel({path:{channel_id:$.id},body:{labelId:O?.id??null}}))}}class ax{client;async activity(){return G(await this.client.storage.getActivity()).map(($)=>new JO(this.client,b.byId(this.client,$.channel_id),$))}labels;constructor($){this.client=$;this.labels=new px($)}byId($){return b.byId(this.client,$)}async dm($){return b.dm(this.client,$)}async private($){return b.private(this.client,$)}async create($){return b.create(this.client,$)}async list(){let{items:$}=G(await this.client.storage.getChannels());return $.map((O)=>b.byId(this.client,O.id.toString()))}async*search($,O){if(!O?.searchOn||O.searchOn==="name"){let{items:j}=G(await this.client.storage.getChannels()),x=$.toLowerCase();for(let S of j)if(S.name?.toLowerCase().includes(x))yield b.byId(this.client,S.id.toString())}else yield*b.search(this.client,$,O)}}class iO{client;chat;id;message;constructor($,O,j,x){this.client=$;this.chat=O;this.id=j;this.message=x}static byId($,O,j,x){return new iO($,O,j,x)}async stop(){G(await this.client.cognition.stopChatStream({body:{chat_id:this.chat.id,stream_id:this.id}}))}toJSON(){return{id:this.id,chatId:this.chat.id,messageId:this.message.id}}}class nO extends P{chat;constructor($,O,j){super($,j);this.chat=O}static byId($,O,j){return new nO($,O,j)}async fetch(){let $=G(await this.client.cognition.getChat({path:{chat_id:this.chat.id}})).chat.messages.find((O)=>O.id===this.id);if(!$)throw new E(`Chat message ${this.id} is not yet available`);return $}content=this.field("content");role=this.field("role");async refresh(){this.detail.clear(),await this.detail.get()}toJSON(){return{...super.toJSON(),chatId:this.chat.id}}}class K$ extends X${async send($){let{attachments:O,additionalInstructions:j,...x}=$,S=await this.mutate((Z)=>Z.cognition.sendChatMessage({body:{...x,chat_id:this.id,additional_instructions:j,attachments:O?.map((X)=>({entity_id:X.entity.id,entity_type:X.type}))}})),K=K$.byId(this.client,S.chat_id);return iO.byId(this.client,K,S.stream_id,nO.byId(this.client,K,S.message_id))}access=new o(this.client,"chat",this);entityType="chat";propertyEntityType="CHAT";async fetch(){let{chat:$}=G(await this.client.cognition.getChat({path:{chat_id:this.id}}));return $}static byId($,O){return new K$($,O)}static async create($,O){let{id:j}=G(await $.cognition.createChat({body:{name:O?.name??null,projectId:O?.project?.id??null}}));return new K$($,j)}name=this.field("name");model=this.field("model");project=this.mappedField("projectId",($)=>$?n.byId(this.client,$):void 0);createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");messages=this.field("messages");async rename($){await this.mutate((O)=>O.cognition.patchChat({path:{chat_id:this.id},body:{name:$}}))}async delete($){await this.mutate((O)=>$?.permanent?O.cognition.permanentlyDeleteChat({path:{chat_id:this.id}}):O.cognition.deleteChat({path:{chat_id:this.id}}))}async copy(){let{id:$}=await this.mutate((O)=>O.cognition.copyChat({path:{chat_id:this.id}}));return new K$(this.client,$)}async restore(){await this.mutate(($)=>$.cognition.revertDeleteChat({path:{chat_id:this.id}}))}async history(){let{conversation:$}=G(await this.client.cognition.getChatHistoryHandler({path:{chat_id:this.id}}));return $}webUrl(){return`${this.client.webAppUrl}/app/chat/${this.id}`}static search=x$({filters:{chat_filters:{}},type:"chat",make:($,O)=>new K$($,O.chat_id)});toMention(){return{tag:a$("m-document-mention",{documentId:this.id,documentName:this.detail.peek()?.name??"",blockName:"chat",blockParams:{}}),mention:{entity_type:"chat",entity_id:this.id}}}}class ix{client;constructor($){this.client=$}byId($){return K$.byId(this.client,$)}create($){return K$.create(this.client,$)}search($,O){return K$.search(this.client,$,O)}}var p6=8;class P$ extends P{parent;constructor($,O,j,x){super($,j,x);this.parent=O}get path(){return{parent_type:this.parent.type,parent_id:this.parent.id,id:this.id}}async fetch(){return G(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new P$($,O,j)}static from($,O,j){return new P$($,O,j.id,j)}text=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");deletedAt=this.field("deleted_at");async threadId(){return(await this.detail.get()).thread_id??this.id}async author(){return M.byId(this.client,(await this.detail.get()).sender_id)}async reply($){return sO(this.client,this.parent,$,{threadId:await this.threadId()})}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}async function Uj($,O){let j={parent_type:O.type,parent_id:O.id},x=u(async(K)=>{let Z=G(await $.storage.messageTimeline({path:j,query:{selection:JSON.stringify({limit:100,cursor:K})}}));return{items:Z.items,nextCursor:Z.next_cursor}}),S=[];for await(let K of x)S.push(K);return uO(S,p6,async(K)=>{let{state:Z,root:X,replies:Y}=G(await $.storage.entityMessageGetThread({path:{...j,id:K.id}}));return{thread:Z,comments:[X,...Y].map((L)=>P$.from($,O,L))}})}async function sO($,O,j,x){let S=G(await $.storage.entityMessageCreate({path:{parent_type:O.type,parent_id:O.id},body:{...O$(j),thread_id:x?.threadId??null}}));return P$.from($,O,S)}class f$ extends z${messageThreadById($){return L$.byId(this.client,{type:"crm_contact",entity:this},$)}timelinePage($){return w$(this.client,{type:"crm_contact",entity:this},(O)=>P$.from(this.client,{type:"crm_contact",id:this.id},O),$)}entityType="crm_contact";async fetch(){return G(await this.client.storage.getContact({path:{contact_id:this.id}}))}static byId($,O){return new f$($,O)}static from($,O){return new f$($,O.id,O)}name=this.field("name");email=this.field("email");company=this.mappedField("companyId",($)=>b$.byId(this.client,$));hidden=this.field("hidden");createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");firstInteraction=this.field("firstInteraction");lastInteraction=this.field("lastInteraction");async hide(){await this.setHidden(!0)}async unhide(){await this.setHidden(!1)}async setHidden($){await this.mutate((O)=>O.storage.setContactHidden({path:{contact_id:this.id},body:{hidden:$}}))}async rename($){await this.mutate((O)=>O.storage.setCrmContactName({path:{contact_id:this.id},body:{name:$}}))}get commentParent(){return{type:"crm_contact",id:this.id}}async comments(){return Uj(this.client,this.commentParent)}async comment($,O){return sO(this.client,this.commentParent,$,O)}commentById($){return P$.byId(this.client,this.commentParent,$)}}class b$ extends X${messageThreadById($){return L$.byId(this.client,{type:"crm_company",entity:this},$)}timelinePage($){return w$(this.client,{type:"crm_company",entity:this},(O)=>P$.from(this.client,{type:"crm_company",id:this.id},O),$)}entityType="crm_company";propertyEntityType="COMPANY";async fetch(){return G(await this.client.storage.getCompany({path:{company_id:this.id}}))}static byId($,O){return new b$($,O)}static from($,O){return new b$($,O.id,O)}name=this.field("name");description=this.field("description");hidden=this.field("hidden");emailSync=this.field("emailSync");team=this.mappedField("teamId",($)=>S$.byId(this.client,$));createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");async domain(){let{domains:$}=await this.detail.get();return $[0]?.domain}async domains(){let{domains:$}=await this.detail.get();return $.map((O)=>O.domain)}async contacts(){return G(await this.client.storage.listCompanyContacts({path:{company_id:this.id}})).map((O)=>f$.from(this.client,O))}static search=x$({filters:{crm_company_filters:{}},type:"company",includeCrm:!0,make:($,O)=>new b$($,O.id)});async hide(){await this.setHidden(!0)}async unhide(){await this.setHidden(!1)}async setHidden($){await this.mutate((O)=>O.storage.setCompanyHidden({path:{company_id:this.id},body:{hidden:$}}))}async setEmailSync($){await this.mutate((O)=>O.storage.setEmailSync({path:{company_id:this.id},body:{email_sync:$}}))}async rename($){await this.mutate((O)=>O.storage.setCrmCompanyName({path:{company_id:this.id},body:{name:$}}))}async createContact($){let O=await this.mutate((j)=>j.storage.createCrmContact({path:{company_id:this.id},body:$}));return f$.from(this.client,O)}get commentParent(){return{type:"crm_company",id:this.id}}async comments(){return Uj(this.client,this.commentParent)}async comment($,O){return sO(this.client,this.commentParent,$,O)}commentById($){return P$.byId(this.client,this.commentParent,$)}}class s$ extends P{tableDetail=new B$(async()=>G(await this.client.storage.getCrmPipelineTable({path:{id:this.id}})));static byId($,O){return new s$($,O)}static from($,O){return new s$($,O.id,O)}async fetch(){return G(await this.client.storage.getCrmPipeline({path:{id:this.id}}))}name=this.field("name");recordType=this.field("recordType");accessLevel=this.field("grant");sharing=this.field("sharing");owner=this.mappedField("userId",($)=>M.byId(this.client,$));team=this.mappedField("teamId",($)=>S$.byId(this.client,$));async rename($){await this.mutate((O)=>O.storage.renameCrmPipeline({path:{id:this.id},body:{name:$}}))}async setSharing($){if($===void 0)throw Error("Sharing is required");await this.mutate((O)=>O.storage.shareCrmPipeline({path:{id:this.id},body:{sharing:$}}))}async setTrashed($){await this.mutate((O)=>O.storage.trashCrmPipeline({path:{id:this.id},body:{trashed:$}}))}async sharePermissions(){return G(await this.client.storage.getCrmPipelinePermissions({path:{id:this.id}}))}async updateSharePermissions($){return this.mutate((O)=>O.storage.updateCrmPipelinePermissions({path:{id:this.id},body:i$($)}))}async table(){return zj.from(this.client,this,await this.tableRecord())}tableRecord(){return this.tableDetail.get()}rows(){return u(async($)=>{let O=G(await this.client.storage.getCrmPipelineRows({path:{id:this.id},query:{after:$}}));return{items:O.rows.map((j)=>BO.from(this.client,this,j)),nextCursor:O.next}})}queryRows($={}){if($.rows?.some((O)=>O.pipeline.id!==this.id))throw Error("Rows belong to another pipeline");return u(async(O)=>{let j=G(await this.client.storage.queryCrmPipelineRows({path:{id:this.id},body:{after:O,query:$.query,rowIds:$.rows?.map((x)=>x.id)}}));return{items:j.rows.map((x)=>BO.from(this.client,this,x)),nextCursor:j.next}})}async applyOps($,O){if(O?.baseVersions?.some((S)=>S.table.pipeline.id!==this.id))throw Error("Table belongs to another pipeline");let j={ops:$,baseVersions:O?.baseVersions?Object.fromEntries(O.baseVersions.map((S)=>[S.table.id,S.version])):void 0},x=await this.mutate((S)=>S.storage.applyCrmPipelineOps({path:{id:this.id},body:j}));return this.tableDetail.clear(),x}}class zj extends P{pipeline;toJSON(){return{...super.toJSON(),pipelineId:this.pipeline.id}}constructor($,O,j){super($,j.table.id,j);this.pipeline=O}static from($,O,j){return new zj($,O,j)}fetch(){return this.pipeline.tableRecord()}async columns(){return(await this.pipeline.tableRecord()).columns.map(($)=>Ij.from(this.client,this,$))}async version(){return(await this.pipeline.tableRecord()).table.version}rowById($){return BO.byId(this.client,this.pipeline,$)}rows(){return this.pipeline.rows()}}class BO extends P{pipeline;toJSON(){return{...super.toJSON(),pipelineId:this.pipeline.id}}constructor($,O,j,x){super($,j,x);this.pipeline=O}static byId($,O,j){return new BO($,O,j)}static from($,O,j){return new BO($,O,j.rowId,j)}async fetch(){for await(let $ of this.pipeline.queryRows({rows:[this]}))if($.id===this.id)return $.detail.get();throw new E(`Pipeline row ${this.id} is unavailable`)}cells=this.field("cells");async refresh(){this.detail.clear(),await this.detail.get()}}class Ij extends P{table;toJSON(){return{...super.toJSON(),pipelineId:this.table.pipeline.id,tableId:this.table.id}}constructor($,O,j){super($,j.column.id,j);this.table=O}static from($,O,j){return new Ij($,O,j)}async fetch(){let $=(await this.table.pipeline.tableRecord()).columns.find((O)=>O.column.id===this.id);if(!$)throw new E(`Pipeline column ${this.id} is unavailable`);return $}async writable(){return(await this.fetch()).writable}async name(){return(await this.fetch()).column.display_name??(await this.fetch()).definition.definition.display_name}}class nx{client;constructor($){this.client=$}byId($){return s$.byId(this.client,$)}async list(){return G(await this.client.storage.listCrmPipelines()).map(($)=>s$.from(this.client,$))}async create($){return s$.from(this.client,G(await this.client.storage.createCrmPipeline({body:$})))}}class sx{client;pipelines;constructor($){this.client=$;this.pipelines=new nx($)}companyById($){return b$.byId(this.client,$)}contactById($){return f$.byId(this.client,$)}async contactByEmail($){let{contact:O}=G(await this.client.storage.getContactByEmail({query:{email:$}}));return O?f$.from(this.client,O):void 0}async searchContacts($,O={}){let{contacts:j}=G(await this.client.storage.searchContacts({query:{query:$,limit:O.limit}}));return j.map((x)=>f$.from(this.client,x))}async createCompany($){return b$.from(this.client,G(await this.client.storage.createCrmCompany({body:$})))}async settings(){return G(await this.client.storage.getCrmTeamSettings())}async updateSettings($){return G(await this.client.storage.putCrmTeamSettings({body:$}))}async setStages($){return G(await this.client.storage.putCrmTeamStages({body:$}))}async resetStages(){G(await this.client.storage.resetCrmTeamStages())}searchCompanies($){return b$.search(this.client,$)}}var G$=Symbol.for("@ts-pattern/matcher"),m1=Symbol.for("@ts-pattern/isVariadic");var tx=($)=>Boolean($&&typeof $=="object"),Tj=($)=>$&&!!$[G$],s=($,O,j)=>{if(Tj($)){let x=$[G$](),{matched:S,selections:K}=x.match(O);return S&&K&&Object.keys(K).forEach((Z)=>j(Z,K[Z])),S}if(tx($)){if(!tx(O))return!1;if(Array.isArray($)){if(!Array.isArray(O))return!1;let x=[],S=[],K=[];for(let Z of $.keys()){let X=$[Z];Tj(X)&&X[m1]?K.push(X):K.length?S.push(X):x.push(X)}if(K.length){if(K.length>1)throw Error("Pattern error: Using `...P.array(...)` several times in a single pattern is not allowed.");if(O.length<x.length+S.length)return!1;let Z=O.slice(0,x.length),X=S.length===0?[]:O.slice(-S.length),Y=O.slice(x.length,S.length===0?1/0:-S.length);return x.every((L,Q)=>s(L,Z[Q],j))&&S.every((L,Q)=>s(L,X[Q],j))&&(K.length===0||s(K[0],Y,j))}return $.length===O.length&&$.every((Z,X)=>s(Z,O[X],j))}return Reflect.ownKeys($).every((x)=>{let S=$[x];return((x in O)||Tj(K=S)&&K[G$]().matcherType==="optional")&&s(S,O[x],j);var K})}return Object.is(O,$)},Y$=($)=>{var O,j,x;return tx($)?Tj($)?(O=(j=(x=$[G$]()).getSelectionKeys)==null?void 0:j.call(x))!=null?O:[]:Array.isArray($)?tO($,Y$):tO(Object.values($),Y$):[]},tO=($,O)=>$.reduce((j,x)=>j.concat(O(x)),[]);function a6(...$){if($.length===1){let[O]=$;return(j)=>s(O,j,()=>{})}if($.length===2){let[O,j]=$;return s(O,j,()=>{})}throw Error(`isMatching wasn't given the right number of arguments: expected 1 or 2, received ${$.length}.`)}function t($){return Object.assign($,{optional:()=>$0($),and:(O)=>d($,O),or:(O)=>c1($,O),select:(O)=>O===void 0?eO($):eO(O,$)})}function ex($){return Object.assign(((O)=>Object.assign(O,{[Symbol.iterator](){let j=0,x=[{value:Object.assign(O,{[m1]:!0}),done:!1},{done:!0,value:void 0}];return{next:()=>{var S;return(S=x[j++])!=null?S:x.at(-1)}}}}))($),{optional:()=>ex($0($)),select:(O)=>ex(O===void 0?eO($):eO(O,$))})}function $0($){return t({[G$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return O===void 0?(Y$($).forEach((S)=>x(S,void 0)),{matched:!0,selections:j}):{matched:s($,O,x),selections:j}},getSelectionKeys:()=>Y$($),matcherType:"optional"})})}var i6=($,O)=>{for(let j of $)if(!O(j))return!1;return!0},n6=($,O)=>{for(let[j,x]of $.entries())if(!O(x,j))return!1;return!0},s6=($,O)=>{let j=Reflect.ownKeys($);for(let x of j)if(!O(x,$[x]))return!1;return!0};function d(...$){return t({[G$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return{matched:$.every((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>tO($,Y$),matcherType:"and"})})}function c1(...$){return t({[G$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return tO($,Y$).forEach((S)=>x(S,void 0)),{matched:$.some((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>tO($,Y$),matcherType:"or"})})}function m($){return{[G$]:()=>({match:(O)=>({matched:Boolean($(O))})})}}function eO(...$){let O=typeof $[0]=="string"?$[0]:void 0,j=$.length===2?$[1]:typeof $[0]=="string"?void 0:$[0];return t({[G$]:()=>({match:(x)=>{let S={[O!=null?O:"@ts-pattern/anonymous-select-key"]:x};return{matched:j===void 0||s(j,x,(K,Z)=>{S[K]=Z}),selections:S}},getSelectionKeys:()=>[O!=null?O:"@ts-pattern/anonymous-select-key"].concat(j===void 0?[]:Y$(j))})})}function u1($){return!0}function k$($){return typeof $=="number"}function t$($){return typeof $=="string"}function e$($){return typeof $=="bigint"}var d1=t(m(u1)),t6=t(m(u1)),e6=d1,o$=($)=>Object.assign(t($),{startsWith:(O)=>{return o$(d($,(j=O,m((x)=>t$(x)&&x.startsWith(j)))));var j},endsWith:(O)=>{return o$(d($,(j=O,m((x)=>t$(x)&&x.endsWith(j)))));var j},minLength:(O)=>o$(d($,((j)=>m((x)=>t$(x)&&x.length>=j))(O))),length:(O)=>o$(d($,((j)=>m((x)=>t$(x)&&x.length===j))(O))),maxLength:(O)=>o$(d($,((j)=>m((x)=>t$(x)&&x.length<=j))(O))),includes:(O)=>{return o$(d($,(j=O,m((x)=>t$(x)&&x.includes(j)))));var j},regex:(O)=>{return o$(d($,(j=O,m((x)=>t$(x)&&Boolean(x.match(j))))));var j}}),h1=o$(m(t$)),g$=($)=>Object.assign(t($),{between:(O,j)=>g$(d($,((x,S)=>m((K)=>k$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>g$(d($,((j)=>m((x)=>k$(x)&&x<j))(O))),gt:(O)=>g$(d($,((j)=>m((x)=>k$(x)&&x>j))(O))),lte:(O)=>g$(d($,((j)=>m((x)=>k$(x)&&x<=j))(O))),gte:(O)=>g$(d($,((j)=>m((x)=>k$(x)&&x>=j))(O))),int:()=>g$(d($,m((O)=>k$(O)&&Number.isInteger(O)))),finite:()=>g$(d($,m((O)=>k$(O)&&Number.isFinite(O)))),positive:()=>g$(d($,m((O)=>k$(O)&&O>0))),negative:()=>g$(d($,m((O)=>k$(O)&&O<0)))}),o6=g$(m(k$)),$O=($)=>Object.assign(t($),{between:(O,j)=>$O(d($,((x,S)=>m((K)=>e$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>$O(d($,((j)=>m((x)=>e$(x)&&x<j))(O))),gt:(O)=>$O(d($,((j)=>m((x)=>e$(x)&&x>j))(O))),lte:(O)=>$O(d($,((j)=>m((x)=>e$(x)&&x<=j))(O))),gte:(O)=>$O(d($,((j)=>m((x)=>e$(x)&&x>=j))(O))),positive:()=>$O(d($,m((O)=>e$(O)&&O>0))),negative:()=>$O(d($,m((O)=>e$(O)&&O<0)))}),$7=$O(m(e$)),O7=t(m(function($){return typeof $=="boolean"})),j7=t(m(function($){return typeof $=="symbol"})),x7=t(m(function($){return $==null})),S7=t(m(function($){return $!=null})),Z$={__proto__:null,matcher:G$,optional:$0,array:function(...$){return ex({[G$]:()=>({match:(O)=>{if(!Array.isArray(O))return{matched:!1};if($.length===0)return{matched:!0};let j=$[0],x={};if(O.length===0)return Y$(j).forEach((K)=>{x[K]=[]}),{matched:!0,selections:x};let S=(K,Z)=>{x[K]=(x[K]||[]).concat([Z])};return{matched:O.every((K)=>s(j,K,S)),selections:x}},getSelectionKeys:()=>$.length===0?[]:Y$($[0])})})},set:function(...$){return t({[G$]:()=>({match:(O)=>{if(!(O instanceof Set))return{matched:!1};let j={};if(O.size===0)return{matched:!0,selections:j};if($.length===0)return{matched:!0};let x=(K,Z)=>{j[K]=(j[K]||[]).concat([Z])},S=$[0];return{matched:i6(O,(K)=>s(S,K,x)),selections:j}},getSelectionKeys:()=>$.length===0?[]:Y$($[0])})})},map:function(...$){return t({[G$]:()=>({match:(O)=>{if(!(O instanceof Map))return{matched:!1};let j={};if(O.size===0)return{matched:!0,selections:j};let x=(X,Y)=>{j[X]=(j[X]||[]).concat([Y])};if($.length===0)return{matched:!0};var S;if($.length===1)throw Error(`\`P.map\` wasn't given enough arguments. Expected (key, value), received ${(S=$[0])==null?void 0:S.toString()}`);let[K,Z]=$;return{matched:n6(O,(X,Y)=>{let L=s(K,Y,x),Q=s(Z,X,x);return L&&Q}),selections:j}},getSelectionKeys:()=>$.length===0?[]:[...Y$($[0]),...Y$($[1])]})})},record:function(...$){return t({[G$]:()=>({match:(O)=>{if(O===null||typeof O!="object"||Array.isArray(O))return{matched:!1};var j;if($.length===0)throw Error(`\`P.record\` wasn't given enough arguments. Expected (value) or (key, value), received ${(j=$[0])==null?void 0:j.toString()}`);let x={},S=(X,Y)=>{x[X]=(x[X]||[]).concat([Y])},[K,Z]=$.length===1?[h1,$[0]]:$;return{matched:s6(O,(X,Y)=>{let L=typeof X!="string"||Number.isNaN(Number(X))?null:Number(X),Q=L!==null&&s(K,L,S),J=s(K,X,S),I=s(Z,Y,S);return(J||Q)&&I}),selections:x}},getSelectionKeys:()=>$.length===0?[]:[...Y$($[0]),...Y$($[1])]})})},intersection:d,union:c1,not:function($){return t({[G$]:()=>({match:(O)=>({matched:!s($,O,()=>{})}),getSelectionKeys:()=>[],matcherType:"not"})})},when:m,select:eO,any:d1,unknown:t6,_:e6,string:h1,number:o6,bigint:$7,boolean:O7,symbol:j7,nullish:x7,nonNullable:S7,instanceOf:function($){return t(m(function(O){return(j)=>j instanceof O}($)))},shape:function($){return t(m(a6($)))}};class l1 extends Error{constructor($){let O;try{O=JSON.stringify($)}catch(j){O=$}super(`Pattern matching error: no pattern matches value ${O}`),this.input=void 0,this.input=$}}var ox={matched:!1,value:void 0};function c($){return new Hj($,ox)}class Hj{constructor($,O){this.input=void 0,this.state=void 0,this.input=$,this.state=O}with(...$){if(this.state.matched)return this;let O=$[$.length-1],j=[$[0]],x;$.length===3&&typeof $[1]=="function"?x=$[1]:$.length>2&&j.push(...$.slice(1,$.length-1));let S=!1,K={},Z=(Y,L)=>{S=!0,K[Y]=L},X=!j.some((Y)=>s(Y,this.input,Z))||x&&!Boolean(x(this.input))?ox:{matched:!0,value:O(S?"@ts-pattern/anonymous-select-key"in K?K["@ts-pattern/anonymous-select-key"]:K:this.input,this.input)};return new Hj(this.input,X)}when($,O){if(this.state.matched)return this;let j=Boolean($(this.input));return new Hj(this.input,j?{matched:!0,value:O(this.input,this.input)}:ox)}otherwise($){return this.state.matched?this.state.value:$(this.input)}exhaustive($=Z7){return this.state.matched?this.state.value:$(this.input)}run(){return this.exhaustive()}returnType(){return this}narrow(){return this}}function Z7($){throw new l1($)}var O0,X7=new Uint8Array(16);function Rj(){if(!O0){if(typeof crypto>"u"||!crypto.getRandomValues)throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");O0=crypto.getRandomValues.bind(crypto)}return O0(X7)}var j$=[];for(let $=0;$<256;++$)j$.push(($+256).toString(16).slice(1));function r1($,O=0){return(j$[$[O+0]]+j$[$[O+1]]+j$[$[O+2]]+j$[$[O+3]]+"-"+j$[$[O+4]]+j$[$[O+5]]+"-"+j$[$[O+6]]+j$[$[O+7]]+"-"+j$[$[O+8]]+j$[$[O+9]]+"-"+j$[$[O+10]]+j$[$[O+11]]+j$[$[O+12]]+j$[$[O+13]]+j$[$[O+14]]+j$[$[O+15]]).toLowerCase()}var j0={};function K7($,O,j){let x;if($)x=p1($.random??$.rng?.()??Rj(),$.msecs,$.seq,O,j);else{let S=Date.now(),K=Rj();Y7(j0,S,K),x=p1(K,j0.msecs,j0.seq,O,j)}return O??r1(x)}function Y7($,O,j){if($.msecs??=-1/0,$.seq??=0,O>$.msecs)$.seq=j[6]<<23|j[7]<<16|j[8]<<8|j[9],$.msecs=O;else if($.seq=$.seq+1|0,$.seq===0)$.msecs++;return $}function p1($,O,j,x,S=0){if($.length<16)throw Error("Random bytes length must be >= 16");if(!x)x=new Uint8Array(16),S=0;else if(S<0||S+16>x.length)throw RangeError(`UUID byte range ${S}:${S+15} is out of buffer bounds`);return O??=Date.now(),j??=$[6]*127<<24|$[7]<<16|$[8]<<8|$[9],x[S++]=O/1099511627776&255,x[S++]=O/4294967296&255,x[S++]=O/16777216&255,x[S++]=O/65536&255,x[S++]=O/256&255,x[S++]=O&255,x[S++]=112|j>>>28&15,x[S++]=j>>>20&255,x[S++]=128|j>>>14&63,x[S++]=j>>>6&255,x[S++]=j<<2&255|$[10]&3,x[S++]=$[11],x[S++]=$[12],x[S++]=$[13],x[S++]=$[14],x[S++]=$[15],x}var d$=K7;class A${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new A$($,O)}async detail(){let{columns:$}=await this.table.detail(),O=$.find((j)=>j.column.id===this.id);if(!O)throw new E(`column ${this.id} is not on table ${this.table.id}`);return O}async name(){let $=await this.detail();return $.column.display_name??$.definition.definition.display_name}async rename($){return await this.table.database.renameColumn(this,$),this}async inferType($){return await this.table.database.inferColumnType(this,$),this}changeType($){return this.table.database.changeColumnType(this,$)}convertIntoNewColumn($){return this.table.database.convertColumnIntoNewColumn(this,$)}casts(){return this.table.database.columnCasts(this)}async delete(){await this.table.database.deleteColumn(this)}async dataType(){return(await this.detail()).definition.definition.data_type}async isMultiSelect(){return(await this.detail()).definition.definition.is_multi_select}async position(){return(await this.detail()).column.position}async definition(){return(await this.detail()).definition}async config(){return(await this.detail()).column.config??void 0}async addOptions($){return await this.table.database.addColumnOptions(this,$),this}toJSON(){return{id:this.id,tableId:this.table.id}}}class F${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new F$($,O)}history(){return this.table.database.rowHistory(this)}toJSON(){return{id:this.id,tableId:this.table.id}}}class Dj{table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new Dj($,O)}async detail(){let{views:$}=await this.table.detail(),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`view ${this.id} is not on table ${this.table.id}`);return O}async name(){return(await this.detail()).name}async position(){return(await this.detail()).position}async layout(){return(await this.detail()).layout}async query(){return(await this.detail()).query}positions(){return this.table.database.viewPositions(this)}toJSON(){return{id:this.id,tableId:this.table.id}}}class J${database;id;constructor($,O){this.database=$;this.id=O}static byId($,O){return new J$($,O)}async detail(){let{tables:$}=await this.database.schema(),O=$.find((j)=>j.table.id===this.id);if(!O)throw new E(`table ${this.id} is not in database ${this.database.id}`);return O}async name(){return(await this.detail()).table.name}async rename($){return await this.database.renameTable(this,$),this}async version(){return(await this.detail()).table.version}async position(){return(await this.detail()).table.position}async columns(){let{columns:$}=await this.detail();return $.map((O)=>A$.byId(this,O.column.id))}addColumn($){return this.database.addColumn(this,$)}async reorderColumns($){return await this.database.reorderColumns(this,$),this}row($){return F$.byId(this,$)}async views(){let{views:$}=await this.detail();return $.map((O)=>Dj.byId(this,O.id))}createWebhook(){return this.database.createWebhook(this)}async delete(){await this.database.deleteTable(this)}toJSON(){return{id:this.id,databaseId:this.database.id}}}async function _j($,O,j,x={}){let S=G(await $.storage.queryDatabases({body:{sql:j,databaseId:x.database?.id,baseVersions:Object.fromEntries((x.baseVersions??[]).map(({table:Q,version:J})=>[Q.id,J]))}})),K=new Map;for(let Q of[x.database,...(x.baseVersions??[]).map(({table:J})=>J.database)]){if(!Q)continue;let J=K.get(Q.id);if(J)J.add(Q);else K.set(Q.id,new Set([Q]))}let Z=(Q)=>{let J=K.get(Q)?.values().next().value;if(J)return J;let I=O($,Q);return K.set(Q,new Set([I])),I},X=(Q)=>{let J=S.tableDatabases[Q];if(!J)throw Error(`SQL response is missing the owner of table ${Q}`);return J$.byId(Z(J),Q)},Y=new Set(Object.keys(S.newVersions).map((Q)=>X(Q).database.id));if(S.statement.kind==="schema")Y.add(S.statement.databaseId);for(let Q of Y)for(let J of K.get(Q)??[])J.invalidateSchema();let L=c(S.statement).with({kind:"select"},(Q)=>Q).with({kind:"schema"},({databaseId:Q,summary:J})=>({kind:"schema",database:Z(Q),summary:J})).with({kind:"insert"},{kind:"update"},{kind:"delete"},({kind:Q,tableId:J,tableName:I})=>({kind:Q,table:X(J),tableName:I})).with({kind:"alterColumnType"},({tableId:Q,tableName:J,columnId:I,columnName:z,to:B})=>{let V=X(Q);return{kind:"alterColumnType",table:V,tableName:J,column:A$.byId(V,I),columnName:z,to:B}}).exhaustive();return{result:S.result?G7(S.result,X,S.tableDatabases):void 0,changesApplied:S.changesApplied,insertedRows:L.kind==="insert"?S.insertedRowIds.map((Q)=>F$.byId(L.table,Q)):[],newVersions:Object.entries(S.newVersions).map(([Q,J])=>({table:X(Q),version:J})),readVersions:Object.entries(S.readVersions).map(([Q,J])=>({table:X(Q),version:J})),truncatedTables:S.truncatedTables,statement:L}}function G7($,O,j){let x=$.sourceTable&&j[$.sourceTable]?O($.sourceTable):void 0;return{columns:$.columns.map(({relatedTable:S,...K})=>({...K,relatedTable:S&&j[S]?O(S):void 0})),rows:$.rows,sourceTable:x,rowHandles:x?$.rowIds.map((S)=>F$.byId(x,S)):[]}}class Cj{table;id;createdBy;record;constructor($,O,j,x){this.table=$;this.id=O;this.createdBy=j;this.record=x}static fromRecord($,O,j){return new Cj($,j.id,O,j)}get tokenPrefix(){return this.record.tokenPrefix}get createdAt(){return this.record.createdAt}delete(){return this.table.database.deleteWebhook(this)}toJSON(){return{id:this.id,tableId:this.table.id,tokenPrefix:this.tokenPrefix}}}class Z0 extends QO{op;row;column;taken;constructor($,O){super($,O);this.name="MacroOpRefusedError",this.message=O.message,this.op=O.op,this.row=O.row,this.column=O.column,this.taken=O.taken}}function Mj($){return c($).with({type:"relation"},({table:O})=>({type:"relation",database:O.database.id,table:O.id})).with({type:Z$.not("relation")},(O)=>O).exhaustive()}var Q7={USER:"People",DOCUMENT:"Documents",TASK:"Tasks",COMPANY:"Companies",CONTACT:"Contacts",CALL_RECORD:"Calls",CHANNEL:"Channels",CHAT:"Chats",PROJECT:"Projects",THREAD:"Emails",CALENDAR_EVENT:"Events",INITIATIVE:"Initiatives"};function J7($){return c($).with({type:"text"},()=>"Text").with({type:"number"},()=>"Number").with({type:"boolean"},()=>"Checkbox").with({type:"date"},()=>"Date").with({type:"link"},()=>"URL").with({type:"select",multi:!0},()=>"Multi-select").with({type:"select",multi:!1},()=>"Select").with({type:"select_number",multi:!0},()=>"Multi-number select").with({type:"select_number",multi:!1},()=>"Number select").with({type:"tag"},()=>"Tag").with({type:"entity"},({target:O})=>Q7[O]).with({type:"relation"},()=>"Relation").exhaustive(()=>"Column")}function x0($){return $.map((O)=>({id:d$(),label:O}))}function a1($,O,j){return $?.kind===O&&"change"in $&&$.change.kind===j}function S0($){return c($).with({kind:"reorder_tables"},({kind:O})=>O).with({kind:Z$.union("table","column","rows","view")},({kind:O,change:j})=>`${O}.${j.kind}`).exhaustive(()=>"unknown")}function l$($,O,j){let[x]=$;if($.length!==1||!a1(x,O,j))throw new f(`expected one ${O}.${j} result, got ${$.map(S0).join(", ")||"none"}`);return x}class V$ extends P{access=new o(this.client,"database",this);async fetch(){return G(await this.client.storage.getDatabase({path:{id:this.id}}))}assertOwns($,O){if(O.id!==this.id)throw new f(`${$} does not belong to database ${this.id}`)}static byId($,O){return new V$($,O)}static async create($,O){let j=G(await $.storage.createDatabase({body:{name:O.name}}));return new V$($,j.id)}static async list($){return G(await $.storage.listDatabases()).map((j)=>new V$($,j.database.id))}query($,O){return _j(this.client,V$.byId,$,{...O,database:this})}invalidateSchema(){this.detail.clear()}schema(){return this.detail.get()}name=this.mappedField("database",($)=>$.name);owner=this.mappedField("database",($)=>M.byId(this.client,$.owner_id));createdAt=this.mappedField("database",($)=>$.created_at);trashedAt=this.mappedField("database",($)=>$.trashed_at??void 0);grant=this.field("grant");tables=this.mappedField("tables",($)=>$.map((O)=>J$.byId(this,O.table.id)));async table($){let{tables:O}=await this.schema(),j=O.find((x)=>x.table.name===$);return j?J$.byId(this,j.table.id):void 0}async createTable($){let{table:O}=l$(await this.applyOps([{kind:"table",table:d$(),change:{kind:"create",name:$.name}}]),"table","created");return J$.byId(this,O)}async applyOps($,O={}){let j={ops:$};if(O.baseVersions!==void 0){for(let{table:S}of O.baseVersions)this.assertOwns(`table ${S.id}`,S.database);j.baseVersions=Object.fromEntries(O.baseVersions.map(({table:S,version:K})=>[S.id,K]))}let{results:x}=await this.mutate(async(S)=>{let K=await S.storage.applyDatabaseOps({path:{id:this.id},body:j});if(K.error!==void 0&&"op"in K.error)throw new Z0(K.response?.status??0,K.error);return K});return x}async reorderTables($){for(let x of $)this.assertOwns(`table ${x.id}`,x.database);let O=await this.applyOps([{kind:"reorder_tables",order:$.map((x)=>x.id)}]),[j]=O;if(O.length!==1||j?.kind!=="reorder_tables")throw new f(`expected one reorder_tables result, got ${O.map(S0).join(", ")||"none"}`);return j.tables.map(({table:x})=>J$.byId(this,x))}async deleteTable($){this.assertOwns(`table ${$.id}`,$.database),l$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"delete"}}]),"table","deleted")}async columnCasts($){return this.assertOwns(`column ${$.id}`,$.table.database),G(await this.client.storage.listDatabaseColumnCasts({path:{id:this.id,table_id:$.table.id,column_id:$.id}}))}async viewPositions($){this.assertOwns(`view ${$.id}`,$.table.database);let{positions:O}=G(await this.client.storage.getDatabaseViewPositions({path:{id:this.id,view_id:$.id}}));return O}async rowHistory($){this.assertOwns(`row ${$.id}`,$.table.database);let{changes:O}=G(await this.client.storage.getDatabaseRowHistory({path:{id:this.id,table_id:$.table.id,row_id:$.id}}));return O}async importTable($){let O=await this.mutate((j)=>j.storage.importDatabaseTable({path:{id:this.id},body:$}));return J$.byId(this,O.id)}webhookOf($){return Cj.fromRecord(J$.byId(this,$.tableId),M.byId(this.client,$.createdBy),$)}async webhooks(){let{webhooks:$}=G(await this.client.storage.listDatabaseWebhooks({path:{id:this.id}}));return $.map((O)=>this.webhookOf(O))}async createWebhook($){this.assertOwns("table",$.database);let O=G(await this.client.storage.createDatabaseWebhook({path:{id:this.id},body:{tableId:$.id}}));return{webhook:this.webhookOf(O.webhook),token:O.token}}async deleteWebhook($){this.assertOwns("webhook",$.table.database),G(await this.client.storage.deleteDatabaseWebhook({path:{id:this.id,webhook_id:$.id}}))}async sharePermissions(){return G(await this.client.storage.getDatabasePermissions({path:{id:this.id}}))}updateSharePermissions($){return this.mutate((O)=>O.storage.updateDatabasePermissions({path:{id:this.id},body:$}))}async changeColumnType($,O){this.assertOwns(`column ${$.id}`,$.table.database);let j=await $.table.version();return l$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"change_type",to:Mj(O.to)}}],{baseVersions:[{table:$.table,version:j}]}),"column","type_changed")}async columnConversion($,O){return this.assertOwns(`column ${$.id}`,$.table.database),G(await this.client.storage.convertDatabaseColumn({path:{id:this.id,table_id:$.table.id,column_id:$.id},body:{to:Mj(O)}}))}async convertColumnIntoNewColumn($,O){let j=await this.columnConversion($,O.to),x=O.name??`${await $.name()} (${J7(O.to)})`,S=d$(),K=[{kind:"column",table:$.table.id,column:S,change:{kind:"create",definition:{source:"new",name:x,type:Mj(O.to),options:x0(j.options)},after:$.id}}];if(j.cells.length>0)K.push({kind:"rows",table:$.table.id,change:{kind:"update",changes:{kind:"per_row",rows:j.cells.map(({row:X,value:Y})=>({row:X,cells:[{column:S,value:Y}]}))}}});let[Z]=await this.applyOps(K,{baseVersions:[{table:$.table,version:j.tableVersion}]});if(!a1(Z,"column","created"))throw new f(`expected a column.created result, got ${Z?S0(Z):"none"}`);return A$.byId($.table,Z.column)}async deleteColumn($){this.assertOwns(`column ${$.id}`,$.table.database);let O=await $.table.version(),{tableVersion:j}=l$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"delete"}}],{baseVersions:[{table:$.table,version:O}]}),"column","deleted");return j}async reorderColumns($,O){this.assertOwns(`table ${$.id}`,$.database);for(let S of O)if(S.table.id!==$.id)throw new f(`column ${S.id} does not belong to table ${$.id}`);let j=await $.version(),{tableVersion:x}=l$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"reorder_columns",order:O.map((S)=>S.id)}}],{baseVersions:[{table:$,version:j}]}),"table","columns_reordered");if(x===void 0)throw new f(`table ${$.id} reordered its columns without a version`);return x}async renameTable($,O){this.assertOwns(`table ${$.id}`,$.database);let j=await $.name(),{tableVersion:x}=l$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"rename",name:O,previousName:j}}]),"table","renamed");if(x===void 0)throw new f(`table ${$.id} was renamed without a version`);return x}async renameColumn($,O){this.assertOwns(`column ${$.id}`,$.table.database);let j=await $.name(),{tableVersion:x}=l$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"rename",name:O,previousName:j}}]),"column","renamed");return x}async inferColumnType($,O){return this.assertOwns(`column ${$.id}`,$.table.database),this.mutate((j)=>j.storage.inferDatabaseColumnType({path:{id:this.id,table_id:$.table.id,column_id:$.id},body:{dataType:O.dataType,baseVersion:O.baseVersion,...O.specificEntityType!==void 0?{specificEntityType:O.specificEntityType}:{}}}))}async addColumn($,O){if(this.assertOwns(`table ${$.id}`,$.database),O.after!==void 0&&O.after.table.id!==$.id)throw new f(`column ${O.after.id} does not belong to table ${$.id}`);let j="property"in O?{source:"existing",property:O.property.id}:{source:"new",name:O.name,type:Mj(O.type),...O.options!==void 0?{options:x0(O.options)}:{},...O.inferType!==void 0?{inferType:O.inferType}:{}},{column:x}=l$(await this.applyOps([{kind:"column",table:$.id,column:d$(),change:{kind:"create",definition:j,...O.after!==void 0?{after:O.after.id}:{}}}]),"column","created");return A$.byId($,x)}async addColumnOptions($,O){return this.assertOwns(`column ${$.id}`,$.table.database),l$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"add_options",options:x0(O)}}]),"column","options_added")}}class X0{client;constructor($){this.client=$}query($,O){return _j(this.client,V$.byId,$,O)}byId($){return V$.byId(this.client,$)}create($){return V$.create(this.client,$)}list(){return V$.list(this.client)}}class Pj{id;name;constructor($,O){this.id=$;this.name=O}static async list($){let{skills:O}=G(await $.storage.getSystemSkillsHandler());return O.map((j)=>new Pj(j.id,j.name))}}class K0{client;async byTeamSlug($){let O=G(await this.client.storage.getDocumentByTeamSlug({path:{slug:$}}));if(typeof O!=="object"||O===null||!("data"in O)||typeof O.data!=="object"||O.data===null||!("documentMetadata"in O.data)||typeof O.data.documentMetadata!=="object"||O.data.documentMetadata===null||!("documentId"in O.data.documentMetadata)||typeof O.data.documentMetadata.documentId!=="string")throw Error("Invalid team task document response");return w.byId(this.client,O.data.documentMetadata.documentId)}async validatePermissionsToken($){let O=G(await this.client.storage.validateDocumentPermissionsToken({body:{token:$}}));return{document:w.byId(this.client,O.document_id),user:O.user_id?M.byId(this.client,O.user_id):void 0,accessLevel:O.access_level,expiresAt:O.exp,issuer:O.iss}}async createUpload($){let O={documentName:$.name,sha:$.sha,fileType:$.fileType,mimeType:$.mimeType,projectId:$.project?.id,teamId:$.team?.id,branchedFromId:$.branchedFrom?.id,emailAttachmentId:$.attachment?.id,isTask:$.isTask},j=G(await this.client.storage.createDocument({body:O})).data;return{document:w.byId(this.client,j.documentMetadata.documentId),uploadUrl:j.presignedUrl??void 0,contentType:j.contentType,content:j.documentMetadata.content}}constructor($){this.client=$}byId($){return w.byId(this.client,$)}create($){return w.create(this.client,$)}async createCanvas($){let O=G(await this.client.storage.createCanvasHandler({body:{documentName:$.name,projectId:$.project?.id}}));return w.byId(this.client,O.documentId)}createSnippet($){return w.createSnippet(this.client,$)}createSkill($){return w.createSkill(this.client,$)}systemSkills(){return Pj.list(this.client)}search($,O){return w.search(this.client,$,O)}recent($){return w.recent(this.client,$)}recentlyDeleted(){return w.recentlyDeleted(this.client)}}class WO extends P{async fetch(){let{attachment:$}=G(await this.client.email.getAttachment({path:{id:this.id}}));return $}static byId($,O){return new WO($,O)}static from($,O){return new WO($,O.db_id,O)}filename=this.field("filename");mimeType=this.field("mime_type");size=this.field("size_bytes");dataUrl=this.field("data_url");sfsId=this.field("sfs_id");contentId=this.field("content_id");async toDocument(){let{document_id:$}=G(await this.client.email.getAttachmentDocumentId({path:{id:this.id}}));return w.byId(this.client,$)}}class R$ extends X${access=new o(this.client,"email_thread",this);async followup(){return G(await this.client.storage.getEmailFollowup({path:{thread_id:this.id}}))}async setFollowup($){return G(await this.client.storage.setEmailFollowup({path:{thread_id:this.id},body:$}))}async calendarInvitations(){return G(await this.client.email.getThreadCalendarInvitations({path:{thread_id:this.id}}))}async addEventToCalendar($,O,j={}){let x=G(await this.client.email.copyThreadCalendarInvitation({path:{thread_id:this.id,message_id:$.id,invitation_id:O.id},body:{calendarId:j.calendar?.id}}));return $$.fromRecord(this.client,x)}async update($){await this.mutate((O)=>O.storage.editThreadV2({path:{thread_id:this.id},body:{projectId:$.project===void 0?void 0:$.project?.id??null,sharePermission:$.sharePermission?i$($.sharePermission):void 0}}))}entityType="email_thread";propertyEntityType="THREAD";async fetch(){let{thread:$}=G(await this.client.email.getThread({path:{thread_id:this.id},query:{limit:100}}));return $}static byId($,O){return new R$($,O)}createdAt=this.field("created_at");updatedAt=this.field("updated_at");isRead=this.field("is_read");inboxVisible=this.field("inbox_visible");accessLevel=this.field("access_level");providerId=this.field("provider_id");link=this.mappedField("link_id",($)=>T$.byId(this.client,$));project=this.mappedField("project_id",($)=>$?n.byId(this.client,$):void 0);latestInboundAt=this.field("latest_inbound_message_ts");latestOutboundAt=this.field("latest_outbound_message_ts");latestNonSpamAt=this.field("latest_non_spam_message_ts");async subject(){let{messages:$}=await this.detail.get();for(let O of $)if(O.subject)return O.subject;return}async participants(){let{messages:$}=await this.detail.get(),O=new Map;for(let j of $)for(let x of[j.from,...j.to,...j.cc,...j.bcc])if(x&&!O.has(x.email))O.set(x.email,x);return[...O.values()]}async messages($){return G(await this.client.email.getThreadMessagesHandler({path:{id:this.id},query:{...$?.since?{since:$.since}:{},...$?.limit?{limit:$.limit}:{}}})).map((j)=>D$.from(this.client,j))}async attachments(){let{messages:$}=await this.detail.get();return $.flatMap((O)=>O.attachments.map((j)=>WO.from(this.client,j)))}async reply($){let O=$.subject??await this.subject()??"",{message:j}=await this.mutate((x)=>x.email.sendMessage({body:{message:{thread_db_id:this.id,replying_to_id:$.replyingTo?.id??null,to:$.to,cc:$.cc??null,bcc:$.bcc??null,subject:O,body_text:$.bodyText}}}));return j.db_id?D$.byId(this.client,j.db_id):void 0}async archive($=!0){await this.mutate((O)=>O.email.archiveThread({path:{id:this.id},body:{value:$}}))}async updateState($){await this.mutate((O)=>O.email.updateThreadState({path:{id:this.id},body:$}))}async operations(){return G(await this.client.email.threadOperations({path:{id:this.id}}))}async markSeen(){await this.mutate(($)=>$.email.threadSeen({path:{id:this.id}}))}async addLabel($){await this.mutate((O)=>O.email.addRemoveThreadLabel({path:{id:this.id},body:{label_id:$.id,value:!0}}))}async removeLabel($){await this.mutate((O)=>O.email.addRemoveThreadLabel({path:{id:this.id},body:{label_id:$.id,value:!1}}))}async moveToProject($){await this.mutate((O)=>O.email.updateThreadProject({path:{thread_id:this.id},body:{projectId:$?.id??null}}))}static search=x$({filters:{email_filters:{}},type:"email",make:($,O)=>new R$($,O.thread_id)})}class D$ extends P{async fetch(){return G(await this.client.email.getMessage({path:{id:this.id}}))}static byId($,O){return new D$($,O)}static from($,O){return new D$($,O.db_id,O)}static async send($,O){let{message:j}=G(await $.email.sendMessage({body:{message:{to:O.to,cc:O.cc??null,bcc:O.bcc??null,subject:O.subject,body_text:O.bodyText}}}));return j.db_id?D$.byId($,j.db_id):void 0}subject=this.field("subject");from=this.field("from");to=this.field("to");cc=this.field("cc");bcc=this.field("bcc");body=this.field("body_parsed");sentAt=this.field("internal_date_ts");labels=this.field("labels");link=this.mappedField("link_id",($)=>T$.byId(this.client,$));async operationStatus(){return G(await this.client.email.messageOperationStatus({path:{id:this.id}}))}async resolveOperation($){await this.mutate((O)=>O.email.resolveMessageOperation({path:{id:this.id},body:$}))}async completeDraftAttachment($,O=0){let j=await this.link();await this.mutate((x)=>x.email.completeDraftAttachment({path:{id:this.id,attachment_id:$},query:{draft_generation:O},headers:{"X-Email-Link-Id":j.id}}))}async transferDraft($){let O=await this.detail.get();return this.mutate((j)=>j.email.transferDraft({path:{id:this.id},body:{...$,draft_generation:$.draft_generation??O.draft_generation??0},headers:{"X-Email-Link-Id":O.link_id}}))}async addLabel($){await this.mutate((O)=>O.email.addRemoveLabel({body:{label_id:$.id,message_ids:[this.id],value:!0}}))}async removeLabel($){await this.mutate((O)=>O.email.addRemoveLabel({body:{label_id:$.id,message_ids:[this.id],value:!1}}))}async thread(){return R$.byId(this.client,(await this.detail.get()).thread_db_id)}}class LO extends D${async draftContext(){let $=await this.detail.get();return{headers:{"X-Email-Link-Id":$.link_id},query:{draft_generation:$.draft_generation??0}}}static byId($,O){return new LO($,O)}draftGeneration=this.field("draft_generation");async update($){let{headers:O,query:j}=await this.draftContext();await this.mutate((x)=>x.email.createDraft({headers:O,body:{draft:{...Y0($),db_id:this.id,draft_generation:$.draftGeneration??j.draft_generation}}}))}async delete(){let{headers:$,query:O}=await this.draftContext();await this.mutate((j)=>j.email.deleteDraft({path:{id:this.id},headers:$,query:O}))}async schedule($,O){let{headers:j,query:x}=await this.draftContext();await this.mutate((S)=>S.email.upsertScheduledMessage({path:{id:this.id},headers:j,query:x,body:{send_time:$,include_signature:O?.includeSignature}}))}async unschedule(){let{headers:$,query:O}=await this.draftContext();await this.mutate((j)=>j.email.deleteScheduledDraft({path:{message_id:this.id},headers:$,query:O}))}async addAttachment($){let O={file_name:$.fileName,sha:$.sha,size:$.size,upload_id:$.uploadId},{headers:j,query:x}=await this.draftContext(),S=await this.mutate((K)=>K.email.addDraftAttachment({path:{id:this.id},headers:j,query:x,body:O}));return{attachment:oO.byId(this.client,this,S.attachment_id,!1,x.draft_generation),uploadUrl:S.upload_url,contentType:S.content_type}}async forwardAttachment($){let{headers:O,query:j}=await this.draftContext(),x=await this.mutate((S)=>S.email.addForwardedAttachment({path:{id:this.id},headers:O,query:j,body:{attachment_id:$.id}}));return oO.byId(this.client,this,x.attachment_id,!0,j.draft_generation)}async removeAttachment($){if($.draft.id!==this.id)throw Error("Attachment belongs to another draft");let{headers:O}=await this.draftContext(),j={draft_generation:$.draftGeneration};if($.forwarded)await this.mutate((x)=>x.email.removeForwardedAttachment({path:{id:this.id,attachment_id:$.id},headers:O,query:j}));else await this.mutate((x)=>x.email.removeDraftAttachment({path:{id:this.id,attachment_id:$.id},headers:O,query:j}))}async verifyAttachment($){if($.draft.id!==this.id||$.forwarded)throw Error("Expected an uploaded attachment on this draft");await this.completeDraftAttachment($.id,$.draftGeneration)}}class oO{draft;id;forwarded;draftGeneration;constructor($,O,j,x){this.draft=$;this.id=O;this.forwarded=j;this.draftGeneration=x}static byId($,O,j,x=!1,S=0){return new oO(O,j,x,S)}complete(){return this.draft.verifyAttachment(this)}remove(){return this.draft.removeAttachment(this)}toJSON(){return{id:this.id,draftId:this.draft.id,forwarded:this.forwarded,draftGeneration:this.draftGeneration}}}function Y0($){let{bodyText:O,bodyHtml:j,bodyMacro:x,headers:S,includeSignature:K,draftGeneration:Z,thread:X,replyingTo:Y,...L}=$;return{...L,body_text:O,body_html:j===void 0?void 0:btoa(Array.from(new TextEncoder().encode(j),(Q)=>String.fromCharCode(Q)).join("")).replaceAll("+","-").replaceAll("/","_").replaceAll("=",""),body_macro:x,headers_json:S,include_signature:K,draft_generation:Z,thread_db_id:X?.id,replying_to_id:Y?.id}}class NO extends P{inbox;constructor($,O,j,x){super($,O,j);this.inbox=x}get headers(){return this.inbox?{"X-Email-Link-Id":this.inbox.id}:void 0}static byId($,O,j){return new NO($,O,void 0,j)}static from($,O,j){return new NO($,O.id,O,j)}async fetch(){let $=G(await this.client.email.listEmailFilters({headers:this.headers})).filters.find((O)=>O.id===this.id);if(!$)throw new E(`Email filter ${this.id} is unavailable`);return $}emailAddress=this.field("email_address");emailDomain=this.field("email_domain");isImportant=this.field("is_important");async setImportant($){let O=await this.detail.get();await this.mutate((j)=>j.email.upsertEmailFilter({headers:this.headers,body:{email_address:O.email_address,email_domain:O.email_domain,is_important:$}}))}async delete(){await this.mutate(($)=>$.email.deleteEmailFilter({path:{id:this.id},headers:this.headers}))}}class OO extends P{async fetch(){let{labels:$}=G(await this.client.email.listLabels()),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`label ${this.id} not found`);return O}static byId($,O){return new OO($,O)}static async list($){let{labels:O}=G(await $.email.listLabels());return O.map((j)=>new OO($,j.id,j))}static async create($,O){let{label:j}=G(await $.email.createLabel({body:{label_name:O}}));if(!j.id)throw new f("created label has no id");return new OO($,j.id)}async delete(){G(await this.client.email.deleteLabel({path:{id:this.id}}))}name=this.field("name");linkId=this.field("linkId");type=this.field("type");createdAt=this.field("createdAt");labelListVisibility=this.field("labelListVisibility");messageListVisibility=this.field("messageListVisibility")}class G0{client;async createDraft($,O){let j=G(await this.client.email.createDraft({body:{draft:Y0($)},headers:O?{"X-Email-Link-Id":O.id}:void 0}));if(!j.draft.db_id)throw Error("Draft response has no message id");return LO.byId(this.client,j.draft.db_id)}draftById($){return LO.byId(this.client,$)}async*scheduled($){let O=$?.pageSize??100;if(!Number.isInteger(O)||O<1)throw Error("pageSize must be positive");let j=Math.min(O,1000);for(let x=0;;x+=j){let S=G(await this.client.email.getScheduledMessages({query:{offset:x,limit:j},headers:$?.inbox?{"X-Email-Link-Id":$.inbox.id}:void 0}));for(let K of S.messages)yield LO.byId(this.client,K.db_id);if(S.messages.length<j)return}}async filters($){return G(await this.client.email.listEmailFilters({headers:$?{"X-Email-Link-Id":$.id}:void 0})).filters.map((O)=>NO.from(this.client,O,$))}async upsertFilter($,O){return NO.from(this.client,G(await this.client.email.upsertEmailFilter({headers:O?{"X-Email-Link-Id":O.id}:void 0,body:{email_address:$.emailAddress,email_domain:$.emailDomain,is_important:$.isImportant}})).filter,O)}async contacts(){return G(await this.client.email.listContacts()).contacts}reminders($){let{inboxes:O,...j}=$??{};return u(async(x)=>{let S=G(await this.client.storage.listEmailReminders({query:{...j,inboxIds:O?.map((K)=>K.id),cursor:x}}));return{items:S.items.map(({threadId:K,...Z})=>({...Z,thread:R$.byId(this.client,K)})),nextCursor:S.nextCursor}})}constructor($){this.client=$}byId($){return R$.byId(this.client,$)}message($){return D$.byId(this.client,$)}attachment($){return WO.byId(this.client,$)}link($){return T$.byId(this.client,$)}links(){return T$.list(this.client)}async connectionProviders(){return G(await this.client.auth.emailConnectionProviders())}async recoverDraftTransfer($){return G(await this.client.email.recoverDraftTransfer({path:{id:$}}))}send($){return D$.send(this.client,$)}search($,O){return R$.search(this.client,$,O)}inbox($){return u(async(O)=>{let j=G(await this.client.email.previewsInboxCursor({path:{view:"inbox"},query:{...$?.pageSize?{limit:$.pageSize}:{},...$?.sort?{sort_method:$.sort}:{},...O?{cursor:O}:{}}}));return{items:j.items.map((x)=>R$.byId(this.client,x.id)),nextCursor:j.next_cursor}})}label($){return OO.byId(this.client,$)}labels(){return OO.list(this.client)}createLabel($){return OO.create(this.client,$)}async deleteLabel($){G(await this.client.email.deleteLabel({path:{id:$.id}}))}async blockSender($){G(await this.client.email.blockSender({body:{email_address:$}}))}async unblockSender($){G(await this.client.email.unblockSender({body:{email_address:$}}))}async blockedSenders(){return G(await this.client.email.listBlockedSenders()).blocked_emails}}class HO{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new HO($,O)}async delete(){G(await this.client.storage.deleteEntityMention({path:{mention_id:this.id}}))}toJSON(){return{id:this.id}}}class Q0{client;constructor($){this.client=$}byId($){return HO.byId(this.client,$)}async create($,O){let j=G(await this.client.storage.createEntityMention({body:{source_entity_id:$.entity.id,source_entity_type:$.type,entity_id:O.entity.id,entity_type:O.type}}));return HO.byId(this.client,j.id)}}class J0{client;constructor($){this.client=$}async list($={}){let{favorites:O}=G(await this.client.storage.listFavorites({query:{entityType:$.entityTypes,entityId:$.entityIds}}));return O}async add($){return G(await this.client.storage.addFavorite({body:{entityId:$.id,entityType:$.entityType}}))}async remove($){G(await this.client.storage.removeFavoriteByEntity({path:{entity_type:$.entityType,entity_id:$.id}}))}async reorder($){G(await this.client.storage.reorderFavorites({body:{favorites:$}}))}}class jO extends z${entityType="foreign_entity";async fetch(){return G(await this.client.storage.getForeignEntity({path:{id:this.id}}))}static byId($,O){return new jO($,O)}static fromRecord($,O){return new jO($,O.id,O)}foreignEntityId=this.field("foreignEntityId");source=this.field("foreignEntitySource");storedForId=this.field("storedForId");storedForAuthEntity=this.field("storedForAuthEntity");createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");async metadata(){return(await this.detail.get()).metadata}}function i1({login:$,...O}){return{...O,login:$??void 0}}class V0{client;constructor($){this.client=$}byId($){return jO.byId(this.client,$)}async bySource($,O){return jO.fromRecord(this.client,G(await this.client.storage.getForeignEntityBySource({path:{source:$,foreign_entity_id:O}})))}async githubPullRequestFacets(){let{repositories:$,authors:O,assignees:j,labels:x}=G(await this.client.storage.getGithubPullRequestFacets());return{repositories:$,authors:O.map(i1),assignees:j.map(i1),labels:x.map(({color:S,...K})=>({...K,color:S??void 0}))}}}class r${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new r$($,O)}async detail(){let O=(await this.form.schema()).sections.flatMap((j)=>j.kind==="questions"?j.questions:[]).find((j)=>j.id===this.id);if(!O)throw new E(`question ${this.id} is not on form ${this.form.id}`);return O}async title(){return(await this.detail()).title}async column(){return A$.byId(await this.form.table(),(await this.detail()).column)}async options(){return(await this.detail()).options.map(($)=>UO.byId(this,$.id))}}class UO{question;id;constructor($,O){this.question=$;this.id=O}static byId($,O){return new UO($,O)}async detail(){let $=(await this.question.detail()).options.find((O)=>O.id===this.id);if(!$)throw new E(`option ${this.id} is not on question ${this.question.id}`);return $}async label(){return(await this.detail()).label}async color(){return(await this.detail()).color??void 0}}class RO{form;id;detail;constructor($,O,j){this.form=$;this.id=O;this.detail=new B$(()=>this.load(),j)}async load(){let $=await this.form.myResponse();if($.response.id!==this.id)throw new E(`response ${this.id} is not your current response`);return $}static byId($,O,j){return new RO($,O,j)}async status(){return(await this.detail.get()).status}async row(){return(await this.detail.get()).row}async answers(){return(await this.detail.get()).answers}async booking(){return(await this.detail.get()).booking}async refresh(){let $=await this.load();return this.detail=new B$(()=>this.load(),$),this}}class p${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new p$($,O)}async detail(){let $=(await this.form.schema()).sections.find((O)=>O.id===this.id);if(!$)throw new E(`section ${this.id} is not on form ${this.form.id}`);return $}async title(){return(await this.detail()).title}async questions(){let $=await this.detail();return $.kind==="questions"?$.questions.map((O)=>r$.byId(this.form,O.id)):[]}}class Aj{entityType;id;constructor($,O){this.entityType=$;this.id=O}static byId($,O){return new Aj($,O)}}class y$ extends P{async fetch(){return G(await this.client.storage.getForm({path:{id:this.id}}))}static byId($,O){return new y$($,O)}static async create($,O){let j=G(await $.storage.createForm({body:{name:O.name,source:O.table?{kind:"table",databaseId:O.table.database.id,tableId:O.table.id}:{kind:"new"}}}));return new y$($,j.form.id,j)}static async list($,O){if(!O)return G(await $.storage.listAccessibleForms()).map(({form:S})=>new y$($,S.id));return G(await $.storage.listForms({query:{databaseId:O.id}})).map((x)=>new y$($,x.id))}schema(){return this.detail.get()}name=this.mappedField("form",($)=>$.name);description=this.mappedField("form",($)=>$.description);owner=this.mappedField("form",($)=>M.byId(this.client,$.ownerId));database=this.mappedField("form",($)=>V$.byId(this.client,$.databaseId));table=this.mappedField("form",($)=>J$.byId(V$.byId(this.client,$.databaseId),$.tableId));audience=this.mappedField("form",($)=>$.audience);status=this.mappedField("form",($)=>$.status);closesAt=this.mappedField("form",($)=>$.closesAt??void 0);access=this.field("access");async sections(){return(await this.detail.get()).sections.map(($)=>p$.byId(this,$.id))}async questions(){return(await this.detail.get()).sections.flatMap(($)=>$.kind==="questions"?$.questions.map((O)=>r$.byId(this,O.id)):[])}async update($){return await this.mutate((O)=>O.storage.updateForm({path:{id:this.id},body:$})),this}assertOwns($){if($.form.id!==this.id)throw new f(`question or section does not belong to form ${this.id}`)}async replaceLayout($){let O=await this.table(),j=(Z)=>{if(Z.table.id!==O.id||Z.table.database.id!==O.database.id)throw new f(`column does not belong to form ${this.id}'s table`);return Z.id},x=(Z)=>({conjunction:Z.conjunction,conditions:Z.conditions.map((X)=>c(X).with({kind:"group"},(Y)=>({kind:"group",...x(Y)})).with({kind:"condition"},(Y)=>({kind:"condition",column:j(Y.column),test:c(Y.test).with({kind:"options"},(L)=>({...L,options:L.options.map((Q)=>Q.id)})).with({kind:"entities"},(L)=>({...L,entities:L.entities.map((Q)=>Q.id)})).with({kind:Z$.union("presence","text","number","date","checkbox")},(L)=>L).exhaustive()})).exhaustive())}),S={sections:$.map((Z)=>{if(Z.section)this.assertOwns(Z.section);let X={id:Z.section?.id??d$(),title:Z.title,description:Z.description??""};return c(Z).with({kind:"booking"},(Y)=>({...X,kind:"booking",target:Y.target})).with({kind:"gate"},(Y)=>({...X,kind:"gate",rules:x(Y.rules),message:Y.message})).with({kind:"questions"},(Y)=>({...X,kind:"questions",questions:Y.questions.map((L)=>{if(L.question)this.assertOwns(L.question);return{id:L.question?.id??d$(),column:j(L.column),helpText:L.helpText??"",required:L.required??!1,widget:L.widget??null}})})).exhaustive()})},K=await this.mutate((Z)=>Z.storage.putFormLayout({path:{id:this.id},body:S}));return{form:this,publicationError:K.publicationError}}wireAnswers($){return $.map(({question:O,value:j})=>{this.assertOwns(O);let x=c(j).with({type:"rows"},(S)=>({type:"rows",value:S.value.map((K)=>K.id)})).with({type:"options"},(S)=>({type:"options",value:S.value.map((K)=>{if(K.question.id!==O.id||K.question.form.id!==this.id)throw new f("option does not belong to the answered question");return{id:K.id}})})).with({type:"entities"},(S)=>({type:"entities",value:S.value.map(({entityType:K,entity:Z})=>({entityType:K,entityId:Z.id}))})).with({type:Z$.union("text","number","boolean","date","link","clear")},(S)=>S).exhaustive();return{question:O.id,value:x}})}unlockedBooking($){return $?{...$,section:p$.byId(this,$.section)}:void 0}async outcome($,O){return c($).with({outcome:"stopped"},(j)=>({...j,section:p$.byId(this,j.section)})).with({outcome:"submitted"},async(j)=>{let x=F$.byId(await this.table(),j.row),S=this.unlockedBooking(j.booking);return{outcome:"submitted",response:RO.byId(this,j.response,{status:"submitted",row:x,answers:O,booking:S}),row:x,...S?{booking:S}:{}}}).exhaustive()}async submit($){let O={answers:this.wireAnswers($)};return this.outcome(G(await this.client.storage.submitFormResponse({path:{id:this.id},body:O})),$)}async editResponse($){let O={answers:this.wireAnswers($)};return this.outcome(G(await this.client.storage.editMyFormResponse({path:{id:this.id},body:O})),$)}async myResponse(){let $=G(await this.client.storage.getMyFormResponse({path:{id:this.id}})),O=await this.table(),j=await Promise.all($.answers.map(async(K)=>{let Z=r$.byId(this,K.question),X=await c(K.value).with({type:"options"},(Y)=>({type:"options",value:Y.value.map((L)=>{if(!("id"in L))throw new f("stored form answers must reference options by id");return UO.byId(Z,L.id)})})).with({type:"entities"},(Y)=>({type:"entities",value:Y.value.map((L)=>({entityType:L.entityType,entity:Aj.byId(L.entityType,L.entityId)}))})).with({type:"rows"},async(Y)=>{let L=await Z.detail();if(L.kind.type!=="relation")throw new f("row answer requires a relation question");let Q=J$.byId(V$.byId(this.client,L.kind.database),L.kind.table);return{type:"rows",value:Y.value.map((J)=>F$.byId(Q,J))}}).with({type:Z$.union("text","number","boolean","date","link","clear")},(Y)=>Y).exhaustive(()=>{throw new f(`answer to question ${Z.id} has a type this SDK doesn't know`)});return{question:Z,value:X}})),x=$.response.row?F$.byId(O,$.response.row):void 0,S=this.unlockedBooking($.booking);return{...S?{booking:S}:{},response:RO.byId(this,$.response.id,{status:$.response.status,row:x,answers:j,booking:S}),status:$.response.status,stoppedAtSection:$.response.stoppedAtSection?p$.byId(this,$.response.stoppedAtSection):void 0,row:x,submittedAt:$.response.submittedAt,updatedAt:$.response.updatedAt,answers:j}}async responseSummary(){let $=G(await this.client.storage.getFormResponseSummary({path:{id:this.id}}));return{...$,stoppedBySection:$.stoppedBySection.map((O)=>({section:p$.byId(this,O.section),count:O.count}))}}async tally(){return G(await this.client.storage.getFormTally({path:{id:this.id}})).questions.map((O)=>{let j=r$.byId(this,O.question);return{question:j,responses:O.responses,buckets:O.buckets.flatMap((x)=>c(x.value).with({kind:"option"},(S)=>[{count:x.count,value:{kind:"option",option:UO.byId(j,S.option)}}]).with({kind:"checkbox"},(S)=>[{count:x.count,value:S}]).exhaustive((S)=>{return console.warn("macro sdk: unknown form tally bucket",S),[]}))}})}async sharePermissions(){return G(await this.client.storage.getFormPermissions({path:{id:this.id}}))}updateSharePermissions($){return this.mutate((O)=>O.storage.updateFormPermissions({path:{id:this.id},body:$}))}webUrl(){return`${this.client.webAppUrl}/app/form/${this.id}`}respondUrl(){return`${this.client.webAppUrl}/app/form/${this.id}/respond`}}class B0{client;constructor($){this.client=$}byId($){return y$.byId(this.client,$)}create($){return y$.create(this.client,$)}list($){return y$.list(this.client,$)}}class DO extends P{static byId($,O){return new DO($,O)}async fetch(){return G(await this.client.storage.getGithubPullRequest({path:{id:this.id}}))}title=this.field("title");url=this.field("url");status=this.field("status");async changes(){let $=G(await this.client.storage.getGithubPullRequestChanges({path:{id:this.id}}));return{changeset:$.changeset?new W0(this.client,this,$.changeset):void 0,error:$.error??void 0}}}class W0{client;pullRequest;record;constructor($,O,j){this.client=$;this.pullRequest=O;this.record=j}get id(){return this.record.id}async patch(){return G(await this.client.storage.getGithubPullRequestChangesPatch({path:{id:this.pullRequest.id},query:{changeset:this.id}})).patch}toJSON(){return{pullRequestId:this.pullRequest.id,...this.record}}}class L0{client;constructor($){this.client=$}byId($){return DO.byId(this.client,$)}forEntity($){return DO.byId(this.client,$.id)}}class _O extends P{static byId($,O){return new _O($,O)}async fetch(){return G(await this.client.storage.getHarnessPairing({path:{code:this.id}}))}name=this.field("requested_name");expiresAt=this.field("expires_at");async approve($){let O={name:$?.name,team_id:$?.team?.id,allow_permission_bypass:$?.allowPermissionBypass};return W$.from(this.client,await this.mutate((j)=>j.storage.approveHarnessPairing({path:{code:this.id},body:O})))}}class $j{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new $j($,O)}async claim($){let O=G(await this.client.storage.claimHarnessPairing({path:{pairing_id:this.id},body:{device_secret:$}}));return"harness"in O?{harness:W$.from(this.client,O.harness),token:O.token}:void 0}toJSON(){return{id:this.id}}}class N0{client;constructor($){this.client=$}byId($){return W$.byId(this.client,$)}async list(){return G(await this.client.storage.listHarnesses()).map(($)=>W$.from(this.client,$))}async me(){return W$.from(this.client,G(await this.client.storage.getSelfHarness()))}async deleteSelf(){G(await this.client.storage.deleteSelfHarness())}async agents(){return G(await this.client.storage.listHarnessAgents()).map(($)=>I$.byId(this.client,$.bot_id))}async sessions(){return G(await this.client.storage.listHarnessSessions()).map(($)=>i.byId(this.client,$.session_id))}pairing($){return _O.byId(this.client,$)}async createPairing($){let O=G(await this.client.storage.createHarnessPairing({body:$}));return{pairing:_O.byId(this.client,O.code),device:$j.byId(this.client,O.pairing_id),deviceSecret:O.device_secret,expiresAt:O.expires_at,pollIntervalSeconds:O.poll_interval_seconds}}}var V7="00000001-0000-0000-0000-000000000002",B7="00000001-0000-0000-0002-000000000004";function W7($){let O=$.match(/^https:\/\/github\.com\/([^/]+)\/([^/]+)\/pull\/([1-9][0-9]*)\/?(?:[?#].*)?$/i);if(!O)throw Error(`Expected a GitHub pull request URL like https://github.com/owner/repo/pull/1, got ${$}`);return`${O[1]}/${O[2]}/pull/${O[3]}`}class _$ extends w{static byId($,O){return new _$($,O)}static async create($,O){let{documentId:j}=G(await $.storage.createTaskHandler({body:{taskName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null,teamId:O.team?.id??null,shareWithTeam:O.shareWithTeam??!0}}));return new _$($,j)}static async forPullRequest($,O){let j=W7(O),{pullRequests:x}=G(await $.storage.getGithubPullRequestTasks({body:{githubKeys:[j]}}));return(x[0]?.taskIds??[]).map((S)=>new _$($,S))}async completed(){let{subType:$}=await this.detail.get();if($!=="task")return;let j=(await this.properties()).find((x)=>x.definition.id===V7)?.value;return j?.type==="SelectOption"&&j.value.includes(B7)}webUrl(){return`${this.client.webAppUrl}/app/task/${this.id}`}static search=x$({filters:{document_filters:{sub_types:["task"],task_filters:{}}},type:"document",make:($,O)=>new _$($,O.document_id)})}class xO extends P{access=new o(this.client,"initiative",this);static byId($,O){return new xO($,O)}static from($,O){return new xO($,O.id,O)}async fetch(){return G(await this.client.storage.getInitiative({path:{initiative_id:this.id}}))}name=this.field("name");owner=this.mappedField("ownerId",($)=>M.byId(this.client,$));members=this.mappedField("memberIds",($)=>$.map((O)=>M.byId(this.client,O)));tasks=this.mappedField("taskIds",($)=>$.map((O)=>_$.byId(this.client,O)));accessLevel=this.field("userAccessLevel");sharePermissions=this.field("sharePermission");async update($){await this.mutate((O)=>O.storage.updateInitiative({path:{initiative_id:this.id},body:{name:$.name,memberIds:$.members?.map((j)=>j.id),sharePermission:$.sharePermission?i$($.sharePermission):void 0}}))}async delete(){await this.mutate(($)=>$.storage.deleteInitiative({path:{initiative_id:this.id}}))}}class U0{client;constructor($){this.client=$}byId($){return xO.byId(this.client,$)}async list(){return G(await this.client.storage.listInitiatives()).initiatives.map(($)=>xO.byId(this.client,$.id))}async create($){return xO.from(this.client,G(await this.client.storage.createInitiative({body:{name:$.name,description:$.description,memberIds:$.members?.map((O)=>O.id),shareWithTeam:$.shareWithTeam,propertyValues:$.propertyValues}})))}}class z0{client;constructor($){this.client=$}byId($){return H$.byId(this.client,$)}async create($){return H$.from(this.client,G(await this.client.storage.meetingCreate({body:$})))}async list(){return G(await this.client.storage.meetingList()).meetings.map(($)=>H$.from(this.client,$))}async active(){return G(await this.client.storage.meetingListActive()).meetings.map(($)=>H$.from(this.client,$))}async lookup($){return H$.from(this.client,G(await this.client.storage.meetingLookup({path:{token:$}})))}}class zO extends P{async fetch(){return G(await this.client.notification.getTypedNotificationById({path:{notification_id:this.id}}))}static byId($,O){return new zO($,O)}static from($,O){return new zO($,O.id,O)}static list($,O){return u(async(j)=>{let x=G(await $.notification.listTypedNotifications({query:{...O?.pageSize?{limit:O.pageSize}:{},...O?.states!==void 0?{states:O.states.join(",")}:{},...j?{cursor:j}:{}}}));return{items:x.items.map((S)=>zO.from($,S)),nextCursor:x.next_cursor}})}type=this.field("notification_event_type");createdAt=this.field("created_at");updatedAt=this.field("updated_at");state=this.field("state");done=this.mappedField("state",($)=>$==="done");sent=this.field("sent");viewedAt=this.field("viewed_at");deletedAt=this.field("deleted_at");owner=this.mappedField("owner_id",($)=>M.byId(this.client,$));sender=this.mappedField("sender_id",($)=>$?M.byId(this.client,$):void 0);metadata=this.field("notification_metadata");async seen(){return await this.state()!=="unseen"}async markSeen(){await this.mutate(($)=>$.notification.bulkMarkNotificationsSeen({body:{notificationIds:[this.id]}}))}async markDone(){await this.mutate(($)=>$.notification.bulkMarkNotificationsDone({body:{notificationIds:[this.id]}}))}async markUndone(){await this.mutate(($)=>$.notification.bulkMarkNotificationsUndone({body:{notificationIds:[this.id]}}))}async delete(){await this.mutate(($)=>$.notification.deleteUserNotificationV2({path:{notification_id:this.id}}))}}class I0{client;constructor($){this.client=$}byId($){return zO.byId(this.client,$)}list($){return zO.list(this.client,$)}async markSeen($){G(await this.client.notification.bulkMarkNotificationsSeen({body:{notificationIds:$}}))}async markDone($){G(await this.client.notification.bulkMarkNotificationsDone({body:{notificationIds:$}}))}async delete($){G(await this.client.notification.bulkDeleteUserNotificationsV2({body:{notificationIds:$}}))}async preferences(){return G(await this.client.notification.getNotificationTypePreferences())}async enableType($){G(await this.client.notification.enableNotificationType({path:{notification_event_type:$}}))}async disableType($){G(await this.client.notification.disableNotificationType({path:{notification_event_type:$}}))}}class T0{client;constructor($){this.client=$}async list(){let{data:$}=G(await this.client.storage.getPinsHandler({}));return $?.recent??[]}async add($,O){G(await this.client.storage.addPinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType,pinIndex:O.index}}))}async remove($){G(await this.client.storage.removePinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType}}))}async reorder($){G(await this.client.storage.reorderPinsHandler({body:$}))}}class H0{client;constructor($){this.client=$}byId($){return n.byId(this.client,$)}create($){return n.create(this.client,$)}search($,O){return n.search(this.client,$,O)}}class CO{client;definitionId;id;record;constructor($,O,j,x){this.client=$;this.definitionId=O;this.id=j;this.record=x}static from($,O,j){return new CO($,O,j.id,j)}get value(){return this.record.value}get color(){return this.record.color??void 0}get displayOrder(){return this.record.display_order}get createdAt(){return this.record.created_at}get updatedAt(){return this.record.updated_at}async update($){return this.record=G(await this.client.properties.updatePropertyOption({path:{definition_id:this.definitionId,option_id:this.id},body:$})),this}async delete(){G(await this.client.properties.deletePropertyOption({path:{definition_id:this.definitionId,option_id:this.id}}))}}class SO{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new B$(()=>this.fetch(),j)}async fetch(){return G(await this.client.properties.getPropertyDefinition({path:{definition_id:this.id}}))}static async create($,O){let j=G(await $.properties.createPropertyDefinition({body:{display_name:O.displayName,scope:O.scope,data_type:O.dataType}}));return new SO($,j.id,j)}static byId($,O){return new SO($,O)}static fromRecord($,O){return new SO($,O.id,O)}get displayName(){return this.detail.get().then(($)=>$.display_name)}get dataType(){return this.detail.get().then(($)=>$.data_type)}get owner(){return this.detail.get().then(($)=>$.owner)}get isSystem(){return this.detail.get().then(($)=>$.is_system)}get isMultiSelect(){return this.detail.get().then(($)=>$.is_multi_select)}get createdAt(){return this.detail.get().then(($)=>$.created_at)}get updatedAt(){return this.detail.get().then(($)=>$.updated_at)}async delete(){return G(await this.client.properties.deletePropertyDefinition({path:{definition_id:this.id}}))}async options(){return G(await this.client.properties.getPropertyOptions({path:{definition_id:this.id}})).map((O)=>CO.from(this.client,this.id,O))}async addOption($){let O=G(await this.client.properties.addPropertyOption({path:{definition_id:this.id},body:$}));return CO.from(this.client,this.id,O)}async updateOption($,O){let j=G(await this.client.properties.updatePropertyOption({path:{definition_id:this.id,option_id:$.id},body:O}));return CO.from(this.client,this.id,j)}async deleteOption($){return G(await this.client.properties.deletePropertyOption({path:{definition_id:this.id,option_id:$.id}}))}}class R0{client;constructor($){this.client=$}async list($){return G(await this.client.properties.listProperties({query:{scope:$?.scope??"all",...$?.forEntityType!==void 0?{for_entity_type:$.forEntityType}:{}}})).map((j)=>{let x="definition"in j?j.definition:j;return SO.fromRecord(this.client,x)})}create($){return SO.create(this.client,$)}definition($){return SO.byId(this.client,$)}async bulkEntityProperties($){return G(await this.client.properties.getBulkEntityProperties({body:$}))}async updateEntityPropertyOptions($,O){return G(await this.client.properties.bulkUpdateEntitiesPropertyOptions({body:{entities:$.map((x)=>x.propertyReference()),property_id:O.property.id,...O.add?{add_option_ids:O.add.map((x)=>x.id)}:{},...O.remove?{remove_option_ids:O.remove.map((x)=>x.id)}:{}}})).results}async addEntityPropertyOption($){return G(await this.client.properties.addEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async removeEntityPropertyOption($){return G(await this.client.properties.removeEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async tags(){return G(await this.client.properties.listTags({}))}}function D0($){return c($).with({type:"cron"},(O)=>O).with({type:"events"},(O)=>({type:"events",filters:O.filters.map(({entities:j,...x})=>({...x,ids:j?.map((S)=>S.entity.id)}))})).exhaustive()}function L7($){return c($).with({type:"multiple"},(O)=>({type:"multiple",triggers:O.triggers.map(D0)})).with({type:"cron"},D0).with({type:"events"},D0).exhaustive()}class ZO extends P{static byId($,O){return new ZO($,O)}static from($,O){if(!O.id)throw Error("Routine response has no id");return new ZO($,O.id,O)}async fetch(){return G(await this.client.scheduledAction.getScheduledAction({path:{id:this.id}}))}name=this.field("name");trigger=this.field("trigger");enabled=this.field("enabled");runVisibility=this.field("run_visibility");nextRunAt=this.field("next_run_at");revision=this.field("configuration_revision");owner=this.mappedField("owner",($)=>M.byId(this.client,$));async update($){await this.mutate((O)=>O.scheduledAction.updateScheduledAction({path:{id:this.id},body:C0($)}))}async setEnabled($){await this.mutate((O)=>O.scheduledAction.setScheduledActionEnabled({path:{id:this.id},body:{enabled:$}}))}async execute(){let $=G(await this.client.scheduledAction.executeScheduledActionNow({path:{id:this.id}}));if($.resource)return c($.resource).with({type:"agent"},(O)=>i.byId(this.client,O.id)).with({type:"chat"},(O)=>K$.byId(this.client,O.id)).exhaustive();return $.chat_id?K$.byId(this.client,$.chat_id):void 0}async history(){return G(await this.client.scheduledAction.listScheduledActionHistory({path:{id:this.id}})).map(($)=>new _0(this,$))}async delete(){await this.mutate(($)=>$.scheduledAction.deleteScheduledAction({path:{id:this.id}}))}}class _0{routine;record;constructor($,O){this.routine=$;this.record=O}get id(){return this.record.id??void 0}toJSON(){return{routine:this.routine.id,...this.record}}}function C0($){let O={prompt:$.prompt,user_prompt:$.userPrompt,model:$.model,agent:$.agent?{bot_id:$.agent.id}:void 0};return{kind:"Agent",name:$.name,enabled:$.enabled,run_visibility:$.runVisibility,trigger:L7($.trigger),task:{...O}}}class M0{client;constructor($){this.client=$}byId($){return ZO.byId(this.client,$)}async create($){return ZO.from(this.client,G(await this.client.scheduledAction.createScheduledAction({body:{...C0($),enabled:$.enabled??!0}})))}async list($){return G(await this.client.scheduledAction.listScheduledActions({query:{include_events:$?.includeEvents}})).map((O)=>ZO.from(this.client,O))}}class P0{client;constructor($){this.client=$}byId($){return _$.byId(this.client,$)}create($){return _$.create(this.client,$)}forPullRequest($){return _$.forPullRequest(this.client,$)}search($,O){return _$.search(this.client,$,O)}}class A0{client;constructor($){this.client=$}byId($){return S$.byId(this.client,$)}current(){return S$.current(this.client)}list(){return S$.list(this.client)}}class F0{client;constructor($){this.client=$}async get($){return G(await this.client.unfurl.getUnfurl({query:{url:$}}))}async bulk($){return G(await this.client.unfurl.getUnfurlBulk({body:{url_list:$}}))}}class E0{client;constructor($){this.client=$}byId($){return M.byId(this.client,$)}me(){return M.me(this.client)}async search($){let O=$.trim().toLocaleLowerCase();if(!O)throw Error("A person search needs a name or email.");let j=await this.client.contacts.getContacts();if(j.response?.status===404)return[];let{contacts:x}=G(j),S=[...new Set(x)],K=[];for(let Z=0;Z<S.length;Z+=100){let X=S.slice(Z,Z+100),{names:Y}=G(await this.client.auth.getUserNamesWithEmail({body:{user_ids:X}})),L=new Map(Y.map((Q)=>[Q.id,Q]));for(let Q of X){let J=L.get(Q)??{id:Q};if(`${[J.first_name,J.last_name].filter(Boolean).join(" ")} ${Q}`.toLocaleLowerCase().includes(O))K.push(M.fromName(this.client,J))}}return K}}class XO extends P{signingSecret;constructor($,O,j,x){super($,O,j);this.signingSecret=x}async fetch(){return G(await this.client.storage.getWebhook({path:{webhook_id:this.id}}))}static async create($,O){let j=G(await $.storage.createWebhook({body:{endpoint_url:O.url,namespace:O.namespace,name:O.name,filters:O.filters,scope:O.scope??"user",...O.headers!==void 0?{headers:O.headers}:{}}}));return new XO($,j.id,j,j.signing_secret)}static byId($,O){return new XO($,O)}static fromRecord($,O){return new XO($,O.id,O)}name=this.field("name");namespace=this.field("namespace");endpointUrl=this.field("endpoint_url");status=this.field("status");isValid=this.field("is_valid");filters=this.field("filters");createdAt=this.field("created_at");workspaceId=this.field("workspace_id");createdBy=this.mappedField("created_by_user_id",($)=>M.byId(this.client,$));async scope(){let $=await this.detail.get();return $.workspace_id===$.created_by_user_id?"user":"team"}async update($){await this.mutate((O)=>O.storage.patchWebhook({path:{webhook_id:this.id},body:$}))}async rename($){await this.update({name:$})}async setUrl($){await this.update({endpoint_url:$})}async setFilters($){await this.update({filters:$})}async pause(){await this.update({status:"paused"})}async resume(){await this.update({status:"active"})}async delete(){await this.mutate(($)=>$.storage.deleteWebhook({path:{webhook_id:this.id}}))}async validate(){return this.mutate(($)=>$.storage.validateWebhook({path:{webhook_id:this.id}}))}}class w0{client;constructor($){this.client=$}create($){return XO.create(this.client,$)}byId($){return XO.byId(this.client,$)}async list(){let{webhooks:$}=G(await this.client.storage.listWebhooks());return $.map((O)=>XO.fromRecord(this.client,O))}}class MO extends P{static byId($,O){return new MO($,O)}static from($,O){return new MO($,O.id,O)}async fetch(){let{account:$}=G(await this.client.storage.linkedAccount());if($?.id!==this.id)throw new E("WhatsApp account is not available");return $}state=this.field("state");identity=this.field("identityJid");owner=this.mappedField("userId",($)=>M.byId(this.client,$));async refresh(){return this.detail.clear(),await this.detail.get(),this}}class C$ extends P{group;constructor($,O,j,x){super($,j,x);this.group=O}static byId($,O,j){return new C$($,O,j)}static from($,O,j){return new C$($,O,j.id,j)}async fetch(){return G(await this.client.storage.whatsappGroupMessage({path:{group_id:this.group.id,message_id:this.id}}))}body=this.field("body");sender=this.field("sender");sentAt=this.field("sentAt");editedAt=this.field("editedAt");deleted=this.field("deleted");reactions=this.field("reactions");deliveryState=this.field("deliveryState");kind=this.field("kind");forwarded=this.field("forwarded");viewOnce=this.field("viewOnce");mentions=this.field("mentions");rich=this.field("rich");replyTo=this.mappedField("replyTo",($)=>$?C$.byId(this.client,this.group,$):void 0);attachments=this.mappedField("attachments",($)=>$.map((O)=>({ordinal:O.ordinal,state:O.state,fileName:O.fileName,mime:O.mime,size:O.size,width:O.width??void 0,height:O.height??void 0,durationSeconds:O.durationSeconds??void 0,presentation:O.presentation??void 0,document:O.documentId?w.byId(this.client,O.documentId):void 0})))}class KO{group;id;record;constructor($,O,j){this.group=$;this.id=O;this.record=j}static byId($,O){return new KO($,O)}static from($,O){return new KO($,O.jid,O)}get displayName(){return this.record?.displayName??void 0}get mentionToken(){return this.id.split("@")[0]??this.id}get admin(){return this.record?.admin}toJSON(){return{id:this.id,group:this.group.id,displayName:this.displayName,admin:this.admin}}}class YO{id;group;filename;kind;constructor($,O,j,x){this.id=$;this.group=O;this.filename=j;this.kind=x}static byId($,O){return new YO(O,$)}static from($,O){return new YO(O.uploadId,$,O.filename,O.kind)}toJSON(){return{id:this.id,group:this.group.id,filename:this.filename,kind:this.kind}}}class GO extends P{group;constructor($,O,j,x){super($,j,x);this.group=O}static byId($,O,j){return new GO($,O,j)}static from($,O,j){return new GO($,O,j.id,j)}async fetch(){let O=G(await this.client.storage.linkedDelivery({path:{group_id:this.group.id},body:[this.id]})).find((j)=>j.id===this.id);if(!O)throw new E("WhatsApp send is not available");return O}state=this.field("state");errorCode=this.field("errorCode");createdAt=this.field("createdAt");message=this.mappedField("messageId",($)=>$?C$.byId(this.client,this.group,$):void 0);async request(){let{payload:$}=await this.detail.get(),O=$.message,j=c(O).returnType().with({type:"media"},(x)=>({type:"media",upload:YO.byId(this.group,x.uploadId),caption:x.caption??void 0})).with({type:"mutation"},(x)=>({type:"mutation",message:C$.byId(this.client,this.group,x.messageId),operation:x.operation,text:x.text??void 0})).with({type:"text"},(x)=>({type:"text",text:x.text,mentions:(x.mentions??[]).map((S)=>KO.byId(this.group,S))})).exhaustive();return{idempotencyKey:$.idempotencyKey,message:j,replyTo:$.replyTo?C$.byId(this.client,this.group,$.replyTo):void 0}}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class v$ extends z${entityType="whatsapp_group";static byId($,O){return new v$($,O)}async fetch(){return G(await this.client.storage.whatsappGroup({path:{group_id:this.id}}))}name=this.field("name");kind=this.field("kind");canSend=this.field("canSend");sendReason=this.field("sendReason");sendingIdentity=this.field("sendingIdentity");unreadCount=this.field("unreadCount");backfill=this.field("backfill");limits=this.field("limits");roster=this.field("roster");participants=this.mappedField("roster",($)=>($?.participants??[]).map((O)=>KO.from(this,O)));disappearingSeconds=this.field("disappearingSeconds");community=this.mappedField("community",($)=>$?q0(this.client,$):void 0);owner=this.mappedField("userId",($)=>M.byId(this.client,$));async*messages($={}){yield*u(async(O)=>{let j=G(await this.client.storage.whatsappGroupMessages({path:{group_id:this.id},query:{before:O,limit:$.limit}}));return{items:j.messages.map((x)=>C$.from(this.client,this,x)),nextCursor:j.nextCursor}})}async markRead($){this.assertGroup($.group),await this.mutate((O)=>O.storage.whatsappGroupRead({path:{group_id:this.id},body:{messageId:$.id}}))}async permissions(){return G(await this.client.storage.whatsappGroupPermissions({path:{group_id:this.id}}))}async updatePermissions($){await this.mutate((O)=>O.storage.whatsappGroupUpdatePermissions({path:{group_id:this.id},body:$}))}async detach(){await this.mutate(($)=>$.storage.linkedDetach({path:{group_id:this.id}}))}async upload($){let O=G(await this.client.storage.linkedUpload({path:{group_id:this.id},body:{file:$}}));return YO.from(this,O)}async reply($,O){if(O.replyTo)this.assertGroup(O.replyTo.group);let j=c($).returnType().with({type:"text"},(S)=>{let K=S.mentions??[];for(let Z of K)this.assertGroup(Z.group);return{type:"text",text:S.text,mentions:K.map((Z)=>Z.id)}}).with({type:"media"},(S)=>{return this.assertGroup(S.upload.group),{type:"media",uploadId:S.upload.id,caption:S.caption}}).with({type:"mutation"},(S)=>{return this.assertGroup(S.message.group),{type:"mutation",messageId:S.message.id,operation:S.operation,text:S.text}}).exhaustive(),x=await this.mutate((S)=>S.storage.linkedReply({path:{group_id:this.id},body:{idempotencyKey:O.idempotencyKey,message:j,replyTo:O.replyTo?.id}}));return GO.from(this.client,this,x)}async sends(){return G(await this.client.storage.whatsappGroupSends({path:{group_id:this.id}})).map(($)=>GO.from(this.client,this,$))}async delivery($){for(let O of $)this.assertGroup(O.group);return G(await this.client.storage.linkedDelivery({path:{group_id:this.id},body:$.map((O)=>O.id)})).map((O)=>GO.from(this.client,this,O))}async messageAttachments($){for(let O of $)this.assertGroup(O.group);return G(await this.client.storage.linkedMessageAttachments({path:{group_id:this.id},body:$.map((O)=>O.id)})).map((O)=>({message:C$.byId(this.client,this,O.messageId),attachments:O.linkedAttachments.map((j)=>({ordinal:j.ordinal,state:j.state,fileName:j.fileName,mime:j.mime,size:j.size,document:j.documentId?w.byId(this.client,j.documentId):void 0}))}))}async refresh(){return this.detail.clear(),await this.detail.get(),this}assertGroup($){if($.id!==this.id)throw Error("WhatsApp reference belongs to another group")}}function q0($,O){return{chat:IO.byId($,O.id),name:O.name,announcements:O.announcements}}class IO extends P{static byId($,O){return new IO($,O)}static from($,O){return new IO($,O.jid,O)}async fetch(){let{chats:$}=G(await this.client.storage.linkedChats()),O=$.find((j)=>j.jid===this.id);if(!O)throw new E("WhatsApp chat is not available");return O}kind=this.field("kind");name=this.field("name");lastActivityAt=this.field("lastActivityAt");archived=this.field("archived");pinned=this.field("pinned");canAdd=this.field("canAdd");cannotAddReason=this.field("cannotAddReason");community=this.mappedField("community",($)=>$?q0(this.client,$):void 0);group=this.mappedField("group",($)=>$?v$.byId(this.client,$.id):void 0);shared=this.mappedField("shared",($)=>$?v$.byId(this.client,$.id):void 0);async adopt(){let $=await this.mutate((O)=>O.storage.linkedAdopt({body:{groupJid:this.id}}));return v$.byId(this.client,$.groupId)}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class f0{client;constructor($){this.client=$}async account(){let{account:$}=G(await this.client.storage.linkedAccount());return $?MO.from(this.client,$):void 0}async groups(){return G(await this.client.storage.whatsappGroups()).map(($)=>v$.byId(this.client,$.id))}async chats(){return G(await this.client.storage.linkedChats()).chats.map(($)=>IO.from(this.client,$))}byId($){return v$.byId(this.client,$)}}function b0($){if("properties"in $.data)return $.data.properties;if($.tag==="calendarEvent")return $.data.extra.properties;return[]}function n1($,O,j){let x=[];for(let S of b0(O)){if(S.definition.data_type!=="TAG"||S.value?.type!=="SelectOption")continue;for(let K of S.value.value){let Z=j.get(K);if(Z&&!x.some((X)=>X.label===Z.label&&X.scope===Z.scope))x.push(Z)}}switch(O.tag){case"document":return{type:"document",id:O.data.id,entity:w.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name,fileType:O.data.fileType,subType:O.data.subType?.type};case"chat":return{type:"ai_chat",id:O.data.id,entity:K$.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name};case"project":return{type:"project",id:O.data.id,entity:n.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name};case"emailThread":return{type:"email",id:O.data.id,entity:R$.byId($,O.data.id),snapshot:O,tags:x,subject:O.data.name,snippet:O.data.snippet,senderName:O.data.senderName,senderEmail:O.data.senderEmail,inboxVisible:O.data.inboxVisible,isRead:O.data.isRead,isDraft:O.data.isDraft};case"channel":return{type:"channel",id:O.data.channel.id,entity:b.byId($,O.data.channel.id),snapshot:O,tags:x,name:O.data.channel.name};case"channelThread":return{type:"channel_thread",id:O.data.id,entity:new h$($,O.data.channel_id,O.data.id),snapshot:O,tags:x,channelId:O.data.channel_id};case"call":return{type:"call",id:O.data.callId,entity:Q$.byId($,O.data.callId),snapshot:O,tags:x,createdBy:O.data.createdBy};case"calendarEvent":return{type:"calendar_event",id:O.data.id,entity:$$.byId($,O.data.id),snapshot:O,tags:x,title:O.data.title,status:O.data.status,location:O.data.location,conferenceUrl:O.data.conferenceUrl,conferenceProvider:O.data.conferenceProvider,time:O.data.time};case"foreignEntity":return{type:"foreign_entity",id:O.data.id,entity:jO.byId($,O.data.id),snapshot:O,tags:x,foreignEntityId:O.data.foreignEntityId,foreignEntitySource:O.data.foreignEntitySource,metadata:O.data.metadata};default:throw Error(`Unexpected workspace entity type: ${O.tag}`)}}var s1="00000000-0000-0000-0000-000000000000",k0={document:["df","id"],project:["pf","pid"],ai_chat:["cf","cid"],email:["ef","ThreadId"],channel:["chanf","ChannelId"],channel_thread:["cthf","ThreadId"],call:["callf","CallId"],calendar_event:["calf","id"],foreign_entity:["fef","id"]},Fj=($)=>$.replace(/[A-Z]/g,(O)=>O.toLowerCase()),t1=($,O)=>$==null?O:{"&":[$,O]};function g0($,O){if(!$||typeof $!=="object"||Array.isArray($))throw Error(`Invalid workspace ${O}: expected a filter expression.`);let j=Object.entries($),x=j[0];if(j.length!==1||x===void 0)throw Error(`Invalid workspace ${O}: use exactly one of l, &, |, !.`);let[S,K]=x;if(S==="l")return;if(S==="!"){g0(K,`${O}.!`);return}if(S!=="&"&&S!=="|")throw Error(`Invalid workspace ${O}: use l, &, | or !.`);if(!Array.isArray(K)||K.length!==2)throw Error(`Invalid workspace ${O}.${S}: expected exactly two expressions. Use {l: {...}} for a single condition; nest binary operators for three or more.`);K.forEach((Z,X)=>{g0(Z,`${O}.${S}[${X}]`)})}class Ej{client;tagSets;constructor($){this.client=$}sets(){return this.tagSets??=this.client.properties.listTags({}).then(G),this.tagSets}async tagMap(){let $=new Map;for(let O of await this.sets())for(let j of O.options)if(j.value.type==="string")$.set(j.id,{label:j.value.value,scope:O.scope==="user"?"personal":"team"});return $}async body($){for(let[S,K,Z]of[["sortBy",$.sortBy,["recently_viewed","recently_updated","recently_created"]],["emailPreset",$.emailPreset,["signal"]],["tagsMatch",$.tagsMatch,["any","all"]]])if(K!==void 0&&!Z.includes(K))throw Error(`Invalid workspace ${S}: ${K}`);if($.includeTypes!==void 0&&(!Array.isArray($.includeTypes)||$.includeTypes.some((S)=>!Object.hasOwn(k0,S))))throw Error(`Invalid workspace includeTypes. Supported values: ${Object.keys(k0).join(", ")}. Tasks use document with df: {l: {dst: 'task'}}.`);for(let S of["df","pf","cf","ef","chanf","cthf","callf","fef","calf","propf"])if($[S]!=null)g0($[S],S);if($.tags?.some((S)=>S.scope!==void 0&&S.scope!=="personal"&&S.scope!=="team"))throw Error("Invalid workspace tag scope");if($.limit!==void 0&&!Number.isFinite($.limit))throw Error("Workspace limit must be finite");let O={df:$.df,pf:$.pf,cf:$.cf,ef:$.ef,chanf:$.chanf,cthf:$.cthf,callf:$.callf,fef:$.fef,calf:$.calf,propf:$.propf,ccf:{l:{id:s1}},favorites_only:$.favoritesOnly,expand:!0,limit:Math.max(1,Math.min(500,Math.trunc($.limit??50))),sort_method:$.sortBy==="recently_viewed"?"viewed_at":$.sortBy==="recently_created"?"created_at":"updated_at",sort_direction:"desc",emailView:$.emailView??"inbox"};if($.emailPreset==="signal")O.ef={"&":[{l:{Importance:!0}},{l:{Shared:"exclude"}}]};let j=$.inbox?.trim();if(j){let{links:S}=G(await this.client.email.listLinks()),K=S.filter((X)=>Fj(X.email_address)===Fj(j)),Z=K[0];if(!Z)throw Error(`No connected inbox matches "${j}". Connected inboxes: ${S.map((X)=>X.email_address).join(", ")}.`);if(K.length>1)throw Error(`Multiple connected inboxes match "${j}"; cannot pick one.`);O.ef=t1(O.ef,{l:{Owner:Z.id}})}let x=$.includeTypes??($.emailPreset==="signal"?["email"]:void 0);if(x?.length){for(let[S,[K,Z]]of Object.entries(k0))if(!x.includes(S))O[K]={l:{[Z]:s1}}}if($.tags?.length){let S=(await this.sets()).flatMap((Y)=>{let L=Y.definition;if(!L)return[];return Y.options.flatMap((Q)=>Q.value.type==="string"?[{id:Q.id,definitionId:L.id,label:Q.value.value,scope:Y.scope==="user"?"personal":"team"}]:[])}),K=new Map;for(let Y of $.tags){let L=S.filter((Q)=>Fj(Q.label)===Fj(Y.label.trim())&&(!Y.scope||Q.scope===Y.scope));if(!L.length)throw Error(`Unknown tag "${Y.label}". Available tags: ${S.map((Q)=>`${Q.label} (${Q.scope})`).join(", ")}.`);if($.tagsMatch==="all"&&L.length>1)throw Error(`Tag "${Y.label}" is ambiguous; specify personal or team scope.`);for(let Q of L)K.set(Q.id,Q)}let X=[...K.values()].map((Y)=>({l:{pd:Y.definitionId,v:{so:Y.id}}})).reduce((Y,L)=>Y===void 0?L:{[$.tagsMatch==="all"?"&":"|"]:[Y,L]},void 0);O.propf=t1(O.propf,X)}return O}}class y0{client;constructor($){this.client=$}async page($={}){let O=new Ej(this.client);return this.fetch(O,await O.body($),$.cursor)}async*list($={}){let O=new Ej(this.client),j=await O.body($);yield*u((x)=>this.fetch(O,j,x))}async fetch($,O,j){let x=G(await this.client.storage.postItemsSoupAst({body:O,query:j?{cursor:j}:void 0})),K=x.items.some((Z)=>b0(Z).some((X)=>X.definition.data_type==="TAG"))?await $.tagMap():new Map;return{items:x.items.map((Z)=>n1(this.client,Z,K)),nextCursor:x.next_cursor,hasMore:x.next_cursor!=null}}}function e1({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((W)=>setTimeout(W,V)));return{stream:async function*(){let V=K??3000,W=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;W++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:l,value:r}=await H.read();if(l)break;U+=r,U=U.replace(/\r\n?/g,`
`);let g=U.split(`
`);U=g.pop()??"";for(let p of g){let a=p.split(`
@@ -54,7 +54,7 @@ async function uO($,O,j){if(!Number.isInteger(O)||O<1)throw RangeError(`concurre
`);U=g.pop()??"";for(let p of g){let a=p.split(`
`),F=[],y;for(let R of a)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))y=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let h=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(h))V=h}let C,v=!1;if(F.length){let R=F.join(`
-`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&W>=Z)break;let _=Math.min(V*2**(W-1),X??30000);await I(_)}}}()}}var e5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},o5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},$4=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Px=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(o5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=e5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return yO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},yO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},Ax=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=$4(x),X=Object.entries(S).map(([Y,L])=>yO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var O4=/\{[^{}]+\}/g,j4=({path:$,url:O})=>{let j=O,x=O.match(O4);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,Px({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,Ax({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${yO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},j6=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=j4({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function M1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var x6=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var S6=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=Px({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=Ax({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=yO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},Z6=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},x4=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function X6($){for(let O of $.security??[]){if(x4($,O.name))continue;let j=await x6(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var P1=($)=>j6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:S6($.querySerializer),url:$.url}),A1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=Ex($.headers,O.headers),j},S4=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},Ex=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?S4(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class Fx{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var K6=()=>({error:new Fx,request:new Fx,response:new Fx}),Z4=S6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),X4={"Content-Type":"application/json"},Jj=($={})=>({...C1,headers:X4,parseAs:"auto",querySerializer:Z4,...$});var Vj=($={})=>{let O=A1(Jj(),$),j=()=>({...O}),x=(Q)=>{return O=A1(O,Q),j()},S=K6(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:Ex(O.headers,Q.headers),serializedBody:void 0};if(J.security)await X6(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=P1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,B;try{let{opts:V,url:W}=await K(Q),T={redirect:"follow",...V,body:M1(V)};z=new Request(W,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;B=await A(z);for(let N of S.response.fns)if(N)B=await N(B,z,V);let D={request:z,response:B};if(B.ok){let N=(V.parseAs==="auto"?Z6(B.headers.get("Content-Type")):V.parseAs)??"json";if(B.status===204||B.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await B[N]();break;case"formData":U=new FormData;break;case"stream":U=B.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await B[N]();break;case"json":{let U=await B.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?B.body:{data:B.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await B.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let W=V;for(let T of S.error.fns)if(T)W=await T(W,B,z,Q);if(W=W||{},J)throw W;return I==="data"?void 0:{error:W,request:z,response:B}}},X=(Q)=>(J)=>Z({...J,method:Q}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return O6({...I,body:I.body,method:Q,onRequest:async(B,V)=>{let W=new Request(B,V);for(let T of S.request.fns)if(T)W=await T(W,I);return W},serializedBody:M1(I),url:z})};return{buildUrl:(Q)=>P1({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var Y6=Vj(Jj());class G6{client;constructor($){this.client=$?.client??Y6}}class Q6{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class wx extends G6{static __registry=new Q6;constructor($){super($);wx.__registry.set(this,$?.key)}listAgents($){return($?.client??this.client).get({url:"/agents",...$})}createAgent($){return($.client??this.client).post({url:"/agents",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAgent($){return($.client??this.client).put({url:"/agents/{agent_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteAnchor($){return($.client??this.client).delete({url:"/annotations/anchors",...$,headers:{"Content-Type":"application/json",...$.headers}})}editAnchor($){return($.client??this.client).patch({url:"/annotations/anchors",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentAnchors($){return($.client??this.client).get({url:"/annotations/anchors/document/{document_id}",...$})}createAnchor($){return($.client??this.client).post({url:"/annotations/anchors/document/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSelfBot($){return($?.client??this.client).get({url:"/bots/me",...$})}getBotOwnerProfiles($){return($?.client??this.client).get({url:"/bots/profiles",...$})}listBotChannels($){return($.client??this.client).get({url:"/bots/{bot_id}/channels",...$})}removeBotFromChannelByBot($){return($.client??this.client).delete({url:"/bots/{bot_id}/channels/{channel_id}",...$})}listOccurrences($){return($.client??this.client).get({url:"/calendar-events",...$})}mentionPreviews($){return($.client??this.client).post({url:"/calendar-events/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}listTeamCalendar($){return($.client??this.client).get({url:"/calendar-events/team",...$})}listTeamOutOfOffice($){return($.client??this.client).get({url:"/calendar-events/team-out-of-office",...$})}eventIcs($){return($.client??this.client).get({url:"/calendar-events/{event_id}/ics",...$})}listJoinRequests($){return($.client??this.client).get({url:"/calendar-events/{event_id}/join-requests",...$})}requestToJoin($){return($.client??this.client).post({url:"/calendar-events/{event_id}/join-requests",...$})}getActiveCalls($){return($?.client??this.client).get({url:"/call/active",...$})}guestCallChatRead($){return($.client??this.client).get({url:"/call/guest-chat/{call_id}",...$})}guestCallChatPost($){return($.client??this.client).post({url:"/call/guest-chat/{call_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingLookup($){return($.client??this.client).get({url:"/call/join/{token}",...$})}meetingGuestJoin($){return($.client??this.client).post({url:"/call/join/{token}",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingLeave($){return($.client??this.client).post({url:"/call/join/{token}/leave",...$})}meetingGuestParticipants($){return($.client??this.client).get({url:"/call/join/{token}/participants",...$})}meetingList($){return($?.client??this.client).get({url:"/call/meetings",...$})}meetingCreate($){return($.client??this.client).post({url:"/call/meetings",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingListActive($){return($?.client??this.client).get({url:"/call/meetings/active",...$})}meetingInvitePermissions($){return($.client??this.client).get({url:"/call/meetings/invite/{token}",...$})}meetingInvite($){return($.client??this.client).post({url:"/call/meetings/invite/{token}",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingInviteUsers($){return($.client??this.client).post({url:"/call/meetings/invite/{token}/users",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingJoin($){return($.client??this.client).post({url:"/call/meetings/join/{token}",...$})}meetingParticipants($){return($.client??this.client).get({url:"/call/meetings/join/{token}/participants",...$})}meetingPrepare($){return($?.client??this.client).post({url:"/call/meetings/prepare",...$})}meetingCancelPreparation($){return($.client??this.client).delete({url:"/call/meetings/prepare/{preparation_id}",...$})}meetingCancel($){return($.client??this.client).delete({url:"/call/meetings/{meeting_id}",...$})}meetingUpdate($){return($.client??this.client).patch({url:"/call/meetings/{meeting_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getBatchCallRecordPreview($){return($.client??this.client).post({url:"/call/record/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteCallRecord($){return($.client??this.client).delete({url:"/call/record/{call_id}",...$})}getCallRecord($){return($.client??this.client).get({url:"/call/record/{call_id}",...$})}editCallRecord($){return($.client??this.client).patch({url:"/call/record/{call_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}declineCall($){return($.client??this.client).post({url:"/call/record/{call_id}/decline",...$})}meetingShare($){return($.client??this.client).post({url:"/call/record/{call_id}/link",...$})}toggleShareWithTeam($){return($.client??this.client).post({url:"/call/record/{call_id}/share-with-team/toggle",...$})}editCallTranscript($){return($.client??this.client).patch({url:"/call/record/{call_id}/transcript",...$,headers:{"Content-Type":"application/json",...$.headers}})}getRingStatus($){return($.client??this.client).get({url:"/call/ring-status/{call_id}",...$})}declineRing($){return($.client??this.client).post({url:"/call/ring-status/{call_id}/decline",...$})}callWebhook($){return($?.client??this.client).post({url:"/call/webhook",...$})}leaveOrEndCall($){return($.client??this.client).delete({url:"/call/{channel_id}",...$})}getOrCreateCall($){return($.client??this.client).get({url:"/call/{channel_id}",...$})}checkActiveCall($){return($.client??this.client).get({url:"/call/{channel_id}/active",...$})}ingestTranscript($){return($.client??this.client).post({url:"/call/{room_name}/transcript",...$,headers:{"Content-Type":"application/json",...$.headers}})}listChannelLabels($){return($?.client??this.client).get({url:"/channel-labels",...$})}createChannelLabel($){return($.client??this.client).post({url:"/channel-labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}setChannelLabel($){return($.client??this.client).put({url:"/channel-labels/channels/{channel_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}previewSmartTag($){return($.client??this.client).post({url:"/channel-labels/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteChannelLabel($){return($.client??this.client).delete({url:"/channel-labels/{label_id}",...$})}renameChannelLabel($){return($.client??this.client).patch({url:"/channel-labels/{label_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}createChannel($){return($.client??this.client).post({url:"/channels",...$,headers:{"Content-Type":"application/json",...$.headers}})}getActivity($){return($?.client??this.client).get({url:"/channels/activity",...$})}postActivity($){return($.client??this.client).post({url:"/channels/activity",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAttachmentReferences($){return($.client??this.client).get({url:"/channels/attachments/{entity_type}/{entity_id}/references",...$})}getOrCreateDm($){return($.client??this.client).post({url:"/channels/get_or_create_dm",...$,headers:{"Content-Type":"application/json",...$.headers}})}getOrCreatePrivate($){return($.client??this.client).post({url:"/channels/get_or_create_private",...$,headers:{"Content-Type":"application/json",...$.headers}})}joinChannelByCode($){return($.client??this.client).post({url:"/channels/join/{join_code}",...$})}createEntityMention($){return($.client??this.client).post({url:"/channels/mentions",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteEntityMention($){return($.client??this.client).delete({url:"/channels/mentions/{mention_id}",...$})}getBatchChannelPreview($){return($.client??this.client).post({url:"/channels/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteChannel($){return($.client??this.client).delete({url:"/channels/{channel_id}",...$})}getChannel($){return($.client??this.client).get({url:"/channels/{channel_id}",...$})}patchChannel($){return($.client??this.client).patch({url:"/channels/{channel_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChannelAttachments($){return($.client??this.client).get({url:"/channels/{channel_id}/attachments",...$})}createChannelScopedBot($){return($.client??this.client).post({url:"/channels/{channel_id}/bots/scoped",...$,headers:{"Content-Type":"application/json",...$.headers}})}joinChannel($){return($.client??this.client).post({url:"/channels/{channel_id}/join",...$})}getChannelJoinLink($){return($.client??this.client).get({url:"/channels/{channel_id}/join-link",...$})}leaveChannel($){return($.client??this.client).post({url:"/channels/{channel_id}/leave",...$})}removeParticipants($){return($.client??this.client).delete({url:"/channels/{channel_id}/participants",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChannelParticipants($){return($.client??this.client).get({url:"/channels/{channel_id}/participants",...$})}addParticipants($){return($.client??this.client).post({url:"/channels/{channel_id}/participants",...$,headers:{"Content-Type":"application/json",...$.headers}})}setChannelPicture($){return($.client??this.client).put({url:"/channels/{channel_id}/profile_picture",...$,headers:{"Content-Type":"application/json",...$.headers}})}postChannelBotWebhook($){return($.client??this.client).post({url:"/channels/{channel_id}/webhook",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteCollabSurface($){return($.client??this.client).delete({url:"/collab_surfaces/{id}",...$})}getCollabSurface($){return($.client??this.client).get({url:"/collab_surfaces/{id}",...$})}ensureCollabSurface($){return($.client??this.client).put({url:"/collab_surfaces/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}createCollabSurfaceToken($){return($.client??this.client).post({url:"/collab_surfaces/{id}/token",...$})}getChannels($){return($?.client??this.client).get({url:"/comms/channels",...$})}createCrmCompany($){return($.client??this.client).post({url:"/crm/companies",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCompany($){return($.client??this.client).get({url:"/crm/companies/{company_id}",...$})}listCompanyContacts($){return($.client??this.client).get({url:"/crm/companies/{company_id}/contacts",...$})}createCrmContact($){return($.client??this.client).post({url:"/crm/companies/{company_id}/contacts",...$,headers:{"Content-Type":"application/json",...$.headers}})}setEmailSync($){return($.client??this.client).put({url:"/crm/companies/{company_id}/email-sync",...$,headers:{"Content-Type":"application/json",...$.headers}})}setCompanyHidden($){return($.client??this.client).put({url:"/crm/companies/{company_id}/hidden",...$,headers:{"Content-Type":"application/json",...$.headers}})}setCrmCompanyName($){return($.client??this.client).put({url:"/crm/companies/{company_id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}searchContacts($){return($?.client??this.client).get({url:"/crm/contacts",...$})}getContactByEmail($){return($.client??this.client).get({url:"/crm/contacts/by-email",...$})}getContact($){return($.client??this.client).get({url:"/crm/contacts/{contact_id}",...$})}setContactHidden($){return($.client??this.client).put({url:"/crm/contacts/{contact_id}/hidden",...$,headers:{"Content-Type":"application/json",...$.headers}})}setCrmContactName($){return($.client??this.client).put({url:"/crm/contacts/{contact_id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCrmPipelines($){return($?.client??this.client).get({url:"/crm/pipelines",...$})}createCrmPipeline($){return($.client??this.client).post({url:"/crm/pipelines",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipeline($){return($.client??this.client).get({url:"/crm/pipelines/{id}",...$})}renameCrmPipeline($){return($.client??this.client).put({url:"/crm/pipelines/{id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}applyCrmPipelineOps($){return($.client??this.client).post({url:"/crm/pipelines/{id}/ops",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipelinePermissions($){return($.client??this.client).get({url:"/crm/pipelines/{id}/permissions",...$})}updateCrmPipelinePermissions($){return($.client??this.client).patch({url:"/crm/pipelines/{id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipelineRows($){return($.client??this.client).get({url:"/crm/pipelines/{id}/rows",...$})}queryCrmPipelineRows($){return($.client??this.client).post({url:"/crm/pipelines/{id}/rows",...$,headers:{"Content-Type":"application/json",...$.headers}})}shareCrmPipeline($){return($.client??this.client).put({url:"/crm/pipelines/{id}/sharing",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipelineTable($){return($.client??this.client).get({url:"/crm/pipelines/{id}/table",...$})}trashCrmPipeline($){return($.client??this.client).put({url:"/crm/pipelines/{id}/trash",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmTeamSettings($){return($?.client??this.client).get({url:"/crm/settings",...$})}putCrmTeamSettings($){return($.client??this.client).put({url:"/crm/settings",...$,headers:{"Content-Type":"application/json",...$.headers}})}resetCrmTeamStages($){return($?.client??this.client).delete({url:"/crm/stages",...$})}putCrmTeamStages($){return($.client??this.client).put({url:"/crm/stages",...$,headers:{"Content-Type":"application/json",...$.headers}})}listDatabases($){return($?.client??this.client).get({url:"/databases",...$})}createDatabase($){return($.client??this.client).post({url:"/databases",...$,headers:{"Content-Type":"application/json",...$.headers}})}saveDatabaseQuery($){return($.client??this.client).post({url:"/databases/queries",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabaseQuery($){return($.client??this.client).get({url:"/databases/queries/{query_id}",...$})}queryDatabases($){return($.client??this.client).post({url:"/databases/query",...$,headers:{"Content-Type":"application/json",...$.headers}})}ensureStarterHandler($){return($?.client??this.client).post({url:"/databases/starter",...$})}deliverDatabaseWebhook($){return($.client??this.client).post({url:"/databases/webhooks/{token}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabase($){return($.client??this.client).get({url:"/databases/{id}",...$})}shareDatabaseAwareness($){return($.client??this.client).put({url:"/databases/{id}/awareness",...$,headers:{"Content-Type":"application/json",...$.headers}})}undoDatabaseChange($){return($.client??this.client).post({url:"/databases/{id}/changes/{change}/undo",...$})}importDatabaseTable($){return($.client??this.client).post({url:"/databases/{id}/import",...$,headers:{"Content-Type":"application/json",...$.headers}})}applyDatabaseOps($){return($.client??this.client).post({url:"/databases/{id}/ops",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabasePermissions($){return($.client??this.client).get({url:"/databases/{id}/permissions",...$})}updateDatabasePermissions($){return($.client??this.client).patch({url:"/databases/{id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabaseTableChanges($){return($.client??this.client).get({url:"/databases/{id}/tables/{table_id}/changes",...$})}listDatabaseColumnCasts($){return($.client??this.client).get({url:"/databases/{id}/tables/{table_id}/columns/{column_id}/casts",...$})}convertDatabaseColumn($){return($.client??this.client).post({url:"/databases/{id}/tables/{table_id}/columns/{column_id}/conversion",...$,headers:{"Content-Type":"application/json",...$.headers}})}inferDatabaseColumnType($){return($.client??this.client).post({url:"/databases/{id}/tables/{table_id}/columns/{column_id}/infer-type",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabaseRowHistory($){return($.client??this.client).get({url:"/databases/{id}/tables/{table_id}/rows/{row_id}/history",...$})}getDatabaseViewPositions($){return($.client??this.client).get({url:"/databases/{id}/views/{view_id}/positions",...$})}listDatabaseWebhooks($){return($.client??this.client).get({url:"/databases/{id}/webhooks",...$})}createDatabaseWebhook($){return($.client??this.client).post({url:"/databases/{id}/webhooks",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteDatabaseWebhook($){return($.client??this.client).delete({url:"/databases/{id}/webhooks/{webhook_id}",...$})}transcribeDictation($){return($.client??this.client).post({bodySerializer:null,url:"/dictation/transcribe",...$,headers:{"Content-Type":"audio/webm",...$.headers}})}getUserDocumentsHandler($){return($.client??this.client).get({url:"/documents",...$})}createDocument($){return($.client??this.client).post({url:"/documents",...$,headers:{"Content-Type":"application/json",...$.headers}})}createCanvasHandler($){return($.client??this.client).post({url:"/documents/create_canvas",...$,headers:{"Content-Type":"application/json",...$.headers}})}createMarkdownHandler($){return($.client??this.client).post({url:"/documents/create_markdown",...$,headers:{"Content-Type":"application/json",...$.headers}})}createSkillHandler($){return($.client??this.client).post({url:"/documents/create_skill",...$,headers:{"Content-Type":"application/json",...$.headers}})}createSnippetHandler($){return($.client??this.client).post({url:"/documents/create_snippet",...$,headers:{"Content-Type":"application/json",...$.headers}})}createTaskHandler($){return($.client??this.client).post({url:"/documents/create_task",...$,headers:{"Content-Type":"application/json",...$.headers}})}getGithubPullRequestTasks($){return($.client??this.client).post({url:"/documents/github_prs/tasks",...$,headers:{"Content-Type":"application/json",...$.headers}})}initializeUserDocuments($){return($?.client??this.client).post({url:"/documents/initialize_user_documents",...$})}getDocumentListHandler($){return($?.client??this.client).get({url:"/documents/list",...$})}validateDocumentPermissionsToken($){return($.client??this.client).post({url:"/documents/permissions_token/validate",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentPermissionsToken($){return($.client??this.client).post({url:"/documents/permissions_token/{document_id}",...$})}presaveDocumentHandler($){return($.client??this.client).put({url:"/documents/presave/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getBatchPreviewHandler($){return($.client??this.client).post({url:"/documents/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentByTeamSlug($){return($.client??this.client).get({url:"/documents/slug/{slug}",...$})}handler($){return($?.client??this.client).get({url:"/documents/starter_docs",...$})}getSystemSkillsHandler($){return($?.client??this.client).get({url:"/documents/system_skills",...$})}deleteDocument($){return($.client??this.client).delete({url:"/documents/{document_id}",...$})}getDocument($){return($.client??this.client).get({url:"/documents/{document_id}",...$})}editDocument($){return($.client??this.client).patch({url:"/documents/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}saveDocumentHandler($){return($.client??this.client).put({url:"/documents/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentBranchName($){return($.client??this.client).get({url:"/documents/{document_id}/branch_name",...$})}copyDocument($){return($.client??this.client).post({url:"/documents/{document_id}/copy",...$,headers:{"Content-Type":"application/json",...$.headers}})}exportDocument($){return($.client??this.client).get({url:"/documents/{document_id}/export",...$})}getDocumentGithubPullRequests($){return($.client??this.client).get({url:"/documents/{document_id}/github_prs",...$})}getLocationHandler($){return($.client??this.client).get({url:"/documents/{document_id}/location",...$})}getDocumentLocationV3($){return($.client??this.client).get({url:"/documents/{document_id}/location_v3",...$})}permanentlyDeleteDocument($){return($.client??this.client).delete({url:"/documents/{document_id}/permanent",...$})}getDocumentProcessingResult($){return($.client??this.client).get({url:"/documents/{document_id}/processing",...$})}jobProcessingResultHandler($){return($.client??this.client).get({url:"/documents/{document_id}/processing/{job_id}",...$})}revertDeleteDocument($){return($.client??this.client).put({url:"/documents/{document_id}/revert_delete",...$})}getDocumentShortId($){return($.client??this.client).get({url:"/documents/{document_id}/short_id",...$})}simpleSave($){return($.client??this.client).put({url:"/documents/{document_id}/simple_save",...$})}getDocumentTeamShare($){return($.client??this.client).get({url:"/documents/{document_id}/team_share",...$})}setDocumentTeamShare($){return($.client??this.client).put({url:"/documents/{document_id}/team_share",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentTextContent($){return($.client??this.client).get({url:"/documents/{document_id}/text-content",...$})}getDocumentViewsHandler($){return($.client??this.client).get({url:"/documents/{document_id}/views",...$})}getDocumentVersion($){return($.client??this.client).get({url:"/documents/{document_id}/{document_version_id}",...$})}accessRequestsState($){return($.client??this.client).get({url:"/entities/{entity_type}/{entity_id}/access-requests",...$})}accessRequestsCancel($){return($.client??this.client).delete({url:"/entities/{entity_type}/{entity_id}/access-requests/mine",...$})}accessRequestsSubmit($){return($.client??this.client).put({url:"/entities/{entity_type}/{entity_id}/access-requests/mine",...$,headers:{"Content-Type":"application/json",...$.headers}})}accessRequestsResolve($){return($.client??this.client).post({url:"/entities/{entity_type}/{entity_id}/access-requests/{request_id}/resolve",...$,headers:{"Content-Type":"application/json",...$.headers}})}accessRequestsDirect($){return($.client??this.client).get({url:"/entities/{entity_type}/{entity_id}/direct-access",...$})}accessRequestsRemoveDirect($){return($.client??this.client).delete({url:"/entities/{entity_type}/{entity_id}/direct-access/{user_id}",...$})}accessRequestsSetDirect($){return($.client??this.client).put({url:"/entities/{entity_type}/{entity_id}/direct-access/{user_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getEntityPermission($){return($.client??this.client).get({url:"/entity/{entity_type}/{entity_id}/permissions",...$})}listFavorites($){return($?.client??this.client).get({url:"/favorites",...$})}addFavorite($){return($.client??this.client).post({url:"/favorites",...$,headers:{"Content-Type":"application/json",...$.headers}})}reorderFavorites($){return($.client??this.client).patch({url:"/favorites/reorder",...$,headers:{"Content-Type":"application/json",...$.headers}})}removeFavoriteByEntity($){return($.client??this.client).delete({url:"/favorites/{entity_type}/{entity_id}",...$})}getForeignEntityBySource($){return($.client??this.client).get({url:"/foreign_entity/by_source/{source}/{foreign_entity_id}",...$})}getForeignEntity($){return($.client??this.client).get({url:"/foreign_entity/{id}",...$})}listForms($){return($.client??this.client).get({url:"/forms",...$})}createForm($){return($.client??this.client).post({url:"/forms",...$,headers:{"Content-Type":"application/json",...$.headers}})}listAccessibleForms($){return($?.client??this.client).get({url:"/forms/accessible",...$})}getForm($){return($.client??this.client).get({url:"/forms/{id}",...$})}updateForm($){return($.client??this.client).patch({url:"/forms/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}collaborateForm($){return($.client??this.client).post({url:"/forms/{id}/collaboration",...$})}putFormLayout($){return($.client??this.client).put({url:"/forms/{id}/layout",...$,headers:{"Content-Type":"application/json",...$.headers}})}getFormPermissions($){return($.client??this.client).get({url:"/forms/{id}/permissions",...$})}updateFormPermissions($){return($.client??this.client).patch({url:"/forms/{id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}submitFormResponse($){return($.client??this.client).post({url:"/forms/{id}/responses",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMyFormResponse($){return($.client??this.client).get({url:"/forms/{id}/responses/mine",...$})}editMyFormResponse($){return($.client??this.client).put({url:"/forms/{id}/responses/mine",...$,headers:{"Content-Type":"application/json",...$.headers}})}getFormResponseSummary($){return($.client??this.client).get({url:"/forms/{id}/responses/summary",...$})}getFormTally($){return($.client??this.client).get({url:"/forms/{id}/tally",...$})}installSync($){return($?.client??this.client).get({url:"/github/install-sync",...$})}getGithubPullRequestFacets($){return($?.client??this.client).get({url:"/github_pull_requests/facets",...$})}getGithubPullRequest($){return($.client??this.client).get({url:"/github_pull_requests/{id}",...$})}getGithubPullRequestChanges($){return($.client??this.client).get({url:"/github_pull_requests/{id}/changes",...$})}getGithubPullRequestChangesPatch($){return($.client??this.client).get({url:"/github_pull_requests/{id}/changes/patch",...$})}createHarnessPairing($){return($.client??this.client).post({url:"/harness-pairings",...$,headers:{"Content-Type":"application/json",...$.headers}})}getHarnessPairing($){return($.client??this.client).get({url:"/harness-pairings/{code}",...$})}approveHarnessPairing($){return($.client??this.client).post({url:"/harness-pairings/{code}/approve",...$,headers:{"Content-Type":"application/json",...$.headers}})}claimHarnessPairing($){return($.client??this.client).post({url:"/harness-pairings/{pairing_id}/claim",...$,headers:{"Content-Type":"application/json",...$.headers}})}listHarnesses($){return($?.client??this.client).get({url:"/harnesses",...$})}deleteSelfHarness($){return($?.client??this.client).delete({url:"/harnesses/me",...$})}getSelfHarness($){return($?.client??this.client).get({url:"/harnesses/me",...$})}listHarnessAgents($){return($?.client??this.client).get({url:"/harnesses/me/agents",...$})}listHarnessSessions($){return($?.client??this.client).get({url:"/harnesses/me/sessions",...$})}deleteHarness($){return($.client??this.client).delete({url:"/harnesses/{harness_id}",...$})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}getHistoryHandler($){return($?.client??this.client).get({url:"/history",...$})}deleteHistoryHandler($){return($.client??this.client).delete({url:"/history/{item_type}/{item_id}",...$})}upsertHistoryHandler($){return($.client??this.client).post({url:"/history/{item_type}/{item_id}",...$})}listInitiatives($){return($?.client??this.client).get({url:"/initiatives",...$})}createInitiative($){return($.client??this.client).post({url:"/initiatives",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteInitiative($){return($.client??this.client).delete({url:"/initiatives/{initiative_id}",...$})}getInitiative($){return($.client??this.client).get({url:"/initiatives/{initiative_id}",...$})}updateInitiative($){return($.client??this.client).patch({url:"/initiatives/{initiative_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getInstructionsHandler($){return($?.client??this.client).get({url:"/instructions",...$})}createInstructionsHandler($){return($?.client??this.client).post({url:"/instructions",...$})}getItemsSoup($){return($?.client??this.client).get({url:"/items/soup",...$})}postItemsSoup($){return($.client??this.client).post({url:"/items/soup",...$,headers:{"Content-Type":"application/json",...$.headers}})}postItemsSoupAst($){return($.client??this.client).post({url:"/items/soup/ast",...$,headers:{"Content-Type":"application/json",...$.headers}})}postItemsSoupAstGrouped($){return($.client??this.client).post({url:"/items/soup/ast/grouped",...$,headers:{"Content-Type":"application/json",...$.headers}})}messageTimeline($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}",...$})}entityMessageCreate($){return($.client??this.client).post({url:"/messages/{parent_type}/{parent_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}entityMessageDeleteMessage($){return($.client??this.client).delete({url:"/messages/{parent_type}/{parent_id}/items/{id}",...$})}entityMessageGetMessage($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/items/{id}",...$})}entityMessageEdit($){return($.client??this.client).patch({url:"/messages/{parent_type}/{parent_id}/items/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}entityMessageReact($){return($.client??this.client).post({url:"/messages/{parent_type}/{parent_id}/items/{id}/reactions",...$,headers:{"Content-Type":"application/json",...$.headers}})}entityMessageLegacy($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/legacy/{legacy_id}",...$})}entityMessageDeleteThread($){return($.client??this.client).delete({url:"/messages/{parent_type}/{parent_id}/threads/{id}",...$})}entityMessageGetThread($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/threads/{id}",...$})}entityMessagePatchThread($){return($.client??this.client).patch({url:"/messages/{parent_type}/{parent_id}/threads/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}messageTimelineEntries($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/timeline",...$})}entityMessageTyping($){return($.client??this.client).post({url:"/messages/{parent_type}/{parent_id}/typing",...$,headers:{"Content-Type":"application/json",...$.headers}})}linkedAccount($){return($?.client??this.client).get({url:"/meta/linked/account",...$})}linkedChats($){return($?.client??this.client).get({url:"/meta/linked/chats",...$})}linkedConfiguration($){return($?.client??this.client).get({url:"/meta/linked/configuration",...$})}linkedConnect($){return($.client??this.client).post({url:"/meta/linked/connect",...$,headers:{"Content-Type":"application/json",...$.headers}})}linkedDisconnect($){return($.client??this.client).post({url:"/meta/linked/disconnect",...$,headers:{"Content-Type":"application/json",...$.headers}})}linkedAdopt($){return($.client??this.client).post({url:"/meta/linked/groups/adopt",...$,headers:{"Content-Type":"application/json",...$.headers}})}linkedCancelPairing($){return($.client??this.client).delete({url:"/meta/linked/pairing/{id}",...$})}linkedPairing($){return($.client??this.client).get({url:"/meta/linked/pairing/{id}",...$})}linkedPasskey($){return($.client??this.client).post({url:"/meta/linked/pairing/{id}/passkey",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappGroups($){return($?.client??this.client).get({url:"/meta/linked/whatsapp-groups",...$})}linkedDetach($){return($.client??this.client).delete({url:"/meta/linked/whatsapp-groups/{group_id}",...$})}whatsappGroup($){return($.client??this.client).get({url:"/meta/linked/whatsapp-groups/{group_id}",...$})}linkedUpload($){return($.client??this.client).post({..._1,url:"/meta/linked/whatsapp-groups/{group_id}/attachments",...$,headers:{"Content-Type":null,...$.headers}})}linkedDelivery($){return($.client??this.client).post({url:"/meta/linked/whatsapp-groups/{group_id}/delivery",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappGroupMessages($){return($.client??this.client).get({url:"/meta/linked/whatsapp-groups/{group_id}/messages",...$})}linkedMessageAttachments($){return($.client??this.client).post({url:"/meta/linked/whatsapp-groups/{group_id}/messages/attachments",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappGroupPermissions($){return($.client??this.client).get({url:"/meta/linked/whatsapp-groups/{group_id}/permissions",...$})}whatsappGroupUpdatePermissions($){return($.client??this.client).patch({url:"/meta/linked/whatsapp-groups/{group_id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappGroupRead($){return($.client??this.client).post({url:"/meta/linked/whatsapp-groups/{group_id}/read",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappGroupSends($){return($.client??this.client).get({url:"/meta/linked/whatsapp-groups/{group_id}/sends",...$})}linkedReply($){return($.client??this.client).post({url:"/meta/linked/whatsapp-groups/{group_id}/sends",...$,headers:{"Content-Type":"application/json",...$.headers}})}getPinsHandler($){return($?.client??this.client).get({url:"/pins",...$})}reorderPinsHandler($){return($.client??this.client).patch({url:"/pins",...$,headers:{"Content-Type":"application/json",...$.headers}})}removePinHandler($){return($.client??this.client).delete({url:"/pins/{pinned_item_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}addPinHandler($){return($.client??this.client).post({url:"/pins/{pinned_item_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getProjectsHandler($){return($?.client??this.client).get({url:"/projects",...$})}createProjectHandler($){return($.client??this.client).post({url:"/projects",...$,headers:{"Content-Type":"application/json",...$.headers}})}getPendingProjectsHandler($){return($?.client??this.client).get({url:"/projects/pending",...$})}getBatchProjectPreview($){return($.client??this.client).post({url:"/projects/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}uploadFolderHandler($){return($.client??this.client).post({url:"/projects/upload",...$,headers:{"Content-Type":"application/json",...$.headers}})}uploadExtractFolderHandler($){return($.client??this.client).post({url:"/projects/upload_extract",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteProjectHandler($){return($.client??this.client).delete({url:"/projects/{id}",...$})}getProjectHandler($){return($.client??this.client).get({url:"/projects/{id}",...$})}getProjectUserAccessLevel($){return($.client??this.client).get({url:"/projects/{id}/access_level",...$})}getProjectContentHandler($){return($.client??this.client).get({url:"/projects/{id}/content",...$})}permanentlyDeleteProject($){return($.client??this.client).delete({url:"/projects/{id}/permanent",...$})}getProjectPermissionsV2($){return($.client??this.client).get({url:"/projects/{id}/permissions",...$})}revertDeleteProject($){return($.client??this.client).put({url:"/projects/{id}/revert_delete",...$})}recentlyDeleted($){return($?.client??this.client).get({url:"/recents/deleted",...$})}listEmailReminders($){return($?.client??this.client).get({url:"/reminders/email/collection",...$})}getEmailFollowup($){return($.client??this.client).get({url:"/reminders/email/{thread_id}",...$})}setEmailFollowup($){return($.client??this.client).put({url:"/reminders/email/{thread_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getViewsHandler($){return($?.client??this.client).get({url:"/saved_views",...$})}createViewHandler($){return($.client??this.client).post({url:"/saved_views",...$,headers:{"Content-Type":"application/json",...$.headers}})}excludeDefaultViewHandler($){return($.client??this.client).post({url:"/saved_views/exclude_default",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteViewHandler($){return($.client??this.client).delete({url:"/saved_views/{saved_view_id}",...$})}patchViewHandler($){return($.client??this.client).patch({url:"/saved_views/{saved_view_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}listSlackImports($){return($?.client??this.client).get({url:"/slack/imports",...$})}createSlackImport($){return($.client??this.client).post({url:"/slack/imports",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSlackImport($){return($.client??this.client).get({url:"/slack/imports/{job_id}",...$})}cancelSlackImport($){return($.client??this.client).post({url:"/slack/imports/{job_id}/cancel",...$})}finalizeSlackImport($){return($.client??this.client).post({url:"/slack/imports/{job_id}/finalize",...$})}registerSlackImportUploads($){return($.client??this.client).post({url:"/slack/imports/{job_id}/uploads",...$,headers:{"Content-Type":"application/json",...$.headers}})}completeSlackImportUploads($){return($.client??this.client).post({url:"/slack/imports/{job_id}/uploads/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}bulkWakeupSyncServiceDocuments($){return($.client??this.client).post({url:"/sync_service/wakeup",...$,headers:{"Content-Type":"application/json",...$.headers}})}editThreadV2($){return($.client??this.client).patch({url:"/threads/{thread_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}listUserApiKeys($){return($?.client??this.client).get({url:"/user-api-keys",...$})}createUserApiKey($){return($.client??this.client).post({url:"/user-api-keys",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteUserApiKey($){return($.client??this.client).delete({url:"/user-api-keys/{id}",...$})}deleteUserDocumentViewLocation($){return($.client??this.client).delete({url:"/user_document_view_location/{document_id}",...$})}getUserDocumentViewLocation($){return($.client??this.client).get({url:"/user_document_view_location/{document_id}",...$})}upsertUserDocumentViewLocation($){return($.client??this.client).post({url:"/user_document_view_location/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentPermissionsV2($){return($.client??this.client).get({url:"/v2/documents/{document_id}/permissions",...$})}editProjectV2($){return($.client??this.client).patch({url:"/v2/projects/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}streamEvents($){return($.client??this.client).sse.get({url:"/webhook/events/stream",...$})}listWebhooks($){return($?.client??this.client).get({url:"/webhook/webhooks",...$})}createWebhook($){return($.client??this.client).post({url:"/webhook/webhooks",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteWebhook($){return($.client??this.client).delete({url:"/webhook/webhooks/{webhook_id}",...$})}getWebhook($){return($.client??this.client).get({url:"/webhook/webhooks/{webhook_id}",...$})}patchWebhook($){return($.client??this.client).patch({url:"/webhook/webhooks/{webhook_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}validateWebhook($){return($.client??this.client).post({url:"/webhook/webhooks/{webhook_id}/validate",...$})}}function J6({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((W)=>setTimeout(W,V)));return{stream:async function*(){let V=K??3000,W=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;W++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:l,value:r}=await H.read();if(l)break;U+=r,U=U.replace(/\r\n?/g,`
+`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&W>=Z)break;let _=Math.min(V*2**(W-1),X??30000);await I(_)}}}()}}var e5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},o5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},$4=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Px=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(o5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=e5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return yO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},yO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},Ax=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=$4(x),X=Object.entries(S).map(([Y,L])=>yO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var O4=/\{[^{}]+\}/g,j4=({path:$,url:O})=>{let j=O,x=O.match(O4);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,Px({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,Ax({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${yO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},j6=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=j4({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function M1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var x6=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var S6=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=Px({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=Ax({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=yO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},Z6=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},x4=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function X6($){for(let O of $.security??[]){if(x4($,O.name))continue;let j=await x6(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var P1=($)=>j6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:S6($.querySerializer),url:$.url}),A1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=Ex($.headers,O.headers),j},S4=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},Ex=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?S4(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class Fx{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var K6=()=>({error:new Fx,request:new Fx,response:new Fx}),Z4=S6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),X4={"Content-Type":"application/json"},Jj=($={})=>({...C1,headers:X4,parseAs:"auto",querySerializer:Z4,...$});var Vj=($={})=>{let O=A1(Jj(),$),j=()=>({...O}),x=(Q)=>{return O=A1(O,Q),j()},S=K6(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:Ex(O.headers,Q.headers),serializedBody:void 0};if(J.security)await X6(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=P1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,B;try{let{opts:V,url:W}=await K(Q),T={redirect:"follow",...V,body:M1(V)};z=new Request(W,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;B=await A(z);for(let N of S.response.fns)if(N)B=await N(B,z,V);let D={request:z,response:B};if(B.ok){let N=(V.parseAs==="auto"?Z6(B.headers.get("Content-Type")):V.parseAs)??"json";if(B.status===204||B.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await B[N]();break;case"formData":U=new FormData;break;case"stream":U=B.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await B[N]();break;case"json":{let U=await B.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?B.body:{data:B.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await B.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let W=V;for(let T of S.error.fns)if(T)W=await T(W,B,z,Q);if(W=W||{},J)throw W;return I==="data"?void 0:{error:W,request:z,response:B}}},X=(Q)=>(J)=>Z({...J,method:Q}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return O6({...I,body:I.body,method:Q,onRequest:async(B,V)=>{let W=new Request(B,V);for(let T of S.request.fns)if(T)W=await T(W,I);return W},serializedBody:M1(I),url:z})};return{buildUrl:(Q)=>P1({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var Y6=Vj(Jj());class G6{client;constructor($){this.client=$?.client??Y6}}class Q6{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class wx extends G6{static __registry=new Q6;constructor($){super($);wx.__registry.set(this,$?.key)}listAgents($){return($?.client??this.client).get({url:"/agents",...$})}createAgent($){return($.client??this.client).post({url:"/agents",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAgent($){return($.client??this.client).put({url:"/agents/{agent_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteAnchor($){return($.client??this.client).delete({url:"/annotations/anchors",...$,headers:{"Content-Type":"application/json",...$.headers}})}editAnchor($){return($.client??this.client).patch({url:"/annotations/anchors",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentAnchors($){return($.client??this.client).get({url:"/annotations/anchors/document/{document_id}",...$})}createAnchor($){return($.client??this.client).post({url:"/annotations/anchors/document/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSelfBot($){return($?.client??this.client).get({url:"/bots/me",...$})}getBotOwnerProfiles($){return($?.client??this.client).get({url:"/bots/profiles",...$})}listBotChannels($){return($.client??this.client).get({url:"/bots/{bot_id}/channels",...$})}removeBotFromChannelByBot($){return($.client??this.client).delete({url:"/bots/{bot_id}/channels/{channel_id}",...$})}listOccurrences($){return($.client??this.client).get({url:"/calendar-events",...$})}mentionPreviews($){return($.client??this.client).post({url:"/calendar-events/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}listTeamCalendar($){return($.client??this.client).get({url:"/calendar-events/team",...$})}listTeamOutOfOffice($){return($.client??this.client).get({url:"/calendar-events/team-out-of-office",...$})}eventIcs($){return($.client??this.client).get({url:"/calendar-events/{event_id}/ics",...$})}listJoinRequests($){return($.client??this.client).get({url:"/calendar-events/{event_id}/join-requests",...$})}requestToJoin($){return($.client??this.client).post({url:"/calendar-events/{event_id}/join-requests",...$})}getActiveCalls($){return($?.client??this.client).get({url:"/call/active",...$})}guestCallChatRead($){return($.client??this.client).get({url:"/call/guest-chat/{call_id}",...$})}guestCallChatPost($){return($.client??this.client).post({url:"/call/guest-chat/{call_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingLookup($){return($.client??this.client).get({url:"/call/join/{token}",...$})}meetingGuestJoin($){return($.client??this.client).post({url:"/call/join/{token}",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingLeave($){return($.client??this.client).post({url:"/call/join/{token}/leave",...$})}meetingGuestParticipants($){return($.client??this.client).get({url:"/call/join/{token}/participants",...$})}meetingList($){return($?.client??this.client).get({url:"/call/meetings",...$})}meetingCreate($){return($.client??this.client).post({url:"/call/meetings",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingListActive($){return($?.client??this.client).get({url:"/call/meetings/active",...$})}meetingInvitePermissions($){return($.client??this.client).get({url:"/call/meetings/invite/{token}",...$})}meetingInvite($){return($.client??this.client).post({url:"/call/meetings/invite/{token}",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingInviteUsers($){return($.client??this.client).post({url:"/call/meetings/invite/{token}/users",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingJoin($){return($.client??this.client).post({url:"/call/meetings/join/{token}",...$})}meetingParticipants($){return($.client??this.client).get({url:"/call/meetings/join/{token}/participants",...$})}meetingPrepare($){return($?.client??this.client).post({url:"/call/meetings/prepare",...$})}meetingCancelPreparation($){return($.client??this.client).delete({url:"/call/meetings/prepare/{preparation_id}",...$})}meetingCancel($){return($.client??this.client).delete({url:"/call/meetings/{meeting_id}",...$})}meetingUpdate($){return($.client??this.client).patch({url:"/call/meetings/{meeting_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getBatchCallRecordPreview($){return($.client??this.client).post({url:"/call/record/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteCallRecord($){return($.client??this.client).delete({url:"/call/record/{call_id}",...$})}getCallRecord($){return($.client??this.client).get({url:"/call/record/{call_id}",...$})}editCallRecord($){return($.client??this.client).patch({url:"/call/record/{call_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}declineCall($){return($.client??this.client).post({url:"/call/record/{call_id}/decline",...$})}meetingShare($){return($.client??this.client).post({url:"/call/record/{call_id}/link",...$})}toggleShareWithTeam($){return($.client??this.client).post({url:"/call/record/{call_id}/share-with-team/toggle",...$})}editCallTranscript($){return($.client??this.client).patch({url:"/call/record/{call_id}/transcript",...$,headers:{"Content-Type":"application/json",...$.headers}})}getRingStatus($){return($.client??this.client).get({url:"/call/ring-status/{call_id}",...$})}declineRing($){return($.client??this.client).post({url:"/call/ring-status/{call_id}/decline",...$})}callWebhook($){return($?.client??this.client).post({url:"/call/webhook",...$})}leaveOrEndCall($){return($.client??this.client).delete({url:"/call/{channel_id}",...$})}getOrCreateCall($){return($.client??this.client).get({url:"/call/{channel_id}",...$})}checkActiveCall($){return($.client??this.client).get({url:"/call/{channel_id}/active",...$})}ingestTranscript($){return($.client??this.client).post({url:"/call/{room_name}/transcript",...$,headers:{"Content-Type":"application/json",...$.headers}})}listChannelLabels($){return($?.client??this.client).get({url:"/channel-labels",...$})}createChannelLabel($){return($.client??this.client).post({url:"/channel-labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}setChannelLabel($){return($.client??this.client).put({url:"/channel-labels/channels/{channel_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}previewSmartTag($){return($.client??this.client).post({url:"/channel-labels/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteChannelLabel($){return($.client??this.client).delete({url:"/channel-labels/{label_id}",...$})}renameChannelLabel($){return($.client??this.client).patch({url:"/channel-labels/{label_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}createChannel($){return($.client??this.client).post({url:"/channels",...$,headers:{"Content-Type":"application/json",...$.headers}})}getActivity($){return($?.client??this.client).get({url:"/channels/activity",...$})}postActivity($){return($.client??this.client).post({url:"/channels/activity",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAttachmentReferences($){return($.client??this.client).get({url:"/channels/attachments/{entity_type}/{entity_id}/references",...$})}getOrCreateDm($){return($.client??this.client).post({url:"/channels/get_or_create_dm",...$,headers:{"Content-Type":"application/json",...$.headers}})}getOrCreatePrivate($){return($.client??this.client).post({url:"/channels/get_or_create_private",...$,headers:{"Content-Type":"application/json",...$.headers}})}joinChannelByCode($){return($.client??this.client).post({url:"/channels/join/{join_code}",...$})}createEntityMention($){return($.client??this.client).post({url:"/channels/mentions",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteEntityMention($){return($.client??this.client).delete({url:"/channels/mentions/{mention_id}",...$})}getBatchChannelPreview($){return($.client??this.client).post({url:"/channels/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteChannel($){return($.client??this.client).delete({url:"/channels/{channel_id}",...$})}getChannel($){return($.client??this.client).get({url:"/channels/{channel_id}",...$})}patchChannel($){return($.client??this.client).patch({url:"/channels/{channel_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChannelAttachments($){return($.client??this.client).get({url:"/channels/{channel_id}/attachments",...$})}createChannelScopedBot($){return($.client??this.client).post({url:"/channels/{channel_id}/bots/scoped",...$,headers:{"Content-Type":"application/json",...$.headers}})}joinChannel($){return($.client??this.client).post({url:"/channels/{channel_id}/join",...$})}getChannelJoinLink($){return($.client??this.client).get({url:"/channels/{channel_id}/join-link",...$})}leaveChannel($){return($.client??this.client).post({url:"/channels/{channel_id}/leave",...$})}removeParticipants($){return($.client??this.client).delete({url:"/channels/{channel_id}/participants",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChannelParticipants($){return($.client??this.client).get({url:"/channels/{channel_id}/participants",...$})}addParticipants($){return($.client??this.client).post({url:"/channels/{channel_id}/participants",...$,headers:{"Content-Type":"application/json",...$.headers}})}setChannelPicture($){return($.client??this.client).put({url:"/channels/{channel_id}/profile_picture",...$,headers:{"Content-Type":"application/json",...$.headers}})}postChannelBotWebhook($){return($.client??this.client).post({url:"/channels/{channel_id}/webhook",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteCollabSurface($){return($.client??this.client).delete({url:"/collab_surfaces/{id}",...$})}getCollabSurface($){return($.client??this.client).get({url:"/collab_surfaces/{id}",...$})}ensureCollabSurface($){return($.client??this.client).put({url:"/collab_surfaces/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}createCollabSurfaceToken($){return($.client??this.client).post({url:"/collab_surfaces/{id}/token",...$})}getChannels($){return($?.client??this.client).get({url:"/comms/channels",...$})}createCrmCompany($){return($.client??this.client).post({url:"/crm/companies",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCompany($){return($.client??this.client).get({url:"/crm/companies/{company_id}",...$})}listCompanyContacts($){return($.client??this.client).get({url:"/crm/companies/{company_id}/contacts",...$})}createCrmContact($){return($.client??this.client).post({url:"/crm/companies/{company_id}/contacts",...$,headers:{"Content-Type":"application/json",...$.headers}})}setEmailSync($){return($.client??this.client).put({url:"/crm/companies/{company_id}/email-sync",...$,headers:{"Content-Type":"application/json",...$.headers}})}setCompanyHidden($){return($.client??this.client).put({url:"/crm/companies/{company_id}/hidden",...$,headers:{"Content-Type":"application/json",...$.headers}})}setCrmCompanyName($){return($.client??this.client).put({url:"/crm/companies/{company_id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}searchContacts($){return($?.client??this.client).get({url:"/crm/contacts",...$})}getContactByEmail($){return($.client??this.client).get({url:"/crm/contacts/by-email",...$})}getContact($){return($.client??this.client).get({url:"/crm/contacts/{contact_id}",...$})}setContactHidden($){return($.client??this.client).put({url:"/crm/contacts/{contact_id}/hidden",...$,headers:{"Content-Type":"application/json",...$.headers}})}setCrmContactName($){return($.client??this.client).put({url:"/crm/contacts/{contact_id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCrmPipelines($){return($?.client??this.client).get({url:"/crm/pipelines",...$})}createCrmPipeline($){return($.client??this.client).post({url:"/crm/pipelines",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipeline($){return($.client??this.client).get({url:"/crm/pipelines/{id}",...$})}renameCrmPipeline($){return($.client??this.client).put({url:"/crm/pipelines/{id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}applyCrmPipelineOps($){return($.client??this.client).post({url:"/crm/pipelines/{id}/ops",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipelinePermissions($){return($.client??this.client).get({url:"/crm/pipelines/{id}/permissions",...$})}updateCrmPipelinePermissions($){return($.client??this.client).patch({url:"/crm/pipelines/{id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipelineRows($){return($.client??this.client).get({url:"/crm/pipelines/{id}/rows",...$})}queryCrmPipelineRows($){return($.client??this.client).post({url:"/crm/pipelines/{id}/rows",...$,headers:{"Content-Type":"application/json",...$.headers}})}shareCrmPipeline($){return($.client??this.client).put({url:"/crm/pipelines/{id}/sharing",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipelineTable($){return($.client??this.client).get({url:"/crm/pipelines/{id}/table",...$})}trashCrmPipeline($){return($.client??this.client).put({url:"/crm/pipelines/{id}/trash",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmTeamSettings($){return($?.client??this.client).get({url:"/crm/settings",...$})}putCrmTeamSettings($){return($.client??this.client).put({url:"/crm/settings",...$,headers:{"Content-Type":"application/json",...$.headers}})}resetCrmTeamStages($){return($?.client??this.client).delete({url:"/crm/stages",...$})}putCrmTeamStages($){return($.client??this.client).put({url:"/crm/stages",...$,headers:{"Content-Type":"application/json",...$.headers}})}listDatabases($){return($?.client??this.client).get({url:"/databases",...$})}createDatabase($){return($.client??this.client).post({url:"/databases",...$,headers:{"Content-Type":"application/json",...$.headers}})}saveDatabaseQuery($){return($.client??this.client).post({url:"/databases/queries",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabaseQuery($){return($.client??this.client).get({url:"/databases/queries/{query_id}",...$})}queryDatabases($){return($.client??this.client).post({url:"/databases/query",...$,headers:{"Content-Type":"application/json",...$.headers}})}ensureStarterHandler($){return($?.client??this.client).post({url:"/databases/starter",...$})}deliverDatabaseWebhook($){return($.client??this.client).post({url:"/databases/webhooks/{token}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabase($){return($.client??this.client).get({url:"/databases/{id}",...$})}shareDatabaseAwareness($){return($.client??this.client).put({url:"/databases/{id}/awareness",...$,headers:{"Content-Type":"application/json",...$.headers}})}undoDatabaseChange($){return($.client??this.client).post({url:"/databases/{id}/changes/{change}/undo",...$})}importDatabaseTable($){return($.client??this.client).post({url:"/databases/{id}/import",...$,headers:{"Content-Type":"application/json",...$.headers}})}applyDatabaseOps($){return($.client??this.client).post({url:"/databases/{id}/ops",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabasePermissions($){return($.client??this.client).get({url:"/databases/{id}/permissions",...$})}updateDatabasePermissions($){return($.client??this.client).patch({url:"/databases/{id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabaseTableChanges($){return($.client??this.client).get({url:"/databases/{id}/tables/{table_id}/changes",...$})}listDatabaseColumnCasts($){return($.client??this.client).get({url:"/databases/{id}/tables/{table_id}/columns/{column_id}/casts",...$})}convertDatabaseColumn($){return($.client??this.client).post({url:"/databases/{id}/tables/{table_id}/columns/{column_id}/conversion",...$,headers:{"Content-Type":"application/json",...$.headers}})}inferDatabaseColumnType($){return($.client??this.client).post({url:"/databases/{id}/tables/{table_id}/columns/{column_id}/infer-type",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabaseRowHistory($){return($.client??this.client).get({url:"/databases/{id}/tables/{table_id}/rows/{row_id}/history",...$})}getDatabaseViewPositions($){return($.client??this.client).get({url:"/databases/{id}/views/{view_id}/positions",...$})}listDatabaseWebhooks($){return($.client??this.client).get({url:"/databases/{id}/webhooks",...$})}createDatabaseWebhook($){return($.client??this.client).post({url:"/databases/{id}/webhooks",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteDatabaseWebhook($){return($.client??this.client).delete({url:"/databases/{id}/webhooks/{webhook_id}",...$})}transcribeDictation($){return($.client??this.client).post({bodySerializer:null,url:"/dictation/transcribe",...$,headers:{"Content-Type":"audio/webm",...$.headers}})}getUserDocumentsHandler($){return($.client??this.client).get({url:"/documents",...$})}createDocument($){return($.client??this.client).post({url:"/documents",...$,headers:{"Content-Type":"application/json",...$.headers}})}createCanvasHandler($){return($.client??this.client).post({url:"/documents/create_canvas",...$,headers:{"Content-Type":"application/json",...$.headers}})}createMarkdownHandler($){return($.client??this.client).post({url:"/documents/create_markdown",...$,headers:{"Content-Type":"application/json",...$.headers}})}createSkillHandler($){return($.client??this.client).post({url:"/documents/create_skill",...$,headers:{"Content-Type":"application/json",...$.headers}})}createSnippetHandler($){return($.client??this.client).post({url:"/documents/create_snippet",...$,headers:{"Content-Type":"application/json",...$.headers}})}createTaskHandler($){return($.client??this.client).post({url:"/documents/create_task",...$,headers:{"Content-Type":"application/json",...$.headers}})}getGithubPullRequestTasks($){return($.client??this.client).post({url:"/documents/github_prs/tasks",...$,headers:{"Content-Type":"application/json",...$.headers}})}initializeUserDocuments($){return($?.client??this.client).post({url:"/documents/initialize_user_documents",...$})}getDocumentListHandler($){return($?.client??this.client).get({url:"/documents/list",...$})}validateDocumentPermissionsToken($){return($.client??this.client).post({url:"/documents/permissions_token/validate",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentPermissionsToken($){return($.client??this.client).post({url:"/documents/permissions_token/{document_id}",...$})}presaveDocumentHandler($){return($.client??this.client).put({url:"/documents/presave/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getBatchPreviewHandler($){return($.client??this.client).post({url:"/documents/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentByTeamSlug($){return($.client??this.client).get({url:"/documents/slug/{slug}",...$})}handler($){return($?.client??this.client).get({url:"/documents/starter_docs",...$})}getSystemSkillsHandler($){return($?.client??this.client).get({url:"/documents/system_skills",...$})}deleteDocument($){return($.client??this.client).delete({url:"/documents/{document_id}",...$})}getDocument($){return($.client??this.client).get({url:"/documents/{document_id}",...$})}editDocument($){return($.client??this.client).patch({url:"/documents/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}saveDocumentHandler($){return($.client??this.client).put({url:"/documents/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentBranchName($){return($.client??this.client).get({url:"/documents/{document_id}/branch_name",...$})}copyDocument($){return($.client??this.client).post({url:"/documents/{document_id}/copy",...$,headers:{"Content-Type":"application/json",...$.headers}})}exportDocument($){return($.client??this.client).get({url:"/documents/{document_id}/export",...$})}getDocumentGithubPullRequests($){return($.client??this.client).get({url:"/documents/{document_id}/github_prs",...$})}getLocationHandler($){return($.client??this.client).get({url:"/documents/{document_id}/location",...$})}getDocumentLocationV3($){return($.client??this.client).get({url:"/documents/{document_id}/location_v3",...$})}permanentlyDeleteDocument($){return($.client??this.client).delete({url:"/documents/{document_id}/permanent",...$})}getDocumentProcessingResult($){return($.client??this.client).get({url:"/documents/{document_id}/processing",...$})}jobProcessingResultHandler($){return($.client??this.client).get({url:"/documents/{document_id}/processing/{job_id}",...$})}revertDeleteDocument($){return($.client??this.client).put({url:"/documents/{document_id}/revert_delete",...$})}getDocumentShortId($){return($.client??this.client).get({url:"/documents/{document_id}/short_id",...$})}simpleSave($){return($.client??this.client).put({url:"/documents/{document_id}/simple_save",...$})}getDocumentTeamShare($){return($.client??this.client).get({url:"/documents/{document_id}/team_share",...$})}setDocumentTeamShare($){return($.client??this.client).put({url:"/documents/{document_id}/team_share",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentTextContent($){return($.client??this.client).get({url:"/documents/{document_id}/text-content",...$})}getDocumentViewsHandler($){return($.client??this.client).get({url:"/documents/{document_id}/views",...$})}getDocumentVersion($){return($.client??this.client).get({url:"/documents/{document_id}/{document_version_id}",...$})}accessRequestsState($){return($.client??this.client).get({url:"/entities/{entity_type}/{entity_id}/access-requests",...$})}accessRequestsCancel($){return($.client??this.client).delete({url:"/entities/{entity_type}/{entity_id}/access-requests/mine",...$})}accessRequestsSubmit($){return($.client??this.client).put({url:"/entities/{entity_type}/{entity_id}/access-requests/mine",...$,headers:{"Content-Type":"application/json",...$.headers}})}accessRequestsResolve($){return($.client??this.client).post({url:"/entities/{entity_type}/{entity_id}/access-requests/{request_id}/resolve",...$,headers:{"Content-Type":"application/json",...$.headers}})}accessRequestsDirect($){return($.client??this.client).get({url:"/entities/{entity_type}/{entity_id}/direct-access",...$})}accessRequestsRemoveDirect($){return($.client??this.client).delete({url:"/entities/{entity_type}/{entity_id}/direct-access/{user_id}",...$})}accessRequestsSetDirect($){return($.client??this.client).put({url:"/entities/{entity_type}/{entity_id}/direct-access/{user_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getEntityPermission($){return($.client??this.client).get({url:"/entity/{entity_type}/{entity_id}/permissions",...$})}listFavorites($){return($?.client??this.client).get({url:"/favorites",...$})}addFavorite($){return($.client??this.client).post({url:"/favorites",...$,headers:{"Content-Type":"application/json",...$.headers}})}reorderFavorites($){return($.client??this.client).patch({url:"/favorites/reorder",...$,headers:{"Content-Type":"application/json",...$.headers}})}removeFavoriteByEntity($){return($.client??this.client).delete({url:"/favorites/{entity_type}/{entity_id}",...$})}getForeignEntityBySource($){return($.client??this.client).get({url:"/foreign_entity/by_source/{source}/{foreign_entity_id}",...$})}getForeignEntity($){return($.client??this.client).get({url:"/foreign_entity/{id}",...$})}listForms($){return($.client??this.client).get({url:"/forms",...$})}createForm($){return($.client??this.client).post({url:"/forms",...$,headers:{"Content-Type":"application/json",...$.headers}})}listAccessibleForms($){return($?.client??this.client).get({url:"/forms/accessible",...$})}getForm($){return($.client??this.client).get({url:"/forms/{id}",...$})}updateForm($){return($.client??this.client).patch({url:"/forms/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}collaborateForm($){return($.client??this.client).post({url:"/forms/{id}/collaboration",...$})}putFormLayout($){return($.client??this.client).put({url:"/forms/{id}/layout",...$,headers:{"Content-Type":"application/json",...$.headers}})}getFormPermissions($){return($.client??this.client).get({url:"/forms/{id}/permissions",...$})}updateFormPermissions($){return($.client??this.client).patch({url:"/forms/{id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}submitFormResponse($){return($.client??this.client).post({url:"/forms/{id}/responses",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMyFormResponse($){return($.client??this.client).get({url:"/forms/{id}/responses/mine",...$})}editMyFormResponse($){return($.client??this.client).put({url:"/forms/{id}/responses/mine",...$,headers:{"Content-Type":"application/json",...$.headers}})}getFormResponseSummary($){return($.client??this.client).get({url:"/forms/{id}/responses/summary",...$})}getFormTally($){return($.client??this.client).get({url:"/forms/{id}/tally",...$})}installSync($){return($?.client??this.client).get({url:"/github/install-sync",...$})}getGithubPullRequestFacets($){return($?.client??this.client).get({url:"/github_pull_requests/facets",...$})}getGithubPullRequest($){return($.client??this.client).get({url:"/github_pull_requests/{id}",...$})}getGithubPullRequestChanges($){return($.client??this.client).get({url:"/github_pull_requests/{id}/changes",...$})}getGithubPullRequestChangesPatch($){return($.client??this.client).get({url:"/github_pull_requests/{id}/changes/patch",...$})}createHarnessPairing($){return($.client??this.client).post({url:"/harness-pairings",...$,headers:{"Content-Type":"application/json",...$.headers}})}getHarnessPairing($){return($.client??this.client).get({url:"/harness-pairings/{code}",...$})}approveHarnessPairing($){return($.client??this.client).post({url:"/harness-pairings/{code}/approve",...$,headers:{"Content-Type":"application/json",...$.headers}})}claimHarnessPairing($){return($.client??this.client).post({url:"/harness-pairings/{pairing_id}/claim",...$,headers:{"Content-Type":"application/json",...$.headers}})}listHarnesses($){return($?.client??this.client).get({url:"/harnesses",...$})}deleteSelfHarness($){return($?.client??this.client).delete({url:"/harnesses/me",...$})}getSelfHarness($){return($?.client??this.client).get({url:"/harnesses/me",...$})}listHarnessAgents($){return($?.client??this.client).get({url:"/harnesses/me/agents",...$})}listHarnessSessions($){return($?.client??this.client).get({url:"/harnesses/me/sessions",...$})}deleteHarness($){return($.client??this.client).delete({url:"/harnesses/{harness_id}",...$})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}getHistoryHandler($){return($?.client??this.client).get({url:"/history",...$})}deleteHistoryHandler($){return($.client??this.client).delete({url:"/history/{item_type}/{item_id}",...$})}upsertHistoryHandler($){return($.client??this.client).post({url:"/history/{item_type}/{item_id}",...$})}listInitiatives($){return($?.client??this.client).get({url:"/initiatives",...$})}createInitiative($){return($.client??this.client).post({url:"/initiatives",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteInitiative($){return($.client??this.client).delete({url:"/initiatives/{initiative_id}",...$})}getInitiative($){return($.client??this.client).get({url:"/initiatives/{initiative_id}",...$})}updateInitiative($){return($.client??this.client).patch({url:"/initiatives/{initiative_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getInstructionsHandler($){return($?.client??this.client).get({url:"/instructions",...$})}createInstructionsHandler($){return($?.client??this.client).post({url:"/instructions",...$})}getItemsSoup($){return($?.client??this.client).get({url:"/items/soup",...$})}postItemsSoup($){return($.client??this.client).post({url:"/items/soup",...$,headers:{"Content-Type":"application/json",...$.headers}})}postItemsSoupAst($){return($.client??this.client).post({url:"/items/soup/ast",...$,headers:{"Content-Type":"application/json",...$.headers}})}postItemsSoupAstGrouped($){return($.client??this.client).post({url:"/items/soup/ast/grouped",...$,headers:{"Content-Type":"application/json",...$.headers}})}messageTimeline($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}",...$})}entityMessageCreate($){return($.client??this.client).post({url:"/messages/{parent_type}/{parent_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}entityMessageDeleteMessage($){return($.client??this.client).delete({url:"/messages/{parent_type}/{parent_id}/items/{id}",...$})}entityMessageGetMessage($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/items/{id}",...$})}entityMessageEdit($){return($.client??this.client).patch({url:"/messages/{parent_type}/{parent_id}/items/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}entityMessageReact($){return($.client??this.client).post({url:"/messages/{parent_type}/{parent_id}/items/{id}/reactions",...$,headers:{"Content-Type":"application/json",...$.headers}})}entityMessageLegacy($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/legacy/{legacy_id}",...$})}entityMessageDeleteThread($){return($.client??this.client).delete({url:"/messages/{parent_type}/{parent_id}/threads/{id}",...$})}entityMessageGetThread($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/threads/{id}",...$})}entityMessagePatchThread($){return($.client??this.client).patch({url:"/messages/{parent_type}/{parent_id}/threads/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}messageTimelineEntries($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/timeline",...$})}entityMessageTyping($){return($.client??this.client).post({url:"/messages/{parent_type}/{parent_id}/typing",...$,headers:{"Content-Type":"application/json",...$.headers}})}linkedAccount($){return($?.client??this.client).get({url:"/meta/linked/account",...$})}linkedChats($){return($?.client??this.client).get({url:"/meta/linked/chats",...$})}linkedConfiguration($){return($?.client??this.client).get({url:"/meta/linked/configuration",...$})}linkedConnect($){return($.client??this.client).post({url:"/meta/linked/connect",...$,headers:{"Content-Type":"application/json",...$.headers}})}linkedDisconnect($){return($.client??this.client).post({url:"/meta/linked/disconnect",...$,headers:{"Content-Type":"application/json",...$.headers}})}linkedAdopt($){return($.client??this.client).post({url:"/meta/linked/groups/adopt",...$,headers:{"Content-Type":"application/json",...$.headers}})}linkedCancelPairing($){return($.client??this.client).delete({url:"/meta/linked/pairing/{id}",...$})}linkedPairing($){return($.client??this.client).get({url:"/meta/linked/pairing/{id}",...$})}linkedPasskey($){return($.client??this.client).post({url:"/meta/linked/pairing/{id}/passkey",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappGroups($){return($?.client??this.client).get({url:"/meta/linked/whatsapp-groups",...$})}linkedDetach($){return($.client??this.client).delete({url:"/meta/linked/whatsapp-groups/{group_id}",...$})}whatsappGroup($){return($.client??this.client).get({url:"/meta/linked/whatsapp-groups/{group_id}",...$})}linkedUpload($){return($.client??this.client).post({..._1,url:"/meta/linked/whatsapp-groups/{group_id}/attachments",...$,headers:{"Content-Type":null,...$.headers}})}linkedDelivery($){return($.client??this.client).post({url:"/meta/linked/whatsapp-groups/{group_id}/delivery",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappGroupMessages($){return($.client??this.client).get({url:"/meta/linked/whatsapp-groups/{group_id}/messages",...$})}linkedMessageAttachments($){return($.client??this.client).post({url:"/meta/linked/whatsapp-groups/{group_id}/messages/attachments",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappGroupMessage($){return($.client??this.client).get({url:"/meta/linked/whatsapp-groups/{group_id}/messages/{message_id}",...$})}whatsappGroupPermissions($){return($.client??this.client).get({url:"/meta/linked/whatsapp-groups/{group_id}/permissions",...$})}whatsappGroupUpdatePermissions($){return($.client??this.client).patch({url:"/meta/linked/whatsapp-groups/{group_id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappGroupRead($){return($.client??this.client).post({url:"/meta/linked/whatsapp-groups/{group_id}/read",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappGroupSends($){return($.client??this.client).get({url:"/meta/linked/whatsapp-groups/{group_id}/sends",...$})}linkedReply($){return($.client??this.client).post({url:"/meta/linked/whatsapp-groups/{group_id}/sends",...$,headers:{"Content-Type":"application/json",...$.headers}})}getPinsHandler($){return($?.client??this.client).get({url:"/pins",...$})}reorderPinsHandler($){return($.client??this.client).patch({url:"/pins",...$,headers:{"Content-Type":"application/json",...$.headers}})}removePinHandler($){return($.client??this.client).delete({url:"/pins/{pinned_item_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}addPinHandler($){return($.client??this.client).post({url:"/pins/{pinned_item_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getProjectsHandler($){return($?.client??this.client).get({url:"/projects",...$})}createProjectHandler($){return($.client??this.client).post({url:"/projects",...$,headers:{"Content-Type":"application/json",...$.headers}})}getPendingProjectsHandler($){return($?.client??this.client).get({url:"/projects/pending",...$})}getBatchProjectPreview($){return($.client??this.client).post({url:"/projects/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}uploadFolderHandler($){return($.client??this.client).post({url:"/projects/upload",...$,headers:{"Content-Type":"application/json",...$.headers}})}uploadExtractFolderHandler($){return($.client??this.client).post({url:"/projects/upload_extract",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteProjectHandler($){return($.client??this.client).delete({url:"/projects/{id}",...$})}getProjectHandler($){return($.client??this.client).get({url:"/projects/{id}",...$})}getProjectUserAccessLevel($){return($.client??this.client).get({url:"/projects/{id}/access_level",...$})}getProjectContentHandler($){return($.client??this.client).get({url:"/projects/{id}/content",...$})}permanentlyDeleteProject($){return($.client??this.client).delete({url:"/projects/{id}/permanent",...$})}getProjectPermissionsV2($){return($.client??this.client).get({url:"/projects/{id}/permissions",...$})}revertDeleteProject($){return($.client??this.client).put({url:"/projects/{id}/revert_delete",...$})}recentlyDeleted($){return($?.client??this.client).get({url:"/recents/deleted",...$})}listEmailReminders($){return($?.client??this.client).get({url:"/reminders/email/collection",...$})}getEmailFollowup($){return($.client??this.client).get({url:"/reminders/email/{thread_id}",...$})}setEmailFollowup($){return($.client??this.client).put({url:"/reminders/email/{thread_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getViewsHandler($){return($?.client??this.client).get({url:"/saved_views",...$})}createViewHandler($){return($.client??this.client).post({url:"/saved_views",...$,headers:{"Content-Type":"application/json",...$.headers}})}excludeDefaultViewHandler($){return($.client??this.client).post({url:"/saved_views/exclude_default",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteViewHandler($){return($.client??this.client).delete({url:"/saved_views/{saved_view_id}",...$})}patchViewHandler($){return($.client??this.client).patch({url:"/saved_views/{saved_view_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}listSlackImports($){return($?.client??this.client).get({url:"/slack/imports",...$})}createSlackImport($){return($.client??this.client).post({url:"/slack/imports",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSlackImport($){return($.client??this.client).get({url:"/slack/imports/{job_id}",...$})}cancelSlackImport($){return($.client??this.client).post({url:"/slack/imports/{job_id}/cancel",...$})}finalizeSlackImport($){return($.client??this.client).post({url:"/slack/imports/{job_id}/finalize",...$})}registerSlackImportUploads($){return($.client??this.client).post({url:"/slack/imports/{job_id}/uploads",...$,headers:{"Content-Type":"application/json",...$.headers}})}completeSlackImportUploads($){return($.client??this.client).post({url:"/slack/imports/{job_id}/uploads/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}bulkWakeupSyncServiceDocuments($){return($.client??this.client).post({url:"/sync_service/wakeup",...$,headers:{"Content-Type":"application/json",...$.headers}})}editThreadV2($){return($.client??this.client).patch({url:"/threads/{thread_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}listUserApiKeys($){return($?.client??this.client).get({url:"/user-api-keys",...$})}createUserApiKey($){return($.client??this.client).post({url:"/user-api-keys",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteUserApiKey($){return($.client??this.client).delete({url:"/user-api-keys/{id}",...$})}deleteUserDocumentViewLocation($){return($.client??this.client).delete({url:"/user_document_view_location/{document_id}",...$})}getUserDocumentViewLocation($){return($.client??this.client).get({url:"/user_document_view_location/{document_id}",...$})}upsertUserDocumentViewLocation($){return($.client??this.client).post({url:"/user_document_view_location/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentPermissionsV2($){return($.client??this.client).get({url:"/v2/documents/{document_id}/permissions",...$})}editProjectV2($){return($.client??this.client).patch({url:"/v2/projects/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}streamEvents($){return($.client??this.client).sse.get({url:"/webhook/events/stream",...$})}listWebhooks($){return($?.client??this.client).get({url:"/webhook/webhooks",...$})}createWebhook($){return($.client??this.client).post({url:"/webhook/webhooks",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteWebhook($){return($.client??this.client).delete({url:"/webhook/webhooks/{webhook_id}",...$})}getWebhook($){return($.client??this.client).get({url:"/webhook/webhooks/{webhook_id}",...$})}patchWebhook($){return($.client??this.client).patch({url:"/webhook/webhooks/{webhook_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}validateWebhook($){return($.client??this.client).post({url:"/webhook/webhooks/{webhook_id}/validate",...$})}}function J6({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((W)=>setTimeout(W,V)));return{stream:async function*(){let V=K??3000,W=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;W++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:l,value:r}=await H.read();if(l)break;U+=r,U=U.replace(/\r\n?/g,`
`);let g=U.split(`
`);U=g.pop()??"";for(let p of g){let a=p.split(`
diff --git a/crates/whatsapp_e2e/Cargo.toml b/crates/whatsapp_e2e/Cargo.toml
index ae36881766..6e6f8d0e51 100644
--- a/crates/whatsapp_e2e/Cargo.toml
+++ b/crates/whatsapp_e2e/Cargo.toml
@@ -23,6 +23,7 @@ workspace-hack = { version = "0.1", path = "../workspace-hack" }
zeroize = { workspace = true }
[dev-dependencies]
+macro_user_id = { path = "../macro_user_id" }
chrono = { workspace = true }
whatsmeow_signal = { path = "../whatsmeow_signal" }
macro_db_migrator = { path = "../macro_db_migrator" }
diff --git a/crates/whatsapp_e2e/src/test.rs b/crates/whatsapp_e2e/src/test.rs
index b4ff63319f..00e6b80553 100644
--- a/crates/whatsapp_e2e/src/test.rs
+++ b/crates/whatsapp_e2e/src/test.rs
@@ -16,7 +16,7 @@ use whatsapp_fake_server::{FakePhone, FakeWhatsApp};
use whatsapp_linked::domain::models::{
AccountState, AdoptGroup, Binding, ChatKind, Features, ReplyContent, SendAuthority, SendReply,
};
-use whatsapp_linked::domain::ports::{Authorizer, LinkedResult};
+use whatsapp_linked::domain::ports::LinkedResult;
use whatsapp_linked::domain::service::LinkedService;
use whatsapp_linked::outbound::pg::PgLinkedRepository;
use whatsmeow::types::Jid;
@@ -28,6 +28,11 @@ mod group_kinds;
mod message_types;
const TIMEOUT: Duration = Duration::from_secs(60);
+/// A test user's id, typed.
+fn person(user: &str) -> macro_user_id::user_id::MacroUserIdStr<'static> {
+ user.to_owned().try_into().expect("test user ids are valid")
+}
+
const ALICE: &str = "macro|[email protected]";
const BOB: &str = "macro|[email protected]";
@@ -50,13 +55,6 @@ async fn take_fleet_slot(pool: &PgPool) -> PgConnection {
struct Allow;
-#[async_trait]
-impl Authorizer for Allow {
- async fn require_group_owner(&self, _: Uuid, _: &str) -> LinkedResult<()> {
- Ok(())
- }
-}
-
/// The database, the DSS-side domain service and the fake WhatsApp world:
/// Alice and Bob (Macro users with their own WhatsApp) and a customer who is
/// only on WhatsApp, all in one group.
@@ -88,7 +86,6 @@ impl World {
},
Arc::new(PgLinkedRepository::new(pool.clone())),
Arc::new(Allow),
- Arc::new(Allow),
);
let whatsapp = FakeWhatsApp::start().await.unwrap();
let alice = whatsapp.add_user("15550000001", "Alice").await;
@@ -118,12 +115,12 @@ impl World {
async fn pair(&self, user: &str, phone: &FakePhone) -> Jid {
let pairing = self
.linked
- .connect(user, false, SendAuthority::Human)
+ .connect(&person(user), false, SendAuthority::Human)
.await
.unwrap();
let qr = wait_for_rows(&self.pool, TIMEOUT, || async {
self.linked
- .pair_state(user, pairing.id, SendAuthority::Human)
+ .pair_state(&person(user), pairing.id, SendAuthority::Human)
.await
.ok()?
.qr
@@ -136,7 +133,7 @@ impl World {
.expect("the phone approves the QR code");
let identity = phone.jid().to_string();
wait_for_rows(&self.pool, TIMEOUT, || async {
- let account = self.linked.account(user).await.ok()??;
+ let account = self.linked.account(&person(user)).await.ok()??;
(account.state == AccountState::Connected
&& account.identity_jid.as_deref() == Some(identity.as_str()))
.then_some(())
@@ -162,7 +159,7 @@ impl World {
async fn adopt(&self, user: &str, users: &[&str]) -> Binding {
let group = self.group.to_string();
wait_for_rows(&self.pool, TIMEOUT, || async {
- let chats = self.linked.chats(user).await.ok()?.chats;
+ let chats = self.linked.chats(&person(user)).await.ok()?.chats;
chats
.iter()
.any(|chat| chat.jid == group && chat.can_add)
@@ -172,7 +169,11 @@ impl World {
.expect("the replica lists the group");
let binding = self
.linked
- .adopt(user, &AdoptGroup { group_jid: group }, SendAuthority::Human)
+ .adopt(
+ &person(user),
+ &AdoptGroup { group_jid: group },
+ SendAuthority::Human,
+ )
.await
.unwrap();
let mut tx = self.pool.begin().await.unwrap();
@@ -195,7 +196,7 @@ impl World {
/// A viewer opens the WhatsApp page; their account's refreshed roster
/// makes it an observer of a group shared with them.
async fn observe(&self, user: &str, binding: &Binding) {
- self.linked.chats(user).await.unwrap();
+ self.linked.chats(&person(user)).await.unwrap();
let observing = wait_for_rows(&self.pool, TIMEOUT, || async {
sqlx::query_scalar!(
r#"SELECT m.account_id FROM whatsapp_group_membership m
@@ -851,7 +852,7 @@ async fn a_message_queued_before_a_crash_is_ingested_once(pool: PgPool) {
#[async_trait]
impl whatsapp_linked::domain::ports::SendRateLimiter for Allow {
- async fn check(&self, _: &str) -> LinkedResult<()> {
+ async fn check(&self, _: &macro_user_id::user_id::MacroUserIdStr<'_>) -> LinkedResult<()> {
Ok(())
}
}
@@ -918,7 +919,7 @@ async fn group_renames_and_removals_in_whatsapp_reach_macro_live(pool: PgPool) {
.await;
let detail = world
.linked
- .adopted_groups(ALICE)
+ .adopted_groups(&person(ALICE))
.await
.unwrap()
.into_iter()
@@ -1081,7 +1082,7 @@ async fn adding_a_group_imports_its_earlier_messages_once_without_notifying(pool
);
let summary = world
.linked
- .adopted_groups(ALICE)
+ .adopted_groups(&person(ALICE))
.await
.unwrap()
.into_iter()
@@ -1155,6 +1156,38 @@ async fn backfill_waits_for_an_offline_phone_and_never_duplicates_live_messages(
replica.drain(TIMEOUT).await.unwrap();
}
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_quiet_group_waits_for_its_first_message_then_imports(pool: PgPool) {
+ let world = World::new(pool).await;
+ let replica = world.replica().await;
+ world.pair(ALICE, &world.alice).await;
+ let binding = world.adopt(ALICE, &[]).await;
+ assert_eq!(
+ backfill_state(&world, &binding, &["waiting_for_message"]).await,
+ ("waiting_for_message".to_owned(), 0),
+ "nobody posted: nothing to start importing from"
+ );
+
+ let first = world
+ .customer
+ .send_text(&world.group, "anyone here?")
+ .await
+ .unwrap();
+ world.timeline(&binding, &first).await;
+ assert_eq!(
+ backfill_state(&world, &binding, &["done", "partial"])
+ .await
+ .0,
+ "done",
+ "the first message starts the import, which finds nothing earlier"
+ );
+ assert_eq!(
+ origins(&world.pool, binding.id).await,
+ [("anyone here?".to_owned(), "whatsapp".to_owned())]
+ );
+ replica.drain(TIMEOUT).await.unwrap();
+}
+
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn the_chat_list_follows_history_sync_and_live_messages(pool: PgPool) {
let world = World::new(pool).await;
@@ -1177,7 +1210,7 @@ async fn the_chat_list_follows_history_sync_and_live_messages(pool: PgPool) {
.await
.unwrap();
let listed = wait_for_rows(&world.pool, TIMEOUT, || async {
- let chats = world.linked.chats(ALICE).await.ok()?.chats;
+ let chats = world.linked.chats(&person(ALICE)).await.ok()?.chats;
let direct = chats
.iter()
.find(|chat| chat.jid == world.customer.jid().to_string())?
@@ -1213,7 +1246,7 @@ async fn the_chat_list_follows_history_sync_and_live_messages(pool: PgPool) {
.await
.unwrap();
let top = wait_for_rows(&world.pool, TIMEOUT, || async {
- let chats = world.linked.chats(ALICE).await.ok()?.chats;
+ let chats = world.linked.chats(&person(ALICE)).await.ok()?.chats;
(chats.first()?.jid == world.bob.jid().to_string()).then(|| chats[0].clone())
})
.await;
@@ -1221,3 +1254,35 @@ async fn the_chat_list_follows_history_sync_and_live_messages(pool: PgPool) {
assert_eq!(top.name, "Bob");
replica.drain(TIMEOUT).await.unwrap();
}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_device_whose_kms_key_was_lost_asks_to_reconnect_and_pairs_again(pool: PgPool) {
+ let world = World::new(pool).await;
+ let replica = world.replica().await;
+ world.pair(ALICE, &world.alice).await;
+ replica.drain(TIMEOUT).await.unwrap();
+
+ // KMS lost the key that wrapped Alice's device (a new LocalStack): the
+ // next replica can never read it, so Alice is asked to reconnect.
+ let lost = Replica::start(
+ &world.pool.connect_options(),
+ &world.whatsapp,
+ &SharedKms::new(),
+ )
+ .await;
+ let logged_out = wait_for_rows(&world.pool, TIMEOUT, || async {
+ let account = world.linked.account(&person(ALICE)).await.ok()??;
+ (account.state == AccountState::LoggedOut).then_some(())
+ })
+ .await;
+ world
+ .expect(
+ logged_out,
+ "an unreadable device marks the account logged out",
+ )
+ .await;
+
+ // Pairing again replaces the device instead of failing to open it.
+ world.pair(ALICE, &world.alice).await;
+ lost.drain(TIMEOUT).await.unwrap();
+}
diff --git a/crates/whatsapp_e2e/src/test/direct_chats.rs b/crates/whatsapp_e2e/src/test/direct_chats.rs
index 94ef35dfb0..ad7f5823d4 100644
--- a/crates/whatsapp_e2e/src/test/direct_chats.rs
+++ b/crates/whatsapp_e2e/src/test/direct_chats.rs
@@ -13,7 +13,7 @@ async fn listed_customer_chat(world: &World) -> whatsapp_linked::domain::models:
let chat = wait_for_rows(&world.pool, TIMEOUT, || async {
world
.linked
- .chats(ALICE)
+ .chats(&person(ALICE))
.await
.ok()?
.chats
@@ -72,7 +72,7 @@ async fn a_direct_chat_imports_its_history_and_works_both_ways(pool: PgPool) {
let binding = world
.linked
.adopt(
- ALICE,
+ &person(ALICE),
&AdoptGroup {
group_jid: chat.jid.clone(),
},
@@ -194,7 +194,11 @@ async fn a_direct_chat_imports_its_history_and_works_both_ways(pool: PgPool) {
);
let read = world
.linked
- .messages(&receipt::<ViewAccessLevel>(BOB, binding.id), None, 100)
+ .messages(
+ &receipt::<ViewAccessLevel>(BOB, binding.id),
+ None,
+ Some(100),
+ )
.await
.unwrap()
.messages;
diff --git a/crates/whatsapp_e2e/src/test/group_kinds.rs b/crates/whatsapp_e2e/src/test/group_kinds.rs
index c51cdbf87f..985dde2ea9 100644
--- a/crates/whatsapp_e2e/src/test/group_kinds.rs
+++ b/crates/whatsapp_e2e/src/test/group_kinds.rs
@@ -125,7 +125,7 @@ async fn a_communitys_groups_are_added_and_used_but_not_the_community(pool: PgPo
let garden_jid = garden.to_string();
let chats = wait_for_rows(&world.pool, TIMEOUT, || async {
- let chats = world.linked.chats(ALICE).await.ok()?.chats;
+ let chats = world.linked.chats(&person(ALICE)).await.ok()?.chats;
chats
.iter()
.any(|chat| chat.jid == garden_jid)
@@ -157,7 +157,11 @@ async fn a_communitys_groups_are_added_and_used_but_not_the_community(pool: PgPo
group_jid: jid.to_string(),
};
let linked = &world.linked;
- async move { linked.adopt(ALICE, &request, SendAuthority::Human).await }
+ async move {
+ linked
+ .adopt(&person(ALICE), &request, SendAuthority::Human)
+ .await
+ }
};
assert!(matches!(
adopt(&community).await.unwrap_err().current_context(),
@@ -171,7 +175,7 @@ async fn a_communitys_groups_are_added_and_used_but_not_the_community(pool: PgPo
.group_detail(&receipt::<ViewAccessLevel>(ALICE, binding.id))
.await
.unwrap();
- assert_eq!(detail.community, Some(neighbours(false)));
+ assert_eq!(detail.group.community, Some(neighbours(false)));
assert!(detail.group.can_send);
let tomatoes = world
.customer
@@ -199,7 +203,7 @@ async fn a_communitys_groups_are_added_and_used_but_not_the_community(pool: PgPo
.group_detail(&receipt::<ViewAccessLevel>(ALICE, notices.id))
.await
.unwrap();
- assert_eq!(detail.community, Some(neighbours(true)));
+ assert_eq!(detail.group.community, Some(neighbours(true)));
assert_eq!(
detail.group.send_reason,
Some(ReplyBlock::NotAllowedInGroup)
diff --git a/crates/whatsapp_e2e/src/test/message_types.rs b/crates/whatsapp_e2e/src/test/message_types.rs
index 7ba05f6486..570fc3c240 100644
--- a/crates/whatsapp_e2e/src/test/message_types.rs
+++ b/crates/whatsapp_e2e/src/test/message_types.rs
@@ -38,7 +38,11 @@ async fn shown(world: &World, binding: &Binding, source: &str) -> WhatsAppGroupM
.unwrap();
world
.linked
- .messages(&receipt::<ViewAccessLevel>(ALICE, binding.id), None, 100)
+ .messages(
+ &receipt::<ViewAccessLevel>(ALICE, binding.id),
+ None,
+ Some(100),
+ )
.await
.unwrap()
.messages
@@ -904,7 +908,11 @@ async fn group_changes_land_once_as_system_lines_that_never_notify(pool: PgPool)
let page = world
.linked
- .messages(&receipt::<ViewAccessLevel>(ALICE, binding.id), None, 100)
+ .messages(
+ &receipt::<ViewAccessLevel>(ALICE, binding.id),
+ None,
+ Some(100),
+ )
.await
.unwrap()
.messages;
@@ -965,7 +973,7 @@ async fn group_changes_land_once_as_system_lines_that_never_notify(pool: PgPool)
// Only the three texts are unread, and only they notify.
let summary = world
.linked
- .adopted_groups(ALICE)
+ .adopted_groups(&person(ALICE))
.await
.unwrap()
.into_iter()
diff --git a/crates/whatsapp_linked/AGENTS.md b/crates/whatsapp_linked/AGENTS.md
index 0f63a674db..bbdc3d6f72 100644
--- a/crates/whatsapp_linked/AGENTS.md
+++ b/crates/whatsapp_linked/AGENTS.md
@@ -35,22 +35,31 @@ rows and `NOTIFY` (the `outbound::pg` notify helper).
- `src/outbound/pg/chats.rs`: the account's chat list (`whatsapp_chat`,
`GET /chats` via `LinkedService::chats`) and importing earlier messages of
added groups (`backfill_*` columns on `whatsapp_group`; limits
- `BACKFILL_MESSAGE_LIMIT` / `BACKFILL_MAX_AGE_DAYS` in `models.rs`). History
+ `BACKFILL_MESSAGE_LIMIT` / `BACKFILL_MAX_AGE_DAYS` in `models.rs`). The
+ anchor is the chat's `whatsapp_chat.anchor`, else the newest stored message
+ the account saw; without one the group is `waiting_for_message` until a chat
+ update brings one. History
messages skip the adoption-time boundary but only reach the account owner's
own groups (`observed_bindings_in`).
- `src/outbound/pg/sends.rs`: enqueue, claim, dispatch fence, outcome. A
repeated intent key returns the stored send before any other check.
-- `src/outbound/pg.rs` `signals`: JSON `NOTIFY` payloads with `traceparent`
- (`src/outbound/trace_context.rs`). Every write a page shows calls
+- `src/signals.rs`: `NOTIFY` channels and JSON payloads with `traceparent`
+ (`src/signals/trace_context.rs`), public so DSS and the session service
+ never import `outbound`; `src/outbound/pg.rs` sends them inside the
+ writing transaction. Every write a page shows calls
`notify_change` (`whatsapp_changed`); DSS pushes it to viewers. Roster writes
signal only real changes (`groups.rs` `same_facts`).
-- Migrations: `crates/macro_db_client/migrations/20261027061310_whatsapp_linked.sql` (the
- final schema, including the one view rule `whatsapp_group_access_level`,
- which entity_access also calls) and `20261027061311_validate_entity_whatsapp_group_type.sql`
- (validates the entity type check in its own transaction).
+- Migrations:
+ `crates/macro_db_client/migrations/20261027061310_whatsapp_linked.sql` (the
+ final schema, including the one view rule `whatsapp_group_access_level`, which
+ entity_access also calls) and
+ `20261027061311_validate_entity_whatsapp_group_type.sql` (validates the entity
+ type check in its own transaction). Deleting a user cascades to their account,
+ chats (with their grants, entity record and sharing settings) and sends;
+ aliases outlive the account that saw them.
## Boundaries
-- Depends on: `entity_access` (group receipts, authorizer), `entity_access_db_utils`
+- Depends on: `entity_access` (group receipts; owner-only routes take an owner receipt), `entity_access_db_utils`
(ordinary grants), `entity_registry_db_utils`, and `share_permission_db_utils`.
- Used by: DSS (`src/whatsapp_linked.rs` composition), the session service.
@@ -72,7 +81,7 @@ rows and `NOTIFY` (the `outbound::pg` notify helper).
- Bot view receipts can read a known shared group, but never borrow an acting user's phone, send records, or unread cursor.
- View access uses ordinary `entity_access` grants (people, teams, and channels
through mentions) and link/team sharing, independent of WhatsApp membership;
- `whatsapp_group_can_view` must resolve the same sources as `entity_access`. Only the adopter receives an owner grant; use the generic
+ `whatsapp_group_can_view` and entity_access both call `whatsapp_group_access_level`; change the rule only there. Only the adopter receives an owner grant; use the generic
direct-access endpoints to share with people.
- `src/domain/timeline.rs` and `src/domain/service/timeline.rs` own list/detail,
timeline, unread and sharing use cases. Group HTTP paths are
diff --git a/crates/whatsapp_linked/Cargo.toml b/crates/whatsapp_linked/Cargo.toml
index 1bd2246453..023e2e72cb 100644
--- a/crates/whatsapp_linked/Cargo.toml
+++ b/crates/whatsapp_linked/Cargo.toml
@@ -12,7 +12,6 @@ ports = [
"dep:entity_access",
"dep:image",
"dep:macro_user_id",
- "dep:nom",
"dep:rootcause",
"entity_access/ports",
]
@@ -57,7 +56,7 @@ entity_access = { path = "../entity_access", default-features = false, optional
image = { workspace = true, optional = true }
macro_authorization = { path = "../macro_authorization", default-features = false, features = ["axum"], optional = true }
macro_user_id = { path = "../macro_user_id", optional = true }
-nom = { workspace = true, optional = true }
+nom = { workspace = true }
rootcause = { workspace = true, optional = true }
serde = { workspace = true }
serde_json = { workspace = true }
diff --git a/crates/whatsapp_linked/src/domain.rs b/crates/whatsapp_linked/src/domain.rs
index 35ee0f0c64..85085c3f15 100644
--- a/crates/whatsapp_linked/src/domain.rs
+++ b/crates/whatsapp_linked/src/domain.rs
@@ -1,5 +1,7 @@
/// Session-service event and command types.
pub mod events;
+/// WhatsApp JIDs.
+pub mod jid;
/// Account, binding and send models shared with the web app.
pub mod models;
/// Polls, locations, contact cards, events and system lines.
diff --git a/crates/whatsapp_linked/src/domain/effects.rs b/crates/whatsapp_linked/src/domain/effects.rs
index 2834f5ea5d..80057da5ea 100644
--- a/crates/whatsapp_linked/src/domain/effects.rs
+++ b/crates/whatsapp_linked/src/domain/effects.rs
@@ -51,6 +51,7 @@ impl EffectsService {
tracing::warn!(
message_id = %effect.message_id,
code = error.current_context().code(),
+ error = %error,
"WhatsApp group notification will retry"
);
self.repository.defer_effect(effect.message_id).await?;
diff --git a/crates/whatsapp_linked/src/domain/events.rs b/crates/whatsapp_linked/src/domain/events.rs
index e7999e99f8..70993e3f79 100644
--- a/crates/whatsapp_linked/src/domain/events.rs
+++ b/crates/whatsapp_linked/src/domain/events.rs
@@ -77,13 +77,16 @@ pub enum PairingUpdate {
/// Verified phone-number JID of the linked account.
identity_jid: String,
},
+ /// WhatsApp's QR session ran out of codes before any was scanned.
+ Expired,
/// Pairing failed.
Failed,
}
/// Kind of a normalized group message.
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, strum::IntoStaticStr)]
#[serde(rename_all = "snake_case")]
+#[strum(serialize_all = "snake_case")]
pub enum MessageKind {
/// Text, possibly quoting `target`.
Text,
@@ -108,24 +111,7 @@ pub enum MessageKind {
impl MessageKind {
/// Snake-case name, as serialized.
pub fn as_str(self) -> &'static str {
- match self {
- Self::Text => "text",
- Self::Reaction => "reaction",
- Self::Edit => "edit",
- Self::Delete => "delete",
- Self::Unsupported => "unsupported",
- Self::Rich => "rich",
- Self::System => "system",
- Self::PollVote => "poll_vote",
- }
- }
-
- /// A new timeline entry rather than a change to an existing one.
- pub fn is_entry(self) -> bool {
- matches!(
- self,
- Self::Text | Self::Unsupported | Self::Rich | Self::System
- )
+ self.into()
}
}
diff --git a/crates/whatsapp_linked/src/domain/jid.rs b/crates/whatsapp_linked/src/domain/jid.rs
new file mode 100644
index 0000000000..13bbfff525
--- /dev/null
+++ b/crates/whatsapp_linked/src/domain/jid.rs
@@ -0,0 +1,94 @@
+//! WhatsApp JIDs as Macro stores them: a group (`<digits>[-<digits>]@g.us`), a
+//! person by phone number (`<digits>@s.whatsapp.net`) or by LID
+//! (`<digits>@lid`). Parsed once, with one length limit for every kind.
+
+use nom::{
+ IResult, Parser,
+ branch::alt,
+ bytes::complete::{tag, take_while1},
+ character::complete::char,
+ combinator::{all_consuming, opt, recognize, value},
+ sequence::{pair, preceded},
+};
+
+/// Longest user part (before `@`) Macro accepts.
+const USER_LIMIT: usize = 64;
+
+/// What a JID addresses.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum JidKind {
+ /// A group or community.
+ Group,
+ /// A person, by phone number.
+ Phone,
+ /// A person, by WhatsApp's LID.
+ Lid,
+}
+
+/// A parsed WhatsApp JID borrowed from its text.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct Jid<'a> {
+ /// The part before `@`.
+ pub user: &'a str,
+ /// What it addresses.
+ pub kind: JidKind,
+}
+
+fn digits(input: &str) -> IResult<&str, &str> {
+ take_while1(|c: char| c.is_ascii_digit())(input)
+}
+
+fn jid(input: &str) -> IResult<&str, Jid<'_>> {
+ let group = pair(
+ recognize(pair(digits, opt(preceded(char('-'), digits)))),
+ value(JidKind::Group, tag("@g.us")),
+ );
+ let person = pair(
+ digits,
+ alt((
+ value(JidKind::Phone, tag("@s.whatsapp.net")),
+ value(JidKind::Lid, tag("@lid")),
+ )),
+ );
+ all_consuming(alt((group, person)))
+ .map(|(user, kind)| Jid { user, kind })
+ .parse(input)
+}
+
+impl<'a> Jid<'a> {
+ /// Parse a group, phone-number or LID JID; anything else is `None`.
+ pub fn parse(text: &'a str) -> Option<Self> {
+ jid(text)
+ .ok()
+ .map(|(_, jid)| jid)
+ .filter(|jid| jid.user.len() <= USER_LIMIT)
+ }
+
+ /// A person (phone number or LID), not a group.
+ pub fn is_person(self) -> bool {
+ matches!(self.kind, JidKind::Phone | JidKind::Lid)
+ }
+
+ /// The phone number, `+<digits>`, of a phone-number JID.
+ pub fn phone_number(self) -> Option<String> {
+ (self.kind == JidKind::Phone).then(|| format!("+{}", self.user))
+ }
+}
+
+/// A group JID.
+pub fn is_group_jid(text: &str) -> bool {
+ Jid::parse(text).is_some_and(|jid| jid.kind == JidKind::Group)
+}
+
+/// A phone-number or LID JID.
+pub fn is_person_jid(text: &str) -> bool {
+ Jid::parse(text).is_some_and(Jid::is_person)
+}
+
+/// `+<digits>` for a phone-number JID.
+pub fn phone_number(text: &str) -> Option<String> {
+ Jid::parse(text).and_then(Jid::phone_number)
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/whatsapp_linked/src/domain/jid/test.rs b/crates/whatsapp_linked/src/domain/jid/test.rs
new file mode 100644
index 0000000000..cd150205f5
--- /dev/null
+++ b/crates/whatsapp_linked/src/domain/jid/test.rs
@@ -0,0 +1,39 @@
+use super::*;
+
+#[test]
+fn every_kind_parses_with_one_limit() {
+ for (text, kind) in [
+ ("[email protected]", Some(JidKind::Group)),
+ ("[email protected]", Some(JidKind::Group)),
+ ("[email protected]", Some(JidKind::Phone)),
+ ("987654321@lid", Some(JidKind::Lid)),
+ ("@g.us", None),
+ ("[email protected]", None),
+ ("[email protected]", None),
+ ("[email protected]", None),
+ ("[email protected]", None),
+ ("15551234567:[email protected]", None),
+ ("status@broadcast", None),
+ ("", None),
+ ] {
+ assert_eq!(Jid::parse(text).map(|jid| jid.kind), kind, "{text}");
+ }
+ let longest = format!("{}@lid", "1".repeat(USER_LIMIT));
+ assert!(is_person_jid(&longest));
+ let too_long = format!("{}@lid", "1".repeat(USER_LIMIT + 1));
+ assert!(!is_person_jid(&too_long));
+ assert!(!is_group_jid(&format!(
+ "{}@g.us",
+ "1".repeat(USER_LIMIT + 1)
+ )));
+}
+
+#[test]
+fn only_phone_number_jids_have_a_number() {
+ assert_eq!(
+ phone_number("[email protected]").as_deref(),
+ Some("+15551234567")
+ );
+ assert_eq!(phone_number("987654321@lid"), None);
+ assert_eq!(phone_number("[email protected]"), None);
+}
diff --git a/crates/whatsapp_linked/src/domain/media.rs b/crates/whatsapp_linked/src/domain/media.rs
index 90f964e03f..8d377ed1ef 100644
--- a/crates/whatsapp_linked/src/domain/media.rs
+++ b/crates/whatsapp_linked/src/domain/media.rs
@@ -36,7 +36,11 @@ impl MediaService {
tracing::Span::current().record("due", due.len());
let mut imported = 0;
for import in &due {
- match self.documents.store(import).await {
+ // One file's bytes in memory at a time.
+ let Some(bytes) = self.repository.import_bytes(import).await? else {
+ continue;
+ };
+ match self.documents.store(import, bytes).await {
Ok(()) => {
self.repository.import_stored(import).await?;
imported += 1;
@@ -46,6 +50,7 @@ impl MediaService {
document_id = %import.document_id,
attempts = import.attempts,
code = error.current_context().code(),
+ error = %error,
"WhatsApp attachment import will retry"
);
self.repository
@@ -58,7 +63,8 @@ impl MediaService {
Ok(imported)
}
- /// Delete staged uploads that were never sent and old participant receipts.
+ /// Delete staged uploads that were never sent, old participant receipts
+ /// and old consumed pairings.
pub async fn expire_retained(&self) -> LinkedResult<u64> {
self.repository.expire_retained().await
}
diff --git a/crates/whatsapp_linked/src/domain/models.rs b/crates/whatsapp_linked/src/domain/models.rs
index ee8af37f33..24ce985400 100644
--- a/crates/whatsapp_linked/src/domain/models.rs
+++ b/crates/whatsapp_linked/src/domain/models.rs
@@ -7,6 +7,7 @@ use uuid::Uuid;
/// Independently controlled backend rollout switches. None grants access.
#[derive(Debug, Clone, Copy, Default, Serialize)]
+#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "schema", schema(as = LinkedFeatures))]
pub struct Features {
@@ -20,10 +21,21 @@ pub struct Features {
/// Account lifecycle. Transport outages are not stored: a connected account
/// stays connected while its session service reconnects.
-#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
+#[derive(
+ Debug,
+ Clone,
+ Copy,
+ Serialize,
+ Deserialize,
+ PartialEq,
+ Eq,
+ strum::IntoStaticStr,
+ strum::EnumString,
+)]
#[serde(rename_all = "snake_case")]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "schema", schema(as = LinkedAccountState))]
+#[strum(serialize_all = "snake_case")]
pub enum AccountState {
/// A pairing transaction is in progress.
Pairing,
@@ -37,29 +49,19 @@ pub enum AccountState {
impl AccountState {
/// Stable storage spelling.
- pub const fn as_str(self) -> &'static str {
- match self {
- Self::Pairing => "pairing",
- Self::Connected => "connected",
- Self::LoggedOut => "logged_out",
- Self::Disconnected => "disconnected",
- }
+ pub fn as_str(self) -> &'static str {
+ self.into()
}
/// Parse the storage spelling.
pub fn parse(value: &str) -> Option<Self> {
- Some(match value {
- "pairing" => Self::Pairing,
- "connected" => Self::Connected,
- "logged_out" => Self::LoggedOut,
- "disconnected" => Self::Disconnected,
- _ => return None,
- })
+ value.parse().ok()
}
}
/// One person's account, never owned by a workspace.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "schema", schema(as = LinkedAccount))]
pub struct Account {
@@ -76,10 +78,21 @@ pub struct Account {
}
/// Pairing transaction state.
-#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
+#[derive(
+ Debug,
+ Clone,
+ Copy,
+ Serialize,
+ Deserialize,
+ PartialEq,
+ Eq,
+ strum::IntoStaticStr,
+ strum::EnumString,
+)]
#[serde(rename_all = "snake_case")]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "schema", schema(as = LinkedPairingState))]
+#[strum(serialize_all = "snake_case")]
pub enum PairingState {
/// Waiting for a session-service replica to start the device.
Waiting,
@@ -99,43 +112,19 @@ pub enum PairingState {
impl PairingState {
/// Stable storage spelling.
- pub const fn as_str(self) -> &'static str {
- match self {
- Self::Waiting => "waiting",
- Self::Qr => "qr",
- Self::Passkey => "passkey",
- Self::Success => "success",
- Self::Expired => "expired",
- Self::Cancelled => "cancelled",
- Self::Failed => "failed",
- }
+ pub fn as_str(self) -> &'static str {
+ self.into()
}
/// Parse the storage spelling.
pub fn parse(value: &str) -> Option<Self> {
- Some(match value {
- "waiting" => Self::Waiting,
- "qr" => Self::Qr,
- "passkey" => Self::Passkey,
- "success" => Self::Success,
- "expired" => Self::Expired,
- "cancelled" => Self::Cancelled,
- "failed" => Self::Failed,
- _ => return None,
- })
- }
-
- /// Whether the transaction has ended.
- pub const fn is_terminal(self) -> bool {
- matches!(
- self,
- Self::Success | Self::Expired | Self::Cancelled | Self::Failed
- )
+ value.parse().ok()
}
}
/// Owner-bound pairing transaction, without its QR or pairing code.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "schema", schema(as = LinkedPairing))]
pub struct Pairing {
@@ -175,6 +164,7 @@ pub struct PairState {
/// Explicit adoption request; the account is selected server-side. The
/// group's name always follows WhatsApp.
#[derive(Debug, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "schema", schema(as = LinkedAdoptGroup))]
pub struct AdoptGroup {
@@ -215,11 +205,10 @@ pub struct Binding {
pub adopted_at: DateTime<Utc>,
}
-/// Verified sender aliases, supplied only by protocol metadata.
+/// Verified sender aliases, supplied only by protocol metadata. Stored in
+/// roster metadata and retained events as camelCase JSON.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
-#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
-#[cfg_attr(feature = "schema", schema(as = LinkedIdentity))]
pub struct Identity {
/// Phone-number or LID account JID.
pub jid: String,
@@ -242,16 +231,13 @@ impl Identity {
[Some(self.jid.as_str()), self.alternate_jid.as_deref()]
.into_iter()
.flatten()
- .find_map(|jid| jid.strip_suffix("@s.whatsapp.net"))
- .map(|phone| format!("+{phone}"))
+ .find_map(super::jid::phone_number)
}
}
/// Current remote participant; Macro access is a separate grant.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
-#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
-#[cfg_attr(feature = "schema", schema(as = LinkedParticipant))]
pub struct Participant {
/// Identity evidence.
#[serde(flatten)]
@@ -261,10 +247,10 @@ pub struct Participant {
}
/// One full metadata read of a group, never an incomplete membership delta.
+/// The session service reports it and it is stored as roster metadata
+/// (camelCase JSON); the API shows it as [`crate::domain::timeline::WhatsAppRoster`].
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
-#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
-#[cfg_attr(feature = "schema", schema(as = LinkedGroupInfo))]
pub struct GroupInfo {
/// Remote group JID.
pub jid: String,
@@ -293,6 +279,7 @@ pub struct GroupInfo {
/// A group entity bound to a remote group.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "schema", schema(as = LinkedGroupReference))]
pub struct GroupReference {
@@ -319,6 +306,22 @@ pub struct CommunityReference {
/// Shown when the community itself is not in the account's group list.
const UNKNOWN_COMMUNITY_NAME: &str = "WhatsApp community";
+impl CommunityReference {
+ /// The community `id`, named after its own metadata's `name` when known.
+ pub fn named(id: String, name: Option<&str>, announcements: bool) -> Self {
+ let name = name
+ .map(str::trim)
+ .filter(|name| !name.is_empty())
+ .unwrap_or(UNKNOWN_COMMUNITY_NAME)
+ .to_owned();
+ Self {
+ id,
+ name,
+ announcements,
+ }
+ }
+}
+
/// Another person's group entity the caller can view.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
@@ -374,17 +377,11 @@ impl GroupInfo {
/// The community this group belongs to, named after `parent` (the
/// community's own metadata) when known.
pub fn community(&self, parent: Option<&GroupInfo>) -> Option<CommunityReference> {
- let id = self.community_jid.clone()?;
- let name = parent
- .map(|parent| parent.name.trim())
- .filter(|name| !name.is_empty())
- .unwrap_or(UNKNOWN_COMMUNITY_NAME)
- .to_owned();
- Some(CommunityReference {
- id,
- name,
- announcements: self.community_announcements,
- })
+ Some(CommunityReference::named(
+ self.community_jid.clone()?,
+ parent.map(|parent| parent.name.as_str()),
+ self.community_announcements,
+ ))
}
/// Whether the given identity may post under the group's current settings.
@@ -396,10 +393,22 @@ impl GroupInfo {
}
/// Whether a WhatsApp chat is a group or a one-to-one chat.
-#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
+#[derive(
+ Debug,
+ Clone,
+ Copy,
+ Serialize,
+ Deserialize,
+ PartialEq,
+ Eq,
+ Hash,
+ strum::IntoStaticStr,
+ strum::EnumString,
+)]
#[serde(rename_all = "snake_case")]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "schema", schema(as = LinkedChatKind))]
+#[strum(serialize_all = "snake_case")]
pub enum ChatKind {
/// A group chat (`…@g.us`).
Group,
@@ -409,20 +418,13 @@ pub enum ChatKind {
impl ChatKind {
/// Stable storage spelling.
- pub const fn as_str(self) -> &'static str {
- match self {
- Self::Group => "group",
- Self::Direct => "direct",
- }
+ pub fn as_str(self) -> &'static str {
+ self.into()
}
/// Parse the storage spelling.
pub fn parse(value: &str) -> Option<Self> {
- Some(match value {
- "group" => Self::Group,
- "direct" => Self::Direct,
- _ => return None,
- })
+ value.parse().ok()
}
}
@@ -492,13 +494,27 @@ pub struct ChatList {
}
/// Where importing a group's earlier messages stands.
-#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
+#[derive(
+ Debug,
+ Clone,
+ Copy,
+ Serialize,
+ Deserialize,
+ PartialEq,
+ Eq,
+ strum::IntoStaticStr,
+ strum::EnumString,
+)]
#[serde(rename_all = "snake_case")]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "schema", schema(as = LinkedBackfillState))]
+#[strum(serialize_all = "snake_case")]
pub enum BackfillState {
- /// Waiting to start: the owner's account has not seen a message in this
- /// chat yet, or has not picked it up.
+ /// Nothing to start from: the owner's account knows no message in this
+ /// chat yet (paired before WhatsApp sent its chat list, and quiet since).
+ /// Becomes `pending` with the chat's first message.
+ WaitingForMessage,
+ /// About to start: the owner's account has not picked it up yet.
Pending,
/// Asking the owner's phone for earlier messages.
Running,
@@ -513,31 +529,13 @@ pub enum BackfillState {
impl BackfillState {
/// Stable storage spelling.
- pub const fn as_str(self) -> &'static str {
- match self {
- Self::Pending => "pending",
- Self::Running => "running",
- Self::WaitingForPhone => "waiting_for_phone",
- Self::Done => "done",
- Self::Partial => "partial",
- }
+ pub fn as_str(self) -> &'static str {
+ self.into()
}
/// Parse the storage spelling.
pub fn parse(value: &str) -> Option<Self> {
- Some(match value {
- "pending" => Self::Pending,
- "running" => Self::Running,
- "waiting_for_phone" => Self::WaitingForPhone,
- "done" => Self::Done,
- "partial" => Self::Partial,
- _ => return None,
- })
- }
-
- /// Still importing (show "Importing history…").
- pub const fn is_active(self) -> bool {
- matches!(self, Self::Pending | Self::Running | Self::WaitingForPhone)
+ value.parse().ok()
}
}
@@ -591,6 +589,7 @@ pub enum ReplyContent {
/// One attachment staged through the attachments route.
Media {
/// The staged upload, which becomes the message's private document.
+ #[serde(rename = "uploadId")]
upload_id: Uuid,
/// Optional caption; audio has none.
caption: Option<String>,
@@ -598,6 +597,7 @@ pub enum ReplyContent {
/// An operation on an existing message in this group.
Mutation {
/// Existing group message, resolved to its WhatsApp source by the server.
+ #[serde(rename = "messageId")]
message_id: Uuid,
/// Explicit operation.
operation: Mutation,
@@ -608,6 +608,7 @@ pub enum ReplyContent {
/// Explicit send action from a person. Only deliberate sends reach WhatsApp.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "schema", schema(as = LinkedSendReply))]
pub struct SendReply {
@@ -622,10 +623,21 @@ pub struct SendReply {
/// Observed send state. `unknown` means the request may have reached WhatsApp;
/// it is never sent again automatically.
-#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
+#[derive(
+ Debug,
+ Clone,
+ Copy,
+ Serialize,
+ Deserialize,
+ PartialEq,
+ Eq,
+ strum::IntoStaticStr,
+ strum::EnumString,
+)]
#[serde(rename_all = "snake_case")]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "schema", schema(as = LinkedDeliveryState))]
+#[strum(serialize_all = "snake_case")]
pub enum DeliveryState {
/// Durable intent, not yet claimed.
Pending,
@@ -635,49 +647,25 @@ pub enum DeliveryState {
Unknown,
/// WhatsApp accepted the message; this does not establish delivery.
Accepted,
- /// Reported sent.
- Sent,
- /// Reported delivered.
- Delivered,
- /// Reported read.
- Read,
/// Rejected, expired or no longer authorized.
Failed,
}
impl DeliveryState {
/// Stable storage spelling.
- pub const fn as_str(self) -> &'static str {
- match self {
- Self::Pending => "pending",
- Self::Sending => "sending",
- Self::Unknown => "unknown",
- Self::Accepted => "accepted",
- Self::Sent => "sent",
- Self::Delivered => "delivered",
- Self::Read => "read",
- Self::Failed => "failed",
- }
+ pub fn as_str(self) -> &'static str {
+ self.into()
}
/// Parse the storage spelling.
pub fn parse(value: &str) -> Option<Self> {
- Some(match value {
- "pending" => Self::Pending,
- "sending" => Self::Sending,
- "unknown" => Self::Unknown,
- "accepted" => Self::Accepted,
- "sent" => Self::Sent,
- "delivered" => Self::Delivered,
- "read" => Self::Read,
- "failed" => Self::Failed,
- _ => return None,
- })
+ value.parse().ok()
}
}
/// Durable result of a deliberate send.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "schema", schema(as = LinkedSendProgress))]
pub struct SendProgress {
@@ -715,24 +703,46 @@ pub enum MediaKind {
Document,
}
+/// Every MIME type Macro sends to WhatsApp, with its category.
+pub const SENDABLE_MEDIA: [(&str, MediaKind); 10] = [
+ ("image/jpeg", MediaKind::Image),
+ ("image/png", MediaKind::Image),
+ ("image/webp", MediaKind::Image),
+ ("audio/mpeg", MediaKind::Audio),
+ ("audio/ogg", MediaKind::Audio),
+ ("audio/aac", MediaKind::Audio),
+ ("audio/mp4", MediaKind::Audio),
+ ("video/mp4", MediaKind::Video),
+ ("application/pdf", MediaKind::Document),
+ ("text/plain", MediaKind::Document),
+];
+
impl MediaKind {
/// Category of a supported MIME type; anything else is refused.
pub fn of(mime: &str) -> Option<Self> {
- Some(match mime {
- "image/jpeg" | "image/png" | "image/webp" => Self::Image,
- "audio/mpeg" | "audio/ogg" | "audio/aac" | "audio/mp4" => Self::Audio,
- "video/mp4" => Self::Video,
- "application/pdf" | "text/plain" => Self::Document,
- _ => return None,
- })
+ SENDABLE_MEDIA
+ .iter()
+ .find(|(sendable, _)| *sendable == mime)
+ .map(|(_, kind)| *kind)
}
}
/// How WhatsApp shows an attachment, when not as a plain file of its kind.
-#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
+#[derive(
+ Debug,
+ Clone,
+ Copy,
+ Serialize,
+ Deserialize,
+ PartialEq,
+ Eq,
+ strum::IntoStaticStr,
+ strum::EnumString,
+)]
#[serde(rename_all = "snake_case")]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "schema", schema(as = LinkedMediaPresentation))]
+#[strum(serialize_all = "snake_case")]
pub enum MediaPresentation {
/// A sticker: a small image (WebP, possibly animated), no caption.
Sticker,
@@ -743,23 +753,14 @@ pub enum MediaPresentation {
}
impl MediaPresentation {
- /// Stored form.
+ /// Stable storage spelling.
pub fn as_str(self) -> &'static str {
- match self {
- Self::Sticker => "sticker",
- Self::Gif => "gif",
- Self::VoiceNote => "voice_note",
- }
+ self.into()
}
- /// Parses the stored form.
+ /// Parse the storage spelling.
pub fn parse(value: &str) -> Option<Self> {
- Some(match value {
- "sticker" => Self::Sticker,
- "gif" => Self::Gif,
- "voice_note" => Self::VoiceNote,
- _ => return None,
- })
+ value.parse().ok()
}
}
@@ -768,6 +769,7 @@ pub const MEDIA_LIMIT_BYTES: usize = 32 * 1024 * 1024;
/// A staged attachment, sent only by a later deliberate send.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "schema", schema(as = LinkedUploadedAttachment))]
pub struct UploadedAttachment {
@@ -797,6 +799,7 @@ pub enum AttachmentState {
/// One attachment of a linked message.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "schema", schema(as = LinkedAttachment))]
pub struct LinkedAttachment {
@@ -824,6 +827,7 @@ pub struct LinkedAttachment {
/// The attachments of one linked group message.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "schema", schema(as = LinkedMessageAttachments))]
pub struct MessageAttachments {
@@ -836,6 +840,17 @@ pub struct MessageAttachments {
/// Most people one text send may @-mention.
pub const MENTION_LIMIT: usize = 64;
+/// Largest WebAuthn challenge or assertion passed through a pairing.
+pub const PASSKEY_LIMIT_BYTES: usize = 32 * 1024;
+
+/// Most messages or send ids one attachments or delivery request names.
+pub const BATCH_LIMIT: usize = 100;
+
+/// Most messages in one timeline page, and the page size when none is asked.
+pub const PAGE_LIMIT: i64 = 100;
+/// Timeline page size when the caller names none.
+pub const DEFAULT_PAGE: i64 = 50;
+
/// Days a participant's receipt is kept.
pub const RECEIPT_RETENTION_DAYS: i32 = 30;
/// Maximum UTF-8 bytes in one text send.
@@ -847,6 +862,7 @@ pub const SEND_EXPIRY_SECONDS: i64 = 10 * 60;
/// Operations implemented for linked groups, independent of current permission.
#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "schema", schema(as = LinkedCapabilities))]
pub struct Capabilities {
@@ -872,21 +888,10 @@ impl Default for Capabilities {
mutation_window_seconds: MUTATION_WINDOW_SECONDS as u32,
max_attachments: 1,
attachment_limit_bytes: MEDIA_LIMIT_BYTES as u32,
- attachment_types: [
- "image/jpeg",
- "image/png",
- "image/webp",
- "audio/mpeg",
- "audio/ogg",
- "audio/aac",
- "audio/mp4",
- "video/mp4",
- "application/pdf",
- "text/plain",
- ]
- .into_iter()
- .map(str::to_owned)
- .collect(),
+ attachment_types: SENDABLE_MEDIA
+ .iter()
+ .map(|(mime, _)| (*mime).to_owned())
+ .collect(),
}
}
}
@@ -907,12 +912,13 @@ pub enum ReplyBlock {
NotObserving,
/// The viewer is not in the group, or only admins may post.
NotAllowedInGroup,
- /// The group is detached, or needs a new content owner.
+ /// The group is detached.
GroupUnavailable,
}
/// Owner-scoped account state, including not connected.
#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "schema", schema(as = LinkedAccountView))]
pub struct AccountView {
@@ -922,6 +928,7 @@ pub struct AccountView {
/// Result of disconnecting an account.
#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "schema", schema(as = LinkedDisconnect))]
pub struct Disconnect {
@@ -937,7 +944,9 @@ pub enum SendAuthority {
Human,
/// The person's verified API credential; sends only from their own account.
UserApiToken,
- /// A bot, harness, or other automation principal; never sends to WhatsApp.
+ /// Acting for the person without being them: a session carrying an agent
+ /// attribution. Bots, harnesses and internal callers never reach these use
+ /// cases (`UserOnly` rejects them). Never sends to WhatsApp.
Automation,
}
@@ -965,9 +974,6 @@ pub enum LinkedError {
/// The account is not connected.
#[error("connect your WhatsApp account first")]
Disconnected,
- /// A sender identity is ambiguous; the event is quarantined.
- #[error("identity_conflict")]
- IdentityConflict,
/// The intent expired before it was attempted.
#[error("send_expired")]
SendExpired,
@@ -980,6 +986,14 @@ pub enum LinkedError {
/// Retryable infrastructure failure.
#[error("WhatsApp is temporarily unavailable; retry shortly")]
Unavailable,
+ /// The account has too many events waiting to be stored; the session
+ /// service leaves the event unacknowledged and WhatsApp redelivers it.
+ #[error("too many WhatsApp events are waiting for this account")]
+ Backlogged,
+ /// Stored data broke an invariant; retrying does not help. The report
+ /// carries the cause.
+ #[error("something went wrong with this WhatsApp chat")]
+ Internal,
}
impl LinkedError {
@@ -996,11 +1010,12 @@ impl LinkedError {
Self::Forbidden => "forbidden",
Self::Conflict => "conflict",
Self::Disconnected => "disconnected",
- Self::IdentityConflict => "identity_conflict",
Self::SendExpired => "send_expired",
Self::Fenced => "lease_fenced",
Self::RateLimited => "rate_limited",
Self::Unavailable => "temporarily_unavailable",
+ Self::Backlogged => "backlogged",
+ Self::Internal => "internal_error",
}
}
}
diff --git a/crates/whatsapp_linked/src/domain/ports.rs b/crates/whatsapp_linked/src/domain/ports.rs
index deaabda4b1..632b682c2c 100644
--- a/crates/whatsapp_linked/src/domain/ports.rs
+++ b/crates/whatsapp_linked/src/domain/ports.rs
@@ -1,5 +1,5 @@
//! Capabilities the linked-device use cases need. Postgres adapters implement
-//! the repositories; DSS supplies the authorizer and group notification publisher.
+//! the repositories; DSS supplies the group notification publisher.
//!
//! Repository methods that change state are atomic and re-check, under lock, the
//! facts their contract names. Methods that signal another process do it with
@@ -9,6 +9,7 @@
use super::{events::*, models::*};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
use uuid::Uuid;
/// Result of every port and service call.
@@ -19,41 +20,46 @@ pub type LinkedResult<T> = Result<T, rootcause::Report<LinkedError>>;
pub trait SendRateLimiter: Send + Sync {
/// Consume one request across all groups and service replicas. Requests
/// rejected later still count; infrastructure failure must fail closed.
- async fn check(&self, user: &str) -> LinkedResult<()>;
+ async fn check(&self, user: &MacroUserIdStr<'_>) -> LinkedResult<()>;
}
/// Owner-scoped account and pairing transitions.
#[async_trait]
pub trait AccountRepository: Send + Sync {
/// The person's account, if they ever started pairing.
- async fn owned_account(&self, user: &str) -> LinkedResult<Option<Account>>;
+ async fn owned_account(&self, user: &MacroUserIdStr<'_>) -> LinkedResult<Option<Account>>;
/// Return the live transaction, or start one: create the account if absent,
/// otherwise move it to `pairing` and bump its generation. Fails with
/// `Conflict` when the account is connected and `replace` is false. With
/// `replace`, first ends the old consent exactly like
/// [`AccountRepository::disconnect`] and drops the expected identity.
/// Signals `whatsapp_pairing_requested`.
- async fn begin_pairing(&self, user: &str, replace: bool) -> LinkedResult<Pairing>;
+ async fn begin_pairing(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ replace: bool,
+ ) -> LinkedResult<Pairing>;
/// The owner's transaction with its current codes; an unconsumed transaction
/// past its deadline is expired first (and its pairing account disconnected).
/// `NotFound` for another user's transaction.
- async fn pair_state(&self, user: &str, pairing: Uuid) -> LinkedResult<PairState>;
+ async fn pair_state(&self, user: &MacroUserIdStr<'_>, pairing: Uuid)
+ -> LinkedResult<PairState>;
/// Store the owner's WebAuthn assertion for a live transaction waiting on a
/// passkey; `NotFound` otherwise. Signals `whatsapp_pairing_requested`.
async fn submit_passkey(
&self,
- user: &str,
+ user: &MacroUserIdStr<'_>,
pairing: Uuid,
response: &serde_json::Value,
) -> LinkedResult<()>;
/// Cancel the owner's live transaction and end the pairing consent.
/// Signals `whatsapp_pairing_requested`. Idempotent.
- async fn cancel_pairing(&self, user: &str, pairing: Uuid) -> LinkedResult<()>;
+ async fn cancel_pairing(&self, user: &MacroUserIdStr<'_>, pairing: Uuid) -> LinkedResult<()>;
/// End consent at exactly this generation: state `disconnected`, generation
/// + 1, memberships end, live pairings cancel, undispatched sends fail.
/// Returns false when that generation was already disconnected.
/// Signals `whatsapp_account_changed`.
- async fn disconnect(&self, user: &str, generation: i64) -> LinkedResult<bool>;
+ async fn disconnect(&self, user: &MacroUserIdStr<'_>, generation: i64) -> LinkedResult<bool>;
}
/// A group entity bound to a remote group, as one viewer can see it.
@@ -80,24 +86,17 @@ pub trait GroupRepository: Send + Sync {
/// (`whatsapp_groups_requested`); the replica rate limits refreshes.
async fn request_groups_refresh(&self, accounts: &[Uuid]) -> LinkedResult<()>;
/// Accounts whose rosters describe a group entity: its observers, and the
- /// viewer's own connected account.
- async fn group_accounts(&self, group_id: Uuid, user: &str) -> LinkedResult<Vec<Uuid>>;
+ /// viewer's own connected account (a bot viewer has none).
+ async fn group_accounts(&self, group_id: Uuid, viewer: &str) -> LinkedResult<Vec<Uuid>>;
/// Group entities bound to these remote groups that the person can see,
/// newest first.
async fn visible_adoptions(
&self,
- user: &str,
+ user: &MacroUserIdStr<'_>,
groups: &[String],
) -> LinkedResult<Vec<VisibleAdoption>>;
/// Latest metadata for a binding's group from any account consenting to it.
async fn binding_roster(&self, binding: &Binding) -> LinkedResult<Option<GroupInfo>>;
- /// Latest metadata for the binding's community (`community_jid`) from any
- /// account consenting to the binding.
- async fn binding_community(
- &self,
- binding: &Binding,
- community_jid: &str,
- ) -> LinkedResult<Option<GroupInfo>>;
/// The account's stored chat list (without the roster), newest first.
async fn account_chats(&self, account: Uuid) -> LinkedResult<Vec<StoredChat>>;
@@ -138,7 +137,7 @@ pub struct Adoption {
/// A new binding, authorized by the domain.
pub struct AdoptionRecord<'a> {
/// Adopting person.
- pub user: &'a str,
+ pub user: &'a MacroUserIdStr<'a>,
/// Their account at the generation that authorized adoption.
pub account: &'a Account,
/// What to add.
@@ -184,38 +183,6 @@ pub struct SendingFacts {
pub can_post: bool,
}
-/// A direct chat has two people: only its owner's own account is in it.
-pub(crate) fn direct_sending_facts(account: &Account, binding: &Binding) -> SendingFacts {
- let owner = account.user_id == binding.user_id;
- SendingFacts {
- observing: owner,
- remote_member: owner,
- can_post: owner,
- }
-}
-
-/// Membership eligibility derived only from the caller's own protocol metadata.
-pub(crate) fn sending_facts_from_roster(
- account: &Account,
- group: Option<GroupInfo>,
-) -> SendingFacts {
- SendingFacts {
- observing: group.is_some(),
- remote_member: group.as_ref().is_some_and(|g| {
- account
- .identity_jid
- .as_deref()
- .is_some_and(|i| g.participant(i).is_some())
- }),
- can_post: group.as_ref().is_some_and(|g| {
- account
- .identity_jid
- .as_deref()
- .is_some_and(|i| g.can_post(i))
- }),
- }
-}
-
/// What a mutation request points at.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MutationTarget {
@@ -227,10 +194,19 @@ pub struct MutationTarget {
pub deleted: bool,
}
+/// An earlier send found by its intent key.
+#[derive(Debug, Clone)]
+pub struct StoredSend {
+ /// SHA-256 of its canonical request; a retry must match it.
+ pub request_sha256: [u8; 32],
+ /// Where it got to.
+ pub progress: SendProgress,
+}
+
/// A validated intent, authorized by the domain.
pub struct SendIntent<'a> {
/// Sending person.
- pub user: &'a str,
+ pub user: &'a MacroUserIdStr<'a>,
/// Their account at its current generation.
pub account: &'a Account,
/// Binding.
@@ -244,7 +220,7 @@ pub struct SendIntent<'a> {
/// A validated attachment upload.
pub struct StagedUpload<'a> {
/// Uploader, who will own the document.
- pub user: &'a str,
+ pub user: &'a MacroUserIdStr<'a>,
/// Group it may be sent to.
pub group_id: Uuid,
/// Display filename.
@@ -264,45 +240,48 @@ pub struct StagedUpload<'a> {
pub trait SendRepository: Send + Sync {
/// Stage an attachment for a later send by the same person in the same group.
async fn stage_upload(&self, upload: StagedUpload<'_>) -> LinkedResult<Uuid>;
- /// MIME type and filename of the person's staged upload in this group.
- async fn staged_upload(
+ /// MIME type of the person's unsent staged upload in this group.
+ async fn staged_upload_mime(
&self,
- user: &str,
+ user: &MacroUserIdStr<'_>,
group_id: Uuid,
upload: Uuid,
- ) -> LinkedResult<Option<(String, String)>>;
- /// Own-account membership facts for the person's account in the binding.
- async fn sending_facts(
+ ) -> LinkedResult<Option<String>>;
+ /// The person's own account's roster of the binding's group, if any.
+ async fn account_roster(
&self,
account: &Account,
binding: &Binding,
- ) -> LinkedResult<SendingFacts>;
+ ) -> LinkedResult<Option<GroupInfo>>;
/// The source of a group message in this binding, for quotes and mutations.
async fn mutation_target(
&self,
binding: &Binding,
message: Uuid,
) -> LinkedResult<Option<MutationTarget>>;
- /// The person's earlier send with this intent key in the group, with the
- /// SHA-256 of its canonical request.
+ /// The person's earlier send with this intent key in the group.
async fn stored_send(
&self,
group_id: Uuid,
- user: &str,
+ user: &MacroUserIdStr<'_>,
idempotency_key: Uuid,
- ) -> LinkedResult<Option<([u8; 32], SendProgress)>>;
+ ) -> LinkedResult<Option<StoredSend>>;
/// Record the intent and assign the group sequence. Replays with the same key
/// return the stored progress; a different payload is a `Conflict`. Inserts
/// only while the account is connected at its generation, the binding is
/// active and the membership still observes. Signals `whatsapp_send_requested`.
async fn enqueue(&self, intent: SendIntent<'_>) -> LinkedResult<SendProgress>;
/// The person's sends in a group that are not yet accepted, newest first.
- async fn open_sends(&self, group_id: Uuid, user: &str) -> LinkedResult<Vec<SendProgress>>;
+ async fn open_sends(
+ &self,
+ group_id: Uuid,
+ user: &MacroUserIdStr<'_>,
+ ) -> LinkedResult<Vec<SendProgress>>;
/// The person's sends for these group messages or intent ids.
async fn sends_for(
&self,
group_id: Uuid,
- user: &str,
+ user: &MacroUserIdStr<'_>,
ids: &[Uuid],
) -> LinkedResult<Vec<SendProgress>>;
}
@@ -324,6 +303,9 @@ pub trait SessionRepository: Send + Sync {
async fn begin_lease(&self, account: Uuid) -> LinkedResult<Lease>;
/// Return claimed but undispatched sends to `pending` before handing over.
async fn release_lease(&self, scope: SessionScope) -> LinkedResult<()>;
+ /// Tell other replicas the account is free to take while it still needs
+ /// a session (`whatsapp_account_released`).
+ async fn announce_released(&self, account: Uuid) -> LinkedResult<()>;
/// Remove and return the owner's WebAuthn assertion, so it is forwarded once.
async fn take_passkey_response(
&self,
@@ -390,11 +372,20 @@ pub trait SessionRepository: Send + Sync {
async fn observed_groups(&self, scope: SessionScope) -> LinkedResult<Vec<String>>;
/// Upsert chat-list rows. Signals the owner's list when something changed.
- async fn update_chats(&self, scope: SessionScope, chats: &[ChatUpdate]) -> LinkedResult<()>;
+ /// Returns whether an added chat waiting for its first message got one
+ /// (it is `pending` now).
+ async fn update_chats(&self, scope: SessionScope, chats: &[ChatUpdate]) -> LinkedResult<bool>;
/// The account owner's groups still importing earlier messages.
async fn backfill_work(&self, scope: SessionScope) -> LinkedResult<Vec<BackfillWork>>;
+ /// No message of the chat is known to start from (`waiting_for_message`).
+ async fn backfill_waiting_for_message(
+ &self,
+ scope: SessionScope,
+ group: Uuid,
+ ) -> LinkedResult<()>;
+
/// A page was requested from the phone just now (`running`).
async fn backfill_requested(&self, scope: SessionScope, group: Uuid) -> LinkedResult<()>;
@@ -523,7 +514,7 @@ pub struct DocumentImport {
pub attachment: AttachmentRef,
/// Reserved document id.
pub document_id: Uuid,
- /// Channel the document is shared with.
+ /// The chat whose viewers inherit access to the document.
pub group_id: Uuid,
/// Owner of the document.
pub owner: String,
@@ -531,10 +522,8 @@ pub struct DocumentImport {
pub filename: String,
/// MIME type.
pub mime: String,
- /// SHA-256 of `bytes`.
+ /// SHA-256 of the bytes.
pub sha256: [u8; 32],
- /// Plaintext bytes.
- pub bytes: Vec<u8>,
/// Earlier failed imports.
pub attempts: i32,
}
@@ -542,15 +531,18 @@ pub struct DocumentImport {
/// The import queue between blobs and documents.
#[async_trait]
pub trait MediaRepository: Send + Sync {
- /// Imports whose retry time has come.
+ /// Imports whose retry time has come, claimed, without their bytes.
async fn due_imports(&self, limit: i64) -> LinkedResult<Vec<DocumentImport>>;
+ /// One claimed import's plaintext bytes; `None` once the blob is gone.
+ async fn import_bytes(&self, import: &DocumentImport) -> LinkedResult<Option<Vec<u8>>>;
/// The document holds the bytes: attach it to the message, drop the blob and
/// queue publication.
async fn import_stored(&self, import: &DocumentImport) -> LinkedResult<()>;
/// Retry later, or give up and show a notice on the message.
async fn import_failed(&self, import: &DocumentImport, permanent: bool) -> LinkedResult<()>;
- /// Delete staged uploads nobody sent and participant receipts older than
- /// [`RECEIPT_RETENTION_DAYS`](crate::domain::models::RECEIPT_RETENTION_DAYS).
+ /// Delete staged uploads nobody sent, participant receipts older than
+ /// [`RECEIPT_RETENTION_DAYS`](crate::domain::models::RECEIPT_RETENTION_DAYS)
+ /// and pairings consumed over a day ago (they keep the expected identity).
async fn expire_retained(&self) -> LinkedResult<u64>;
}
@@ -559,12 +551,5 @@ pub trait MediaRepository: Send + Sync {
pub trait DocumentStore: Send + Sync {
/// Create the document with the reserved id, owned by `owner`, holding the
/// bytes; group viewers inherit attachment access. Never rewrites uploaded bytes.
- async fn store(&self, import: &DocumentImport) -> LinkedResult<()>;
-}
-
-/// Native authorization owned by entity access.
-#[async_trait]
-pub trait Authorizer: Send + Sync {
- /// The person owns the group entity.
- async fn require_group_owner(&self, group_id: Uuid, user: &str) -> LinkedResult<()>;
+ async fn store(&self, import: &DocumentImport, bytes: Vec<u8>) -> LinkedResult<()>;
}
diff --git a/crates/whatsapp_linked/src/domain/service.rs b/crates/whatsapp_linked/src/domain/service.rs
index 235bf17300..9b6dcf9d91 100644
--- a/crates/whatsapp_linked/src/domain/service.rs
+++ b/crates/whatsapp_linked/src/domain/service.rs
@@ -1,8 +1,14 @@
//! Owner-bound account lifecycle, adoption and deliberate sends, as served by DSS.
-use super::{models::*, ports::*, timeline::*};
+use super::{
+ jid::{Jid, is_group_jid},
+ models::*,
+ ports::*,
+ timeline::*,
+};
use chrono::{DateTime, Utc};
use entity_access::domain::models::{EntityAccessReceipt, EntityType, RequiredPermission};
+use macro_user_id::user_id::MacroUserIdStr;
use sha2::{Digest, Sha256};
use std::sync::Arc;
use uuid::Uuid;
@@ -19,7 +25,6 @@ pub struct LinkedService {
groups: Arc<dyn GroupRepository>,
bindings: Arc<dyn BindingRepository>,
sends: Arc<dyn SendRepository>,
- authorizer: Arc<dyn Authorizer>,
timeline: Arc<dyn TimelineRepository>,
send_rate_limiter: Arc<dyn SendRateLimiter>,
}
@@ -29,7 +34,6 @@ impl LinkedService {
pub fn new<R>(
features: Features,
repository: Arc<R>,
- authorizer: Arc<dyn Authorizer>,
send_rate_limiter: Arc<dyn SendRateLimiter>,
) -> Self
where
@@ -47,8 +51,6 @@ impl LinkedService {
bindings: repository.clone(),
sends: repository.clone(),
timeline: repository,
- authorizer,
-
send_rate_limiter,
}
}
@@ -59,15 +61,15 @@ impl LinkedService {
}
/// Personal settings never depend on workspace administration.
- pub async fn account(&self, user: &str) -> LinkedResult<Option<Account>> {
+ pub async fn account(&self, user: &MacroUserIdStr<'_>) -> LinkedResult<Option<Account>> {
self.accounts.owned_account(user).await
}
/// Start explicit owner consent. Replacement never inherits the old identity.
- #[tracing::instrument(name = "whatsapp.linked.connect", skip_all, err, fields(replace = replace, pairing_id))]
+ #[tracing::instrument(name = "whatsapp.linked.connect", skip_all, err, fields(replace = replace, pairing_id, account_id))]
pub async fn connect(
&self,
- user: &str,
+ user: &MacroUserIdStr<'_>,
replace: bool,
authority: SendAuthority,
) -> LinkedResult<Pairing> {
@@ -76,14 +78,16 @@ impl LinkedService {
return Err(LinkedError::ConfigurationRequired.into());
}
let pairing = self.accounts.begin_pairing(user, replace).await?;
- tracing::Span::current().record("pairing_id", tracing::field::display(pairing.id));
+ let span = tracing::Span::current();
+ span.record("pairing_id", tracing::field::display(pairing.id));
+ span.record("account_id", tracing::field::display(pairing.account_id));
Ok(pairing)
}
/// Poll the initiating person's transaction, including secret enrollment material.
pub async fn pair_state(
&self,
- user: &str,
+ user: &MacroUserIdStr<'_>,
pairing: Uuid,
authority: SendAuthority,
) -> LinkedResult<PairState> {
@@ -96,7 +100,7 @@ impl LinkedService {
#[tracing::instrument(name = "whatsapp.linked.passkey", skip_all, err, fields(pairing_id = %pairing))]
pub async fn passkey(
&self,
- user: &str,
+ user: &MacroUserIdStr<'_>,
pairing: Uuid,
response: &serde_json::Value,
authority: SendAuthority,
@@ -115,7 +119,7 @@ impl LinkedService {
#[tracing::instrument(name = "whatsapp.linked.cancel_pairing", skip_all, err, fields(pairing_id = %pairing))]
pub async fn cancel(
&self,
- user: &str,
+ user: &MacroUserIdStr<'_>,
pairing: Uuid,
authority: SendAuthority,
) -> LinkedResult<()> {
@@ -127,7 +131,7 @@ impl LinkedService {
#[tracing::instrument(name = "whatsapp.linked.disconnect", skip_all, err, fields(generation = generation))]
pub async fn disconnect(
&self,
- user: &str,
+ user: &MacroUserIdStr<'_>,
generation: i64,
authority: SendAuthority,
) -> LinkedResult<Disconnect> {
@@ -138,7 +142,7 @@ impl LinkedService {
})
}
- async fn connected(&self, user: &str) -> LinkedResult<(Account, String)> {
+ async fn connected(&self, user: &MacroUserIdStr<'_>) -> LinkedResult<(Account, String)> {
let account = self
.accounts
.owned_account(user)
@@ -157,12 +161,18 @@ impl LinkedService {
/// added, shared with the caller or addable; direct chats are addable (not
/// your own chat) and never shown as shared. Returns stored data
/// and requests a group refresh.
- #[tracing::instrument(name = "whatsapp.linked.chats", skip_all, err, fields(count))]
- pub async fn chats(&self, user: &str) -> LinkedResult<ChatList> {
+ #[tracing::instrument(
+ name = "whatsapp.linked.chats",
+ skip_all,
+ err,
+ fields(count, account_id)
+ )]
+ pub async fn chats(&self, user: &MacroUserIdStr<'_>) -> LinkedResult<ChatList> {
if !self.features.adoption {
return Err(LinkedError::ConfigurationRequired.into());
}
let (account, identity) = self.connected(user).await?;
+ tracing::Span::current().record("account_id", tracing::field::display(account.id));
self.groups.request_groups_refresh(&[account.id]).await?;
let roster = self.groups.account_groups(account.id).await?;
let stored = self.groups.account_chats(account.id).await?;
@@ -270,7 +280,7 @@ impl LinkedService {
)]
pub async fn adopt(
&self,
- user: &str,
+ user: &MacroUserIdStr<'_>,
request: &AdoptGroup,
authority: SendAuthority,
) -> LinkedResult<Binding> {
@@ -335,29 +345,25 @@ impl LinkedService {
Ok(adopted.binding)
}
- async fn managed_binding(&self, user: &str, group_id: Uuid) -> LinkedResult<Binding> {
+ /// Detach locally; nothing changes in WhatsApp. Only the person who
+ /// added the chat, in their own session, stops syncing it.
+ #[tracing::instrument(name = "whatsapp.linked.detach", skip_all, err, fields(group_id))]
+ pub async fn detach<T: RequiredPermission>(
+ &self,
+ access: &EntityAccessReceipt<T>,
+ authority: SendAuthority,
+ ) -> LinkedResult<()> {
+ human(authority)?;
+ let (user, group_id) = receipt_scope(access)?;
+ tracing::Span::current().record("group_id", tracing::field::display(group_id));
let binding = self
.bindings
.binding(group_id)
.await?
.ok_or(LinkedError::NotFound)?;
- self.authorizer.require_group_owner(group_id, user).await?;
- if binding.user_id != user {
+ if binding.user_id != user.as_ref() {
return Err(LinkedError::Forbidden.into());
}
- Ok(binding)
- }
-
- /// Detach locally; nothing changes in WhatsApp.
- #[tracing::instrument(name = "whatsapp.linked.detach", skip_all, err, fields(group_id = %group_id))]
- pub async fn detach(
- &self,
- user: &str,
- group_id: Uuid,
- authority: SendAuthority,
- ) -> LinkedResult<()> {
- human(authority)?;
- let binding = self.managed_binding(user, group_id).await?;
self.bindings.detach(&binding).await
}
@@ -368,7 +374,11 @@ impl LinkedService {
) -> LinkedResult<Option<ReplyBlock>> {
let facts = match account {
Some(account) if account.state == AccountState::Connected => {
- Some(self.sends.sending_facts(account, binding).await?)
+ let roster = match binding.kind {
+ ChatKind::Group => self.sends.account_roster(account, binding).await?,
+ ChatKind::Direct => None,
+ };
+ Some(sending_facts(account, binding, roster))
}
_ => None,
};
@@ -402,12 +412,15 @@ impl LinkedService {
.into();
// A retry with the same intent key returns the original send, whatever
// happened since; it never sends twice.
- if let Some((stored, progress)) = self
+ if let Some(StoredSend {
+ request_sha256,
+ progress,
+ }) = self
.sends
.stored_send(group_id, user, request.idempotency_key)
.await?
{
- if stored != digest {
+ if request_sha256 != digest {
return Err(LinkedError::Conflict.into());
}
tracing::Span::current().record("send_id", tracing::field::display(progress.id));
@@ -420,12 +433,8 @@ impl LinkedService {
.await?
.ok_or(LinkedError::NotFound)?;
let account = self.accounts.owned_account(user).await?;
- match self.reply_block(account.as_ref(), &binding).await? {
- None => {}
- Some(ReplyBlock::NoAccount | ReplyBlock::Disconnected) => {
- return Err(LinkedError::Disconnected.into());
- }
- Some(_) => return Err(LinkedError::Forbidden.into()),
+ if let Some(block) = self.reply_block(account.as_ref(), &binding).await? {
+ return Err(refusal(block).into());
}
let account = account.ok_or(LinkedError::Disconnected)?;
let identity = account
@@ -440,9 +449,9 @@ impl LinkedService {
.ok_or(LinkedError::NotFound)?;
}
if let ReplyContent::Media { upload_id, caption } = &request.message {
- let (mime, _) = self
+ let mime = self
.sends
- .staged_upload(user, group_id, *upload_id)
+ .staged_upload_mime(user, group_id, *upload_id)
.await?
.ok_or(LinkedError::NotFound)?;
if MediaKind::of(&mime) == Some(MediaKind::Audio) && caption.is_some() {
@@ -510,7 +519,7 @@ impl LinkedService {
.any(|c| c.is_control() || c == '/' || c == '\\')
{
return Err(LinkedError::Invalid(
- "attachments must be 1 byte to 32 MiB with a filename",
+ "an attachment needs a filename and must be non-empty and within the size limit",
)
.into());
}
@@ -520,12 +529,8 @@ impl LinkedService {
.await?
.ok_or(LinkedError::NotFound)?;
let account = self.accounts.owned_account(user).await?;
- if self
- .reply_block(account.as_ref(), &binding)
- .await?
- .is_some()
- {
- return Err(LinkedError::Forbidden.into());
+ if let Some(block) = self.reply_block(account.as_ref(), &binding).await? {
+ return Err(refusal(block).into());
}
let upload_id = self
.sends
@@ -554,8 +559,8 @@ impl LinkedService {
messages: &[Uuid],
) -> LinkedResult<Vec<MessageAttachments>> {
let (_, group_id) = view_scope(access)?;
- if messages.len() > 100 {
- return Err(LinkedError::Invalid("at most 100 messages").into());
+ if messages.len() > BATCH_LIMIT {
+ return Err(LinkedError::Invalid("too many messages in one request").into());
}
let binding = self
.bindings
@@ -572,16 +577,13 @@ impl LinkedService {
ids: &[Uuid],
) -> LinkedResult<Vec<SendProgress>> {
let (user, group_id) = receipt_scope(access)?;
- if ids.len() > 100 {
- return Err(LinkedError::Invalid("at most 100 messages").into());
+ if ids.len() > BATCH_LIMIT {
+ return Err(LinkedError::Invalid("too many messages in one request").into());
}
self.sends.sends_for(group_id, user, ids).await
}
}
-/// Largest WebAuthn assertion accepted from the browser.
-const PASSKEY_LIMIT_BYTES: usize = 32 * 1024;
-
fn human(authority: SendAuthority) -> LinkedResult<()> {
match authority {
SendAuthority::Human => Ok(()),
@@ -598,18 +600,23 @@ fn sender(authority: SendAuthority) -> LinkedResult<()> {
}
}
+/// The WhatsApp chat a receipt names.
+fn receipt_group<T: RequiredPermission>(access: &EntityAccessReceipt<T>) -> LinkedResult<Uuid> {
+ let entity = access.entity();
+ if entity.entity_type != EntityType::WhatsAppGroup {
+ return Err(LinkedError::Forbidden.into());
+ }
+ Ok(Uuid::parse_str(&entity.entity_id).map_err(|_| LinkedError::NotFound)?)
+}
+
+/// The person and chat of a receipt held by a person.
fn receipt_scope<T: RequiredPermission>(
access: &EntityAccessReceipt<T>,
-) -> LinkedResult<(&str, Uuid)> {
+) -> LinkedResult<(&MacroUserIdStr<'static>, Uuid)> {
let user = access
.get_authenticated_user()
.map_err(|_| LinkedError::Forbidden)?;
- let entity = access.entity();
- if entity.entity_type != EntityType::WhatsAppGroup {
- return Err(LinkedError::Forbidden.into());
- }
- let group_id = Uuid::parse_str(&entity.entity_id).map_err(|_| LinkedError::NotFound)?;
- Ok((user.as_ref(), group_id))
+ Ok((user, receipt_group(access)?))
}
/// Read receipts may represent a bot, but never borrow its acting user's phone
@@ -622,27 +629,19 @@ fn view_scope<T: RequiredPermission>(
entity_access::domain::models::EntityAccessAuth::Bot(bot) => bot.bot_id_str().as_ref(),
_ => return Err(LinkedError::Forbidden.into()),
};
- let entity = access.entity();
- if entity.entity_type != EntityType::WhatsAppGroup {
- return Err(LinkedError::Forbidden.into());
- }
- Ok((
- principal,
- Uuid::parse_str(&entity.entity_id).map_err(|_| LinkedError::NotFound)?,
- ))
+ Ok((principal, receipt_group(access)?))
}
-/// WhatsApp group JIDs: digits, optionally `creator-timestamp`, at `g.us`.
/// The caller's own Macro group for a WhatsApp group, else someone else's
/// group for it that was shared with them.
fn adoption_of(
- user: &str,
+ user: &MacroUserIdStr<'_>,
adoptions: &[VisibleAdoption],
jid: &str,
) -> (Option<GroupReference>, Option<SharedGroupReference>) {
let mine = adoptions
.iter()
- .find(|adoption| adoption.group_jid == jid && adoption.owner_id == user)
+ .find(|adoption| adoption.group_jid == jid && adoption.owner_id == user.as_ref())
.map(|adoption| GroupReference {
id: adoption.id,
name: adoption.name.clone(),
@@ -650,7 +649,7 @@ fn adoption_of(
let shared = mine.is_none().then(|| {
adoptions
.iter()
- .find(|adoption| adoption.group_jid == jid && adoption.owner_id != user)
+ .find(|adoption| adoption.group_jid == jid && adoption.owner_id != user.as_ref())
.map(|adoption| SharedGroupReference {
id: adoption.id,
name: adoption.name.clone(),
@@ -665,18 +664,51 @@ fn chat_fallback_name(jid: &str, kind: ChatKind, identity: &str) -> String {
match kind {
ChatKind::Group => "WhatsApp group".to_owned(),
ChatKind::Direct if jid == identity => "You".to_owned(),
- ChatKind::Direct => jid
- .strip_suffix("@s.whatsapp.net")
- .map(|phone| format!("+{phone}"))
- .unwrap_or_else(|| "WhatsApp contact".to_owned()),
+ ChatKind::Direct => {
+ super::jid::phone_number(jid).unwrap_or_else(|| "WhatsApp contact".to_owned())
+ }
}
}
-pub(crate) fn is_group_jid(jid: &str) -> bool {
- jid.len() <= 256
- && jid.strip_suffix("@g.us").is_some_and(|user| {
- !user.is_empty() && user.bytes().all(|b| b.is_ascii_digit() || b == b'-')
- })
+/// Whether the person's own account can send in the chat, from its own
+/// roster of the group. A direct chat has two people: only its owner's own
+/// account is in it.
+pub(crate) fn sending_facts(
+ account: &Account,
+ binding: &Binding,
+ roster: Option<GroupInfo>,
+) -> SendingFacts {
+ if binding.kind == ChatKind::Direct {
+ let owner = account.user_id == binding.user_id;
+ return SendingFacts {
+ observing: owner,
+ remote_member: owner,
+ can_post: owner,
+ };
+ }
+ let identity = account.identity_jid.as_deref();
+ SendingFacts {
+ observing: roster.is_some(),
+ remote_member: roster
+ .as_ref()
+ .zip(identity)
+ .is_some_and(|(group, identity)| group.participant(identity).is_some()),
+ can_post: roster
+ .as_ref()
+ .zip(identity)
+ .is_some_and(|(group, identity)| group.can_post(identity)),
+ }
+}
+
+/// The error a send or upload refused for `block` returns.
+fn refusal(block: ReplyBlock) -> LinkedError {
+ match block {
+ ReplyBlock::NoAccount | ReplyBlock::Disconnected => LinkedError::Disconnected,
+ ReplyBlock::SendingDisabled
+ | ReplyBlock::NotObserving
+ | ReplyBlock::NotAllowedInGroup
+ | ReplyBlock::GroupUnavailable => LinkedError::Forbidden,
+ }
}
/// Why the person cannot send now, from the current facts.
@@ -709,7 +741,9 @@ pub(crate) fn reply_block(
fn validate_text(text: &str) -> LinkedResult<()> {
if text.trim().is_empty() || text.len() > TEXT_LIMIT_BYTES {
- return Err(LinkedError::Invalid("message is empty or longer than 16 KiB").into());
+ return Err(
+ LinkedError::Invalid("the message is empty or longer than the text limit").into(),
+ );
}
Ok(())
}
@@ -721,13 +755,12 @@ fn validate_mentions(text: &str, mentions: &[String]) -> LinkedResult<()> {
return Err(LinkedError::Invalid("too many mentions in one message").into());
}
for mention in mentions {
- let user = mention
- .strip_suffix("@s.whatsapp.net")
- .or_else(|| mention.strip_suffix("@lid"))
- .filter(|user| !user.is_empty() && user.bytes().all(|byte| byte.is_ascii_digit()))
+ let user = Jid::parse(mention)
+ .filter(|jid| jid.is_person())
.ok_or(LinkedError::Invalid(
"a mention is not a WhatsApp participant",
- ))?;
+ ))?
+ .user;
if !text.contains(&format!("@{user}")) {
return Err(LinkedError::Invalid("a mentioned person is not named in the text").into());
}
@@ -784,7 +817,7 @@ pub(crate) fn authorize_mutation(
return Err(LinkedError::Forbidden.into());
}
if now - target.source_at > chrono::Duration::seconds(MUTATION_WINDOW_SECONDS) {
- return Err(LinkedError::Invalid("messages can only be changed for ten minutes").into());
+ return Err(LinkedError::Invalid("the time to change this message has passed").into());
}
Ok(())
}
diff --git a/crates/whatsapp_linked/src/domain/service/timeline.rs b/crates/whatsapp_linked/src/domain/service/timeline.rs
index 3ae1d51fe2..f7efef82c5 100644
--- a/crates/whatsapp_linked/src/domain/service/timeline.rs
+++ b/crates/whatsapp_linked/src/domain/service/timeline.rs
@@ -9,94 +9,103 @@ use models_permissions::share_permission::{
};
impl LinkedService {
/// List all shared groups, including for viewers with no WhatsApp account.
- #[tracing::instrument(name = "whatsapp.groups.list", skip_all, err)]
- pub async fn adopted_groups(&self, user: &str) -> LinkedResult<Vec<WhatsAppGroupSummary>> {
+ #[tracing::instrument(name = "whatsapp.linked.list", skip_all, err, fields(count))]
+ pub async fn adopted_groups(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ ) -> LinkedResult<Vec<WhatsAppGroupSummary>> {
let records = self.timeline.visible_groups(user).await?;
let account = self.accounts.owned_account(user).await?;
- let groups = records
+ tracing::Span::current().record("count", records.len());
+ Ok(records
.into_iter()
.map(|record| {
- let facts = account.as_ref().map(|a| match record.binding.kind {
- ChatKind::Group => sending_facts_from_roster(a, record.roster),
- ChatKind::Direct => direct_sending_facts(a, &record.binding),
- });
- let mut group = record.summary;
- group.send_reason = reply_block(
+ let facts = account
+ .as_ref()
+ .map(|account| sending_facts(account, &record.binding, record.roster));
+ let reason = reply_block(
self.features,
account.as_ref(),
&record.binding,
facts.as_ref(),
);
- group.can_send = group.send_reason.is_none();
- group
+ record.facts.summary(reason)
})
- .collect();
- Ok(groups)
+ .collect())
}
/// Authorized group detail, standard sharing and own sending identity.
+ #[tracing::instrument(name = "whatsapp.linked.detail", skip_all, err, fields(group_id))]
pub async fn group_detail<T: RequiredPermission>(
&self,
access: &EntityAccessReceipt<T>,
) -> LinkedResult<WhatsAppGroupDetail> {
let (user, id) = view_scope(access)?;
+ tracing::Span::current().record("group_id", tracing::field::display(id));
let binding = self
.bindings
.binding(id)
.await?
.ok_or(LinkedError::NotFound)?;
- let account = self.accounts.owned_account(user).await?;
- let mut group = self.timeline.summary(id, user).await?;
+ // A bot viewer reads, but has no WhatsApp account of its own.
+ let account = match access.get_authenticated_user() {
+ Ok(person) => self.accounts.owned_account(person).await?,
+ Err(_) => None,
+ };
+ let facts = self.timeline.group_facts(id, user).await?;
let observers = self.groups.group_accounts(id, user).await?;
self.groups.request_groups_refresh(&observers).await?;
- group.send_reason = self.reply_block(account.as_ref(), &binding).await?;
- group.can_send = group.send_reason.is_none();
+ let reason = self.reply_block(account.as_ref(), &binding).await?;
let access_level = match access.entity_permission() {
EntityPermission::AccessLevel { access_level } => *access_level,
_ => return Err(LinkedError::Forbidden.into()),
};
let roster = self.groups.binding_roster(&binding).await?;
- let community = match roster.as_ref().and_then(|r| r.community_jid.as_deref()) {
- Some(community_jid) => {
- let parent = self
- .groups
- .binding_community(&binding, community_jid)
- .await?;
- roster.as_ref().and_then(|r| r.community(parent.as_ref()))
- }
- None => None,
- };
Ok(WhatsAppGroupDetail {
- group,
+ group: facts.summary(reason),
share_permission: self.timeline.permissions(id).await?,
access_level,
disappearing_seconds: roster.as_ref().and_then(|r| r.disappearing_seconds),
- community,
- roster,
+ roster: roster.as_ref().map(WhatsAppRoster::from),
sending_identity: account.and_then(|a| a.identity_jid),
limits: Capabilities::default(),
})
}
- /// Read the complete timeline through view access, without remote membership.
+ /// Read the complete timeline through view access, without remote
+ /// membership. `limit` defaults to [`DEFAULT_PAGE`], at most [`PAGE_LIMIT`].
pub async fn messages<T: RequiredPermission>(
&self,
access: &EntityAccessReceipt<T>,
before: Option<Uuid>,
- limit: i64,
+ limit: Option<i64>,
) -> LinkedResult<WhatsAppGroupMessages> {
let (user, id) = view_scope(access)?;
- if !(1..=100).contains(&limit) {
- return Err(LinkedError::Invalid("limit must be between 1 and 100").into());
+ let limit = limit.unwrap_or(DEFAULT_PAGE);
+ if !(1..=PAGE_LIMIT).contains(&limit) {
+ return Err(LinkedError::Invalid("the page size is out of range").into());
}
self.timeline.messages(id, user, before, limit).await
}
+ /// One message through view access, as the timeline shows it.
+ pub async fn message<T: RequiredPermission>(
+ &self,
+ access: &EntityAccessReceipt<T>,
+ message: Uuid,
+ ) -> LinkedResult<WhatsAppGroupMessage> {
+ let (user, id) = view_scope(access)?;
+ self.timeline
+ .message(id, user, message)
+ .await?
+ .ok_or_else(|| LinkedError::NotFound.into())
+ }
/// Advance the caller's own read cursor monotonically.
- #[tracing::instrument(name="whatsapp.groups.read",skip_all,err,fields(message_id=%message))]
+ #[tracing::instrument(name = "whatsapp.linked.read", skip_all, err, fields(group_id, message_id = %message))]
pub async fn mark_read<T: RequiredPermission>(
&self,
access: &EntityAccessReceipt<T>,
message: Uuid,
) -> LinkedResult<()> {
let (user, id) = receipt_scope(access)?;
+ tracing::Span::current().record("group_id", tracing::field::display(id));
self.timeline.mark_read(id, user, message).await
}
/// List only the caller's pending, uncertain or failed sends.
@@ -118,7 +127,7 @@ impl LinkedService {
/// Only the actual owner, in a session of their own, controls link, team
/// and channel sharing; ordinary people grants use the generic
/// direct-access endpoints. Everything is shared read-only.
- #[tracing::instrument(name = "whatsapp.groups.permissions", skip_all, err, fields(group_id))]
+ #[tracing::instrument(name = "whatsapp.linked.permissions", skip_all, err, fields(group_id))]
pub async fn update_permissions<T: RequiredPermission>(
&self,
access: &EntityAccessReceipt<T>,
@@ -129,9 +138,7 @@ impl LinkedService {
let (user, id) = receipt_scope(access)?;
tracing::Span::current().record("group_id", tracing::field::display(id));
let facts = self.timeline.share_facts(id).await?;
- let actor =
- MacroUserIdStr::try_from(user.to_owned()).map_err(|_| LinkedError::Forbidden)?;
- if !facts.owner.is_user(&actor) {
+ if !facts.owner.is_user(user) {
return Err(LinkedError::Forbidden.into());
}
if update
@@ -148,7 +155,7 @@ impl LinkedService {
.unwrap_or_default(),
)?;
let command = authorize_team_share(
- Some(&actor),
+ Some(user),
&facts,
TeamShareRequest {
access_level: update.team_share_access_level,
diff --git a/crates/whatsapp_linked/src/domain/session.rs b/crates/whatsapp_linked/src/domain/session.rs
index cb88d997dc..795fd708b8 100644
--- a/crates/whatsapp_linked/src/domain/session.rs
+++ b/crates/whatsapp_linked/src/domain/session.rs
@@ -3,7 +3,12 @@
//! [`SessionService::begin_lease`]; every write is fenced by that epoch, and a
//! `Fenced` error means the replica must stop the account immediately.
-use super::{events::*, models::*, ports::*, service::is_group_jid};
+use super::{
+ events::*,
+ jid::{Jid, JidKind, is_group_jid, is_person_jid},
+ models::*,
+ ports::*,
+};
use std::sync::Arc;
use uuid::Uuid;
@@ -48,6 +53,12 @@ impl SessionService {
self.repository.release_lease(scope).await
}
+ /// Tell other replicas an unlocked account still needs a session. Call
+ /// after unlocking, or the next replica's lock attempt loses the race.
+ pub async fn announce_released(&self, account: Uuid) -> LinkedResult<()> {
+ self.repository.announce_released(account).await
+ }
+
/// Lifecycle of an account, for discovery and stop decisions.
pub async fn account_state(&self, account: Uuid) -> LinkedResult<Option<AccountState>> {
self.repository.account_state(account).await
@@ -93,9 +104,13 @@ impl SessionService {
PairingUpdate::PairCode(code) => ("pair_code", !code.is_empty() && code.len() <= 64),
PairingUpdate::Passkey { challenge } => (
"passkey",
- challenge.is_object() && challenge.to_string().len() <= 32 * 1024,
+ challenge.is_object() && challenge.to_string().len() <= PASSKEY_LIMIT_BYTES,
+ ),
+ PairingUpdate::Success { identity_jid } => (
+ "success",
+ Jid::parse(identity_jid).is_some_and(|jid| jid.kind == JidKind::Phone),
),
- PairingUpdate::Success { identity_jid } => ("success", is_user_jid(identity_jid)),
+ PairingUpdate::Expired => ("expired", true),
PairingUpdate::Failed => ("failed", true),
};
tracing::Span::current().record("update", name);
@@ -227,23 +242,35 @@ impl SessionService {
}
/// Record what the account learned about chats in its WhatsApp chat list
- /// (history sync, live messages, contact and chat-setting updates).
- #[tracing::instrument(name = "whatsapp.session.update_chats", skip_all, err, fields(account_id = %scope.account_id, count = chats.len()))]
+ /// (history sync, live messages, contact and chat-setting updates). A
+ /// batch is a whole history sync, so a chat whose JID or kind is invalid
+ /// is skipped (counted on the span) rather than refusing the rest.
+ #[tracing::instrument(name = "whatsapp.session.update_chats", skip_all, err, fields(account_id = %scope.account_id, count = chats.len(), skipped))]
pub async fn update_chats(
&self,
scope: SessionScope,
chats: &[ChatUpdate],
- ) -> LinkedResult<()> {
+ ) -> LinkedResult<bool> {
let valid: Vec<ChatUpdate> = chats
.iter()
.filter(|chat| match chat.kind {
ChatKind::Group => is_group_jid(&chat.jid),
- ChatKind::Direct => is_user_jid(&chat.jid) || is_lid_jid(&chat.jid),
+ ChatKind::Direct => is_person_jid(&chat.jid),
})
.cloned()
.collect();
+ let skipped = chats.len() - valid.len();
+ tracing::Span::current().record("skipped", skipped);
+ if skipped > 0 {
+ tracing::debug!(
+ account_id = %scope.account_id,
+ skipped,
+ reason = "invalid_chat_jid",
+ "Skipped WhatsApp chats with an invalid JID"
+ );
+ }
if valid.is_empty() {
- return Ok(());
+ return Ok(false);
}
self.repository.update_chats(scope, &valid).await
}
@@ -256,6 +283,18 @@ impl SessionService {
Ok(work)
}
+ /// No message of an added chat is known to start importing from.
+ #[tracing::instrument(name = "whatsapp.session.backfill_waiting_for_message", skip_all, err, fields(account_id = %scope.account_id, group_id = %group))]
+ pub async fn backfill_waiting_for_message(
+ &self,
+ scope: SessionScope,
+ group: Uuid,
+ ) -> LinkedResult<()> {
+ self.repository
+ .backfill_waiting_for_message(scope, group)
+ .await
+ }
+
/// A page of earlier messages was requested from the phone just now.
#[tracing::instrument(name = "whatsapp.session.backfill_requested", skip_all, err, fields(account_id = %scope.account_id, group_id = %group))]
pub async fn backfill_requested(&self, scope: SessionScope, group: Uuid) -> LinkedResult<()> {
@@ -277,7 +316,7 @@ impl SessionService {
page: &HistoryPage,
) -> LinkedResult<Vec<(Uuid, BackfillState)>> {
if !is_group_jid(&page.chat_jid) && !is_person_jid(&page.chat_jid) {
- return Ok(vec![]);
+ return Err(LinkedError::Invalid("a history page names no WhatsApp chat").into());
}
self.repository.backfill_page(scope, page).await
}
@@ -308,7 +347,7 @@ impl SessionService {
/// Persist an event durably without notification or document work, so the protocol event can
/// be acknowledged right after; `replay_deferred` ingests it. Idempotent on
- /// `event_id`. `Unavailable` when the account's backlog is full: do not ack.
+ /// `event_id`. `Backlogged` when the account's backlog is full: do not ack.
#[tracing::instrument(name = "whatsapp.session.enqueue_inbound", skip_all, err, fields(account_id = %scope.account_id, event_id = %event.event_id))]
pub async fn enqueue_inbound(
&self,
@@ -337,6 +376,7 @@ impl SessionService {
Err(error) => tracing::warn!(
event_id = %event.event_id,
code = error.current_context().code(),
+ error = %error,
"Deferred WhatsApp event will retry"
),
}
@@ -395,22 +435,6 @@ impl SessionService {
}
}
-/// Phone-number user JIDs, the form a paired account reports.
-fn is_user_jid(jid: &str) -> bool {
- jid.len() <= 256
- && jid
- .strip_suffix("@s.whatsapp.net")
- .is_some_and(|user| !user.is_empty() && user.bytes().all(|b| b.is_ascii_digit()))
-}
-
-/// Phone-number or LID JIDs that can identify a person.
-fn is_person_jid(jid: &str) -> bool {
- is_user_jid(jid)
- || jid.strip_suffix("@lid").is_some_and(|user| {
- !user.is_empty() && user.len() <= 64 && user.bytes().all(|b| b.is_ascii_digit())
- })
-}
-
pub(crate) fn validate_event(event: &InboundEvent) -> LinkedResult<()> {
let direct = is_person_jid(&event.group_jid);
if !is_group_jid(&event.group_jid) && !direct {
@@ -504,10 +528,3 @@ pub(crate) fn validate_event(event: &InboundEvent) -> LinkedResult<()> {
}
}
}
-
-fn is_lid_jid(jid: &str) -> bool {
- jid.len() <= 256
- && jid
- .strip_suffix("@lid")
- .is_some_and(|user| !user.is_empty() && user.bytes().all(|b| b.is_ascii_digit()))
-}
diff --git a/crates/whatsapp_linked/src/domain/timeline.rs b/crates/whatsapp_linked/src/domain/timeline.rs
index a33457051f..c53c352f15 100644
--- a/crates/whatsapp_linked/src/domain/timeline.rs
+++ b/crates/whatsapp_linked/src/domain/timeline.rs
@@ -2,6 +2,7 @@
use super::{models::*, ports::LinkedResult};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
use models_permissions::share_permission::{SharePermissionV2, UpdateSharePermissionRequestV2};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
@@ -11,6 +12,7 @@ pub mod view;
/// Adopted group visible through ordinary entity sharing.
#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
pub struct WhatsAppGroupSummary {
/// Entity identifier.
@@ -21,7 +23,8 @@ pub struct WhatsAppGroupSummary {
pub kind: ChatKind,
/// Actual entity owner.
pub user_id: String,
- /// Unread live messages for this viewer.
+ /// Unread live messages for this viewer, counted up to
+ /// [`UNREAD_COUNT_CAP`].
pub unread_count: i64,
/// Latest message timestamp.
pub last_message_at: Option<DateTime<Utc>>,
@@ -29,12 +32,15 @@ pub struct WhatsAppGroupSummary {
pub can_send: bool,
/// Reason sending is blocked.
pub send_reason: Option<ReplyBlock>,
- /// Importing earlier messages after the group was added; `null` for
- /// groups added before this existed.
+ /// Importing earlier messages after the chat was added; `null` when
+ /// there is nothing to import.
pub backfill: Option<Backfill>,
+ /// The WhatsApp community this group belongs to, if any.
+ pub community: Option<CommunityReference>,
}
/// Full group detail and current viewer capabilities.
#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
pub struct WhatsAppGroupDetail {
/// List metadata.
@@ -45,19 +51,68 @@ pub struct WhatsAppGroupDetail {
/// Caller's effective permission.
pub access_level: models_permissions::share_permission::access_level::AccessLevel,
/// Latest remote metadata, absent when no observer is connected.
- pub roster: Option<GroupInfo>,
+ pub roster: Option<WhatsAppRoster>,
/// WhatsApp's disappearing-messages timer in seconds while it is on;
/// Macro keeps the messages anyway. `null` when off or unknown.
pub disappearing_seconds: Option<u32>,
- /// The WhatsApp community this group belongs to, if any.
- pub community: Option<CommunityReference>,
/// Caller's own phone identity, never another account's identity.
pub sending_identity: Option<String>,
/// Size and mutation limits.
pub limits: Capabilities,
}
+/// A chat's WhatsApp metadata as the caller's account last read it.
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+pub struct WhatsAppRoster {
+ /// WhatsApp subject.
+ pub name: String,
+ /// Everyone in the chat.
+ pub participants: Vec<WhatsAppParticipant>,
+ /// Only admins may post.
+ pub announce: bool,
+ /// When this was read from WhatsApp.
+ pub observed_at: DateTime<Utc>,
+}
+
+/// Someone in a WhatsApp chat; Macro access is a separate grant.
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+pub struct WhatsAppParticipant {
+ /// Phone-number or LID JID.
+ pub jid: String,
+ /// The other address WhatsApp verified for them.
+ pub alternate_jid: Option<String>,
+ /// Their WhatsApp name, untrusted.
+ pub display_name: Option<String>,
+ /// Group admin.
+ pub admin: bool,
+}
+
+impl From<&GroupInfo> for WhatsAppRoster {
+ fn from(info: &GroupInfo) -> Self {
+ Self {
+ name: info.name.clone(),
+ participants: info
+ .participants
+ .iter()
+ .map(|participant| WhatsAppParticipant {
+ jid: participant.identity.jid.clone(),
+ alternate_jid: participant.identity.alternate_jid.clone(),
+ display_name: participant.identity.display_name.clone(),
+ admin: participant.admin,
+ })
+ .collect(),
+ announce: info.announce,
+ observed_at: info.observed_at,
+ }
+ }
+}
+
/// Message sender from protocol-verified identity evidence.
#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
pub struct WhatsAppGroupSender {
/// External person identity.
@@ -69,6 +124,7 @@ pub struct WhatsAppGroupSender {
}
/// Grouped reactions.
#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
pub struct WhatsAppGroupReaction {
/// Emoji.
@@ -80,6 +136,7 @@ pub struct WhatsAppGroupReaction {
}
/// One message in an adopted group.
#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
pub struct WhatsAppGroupMessage {
/// Stable message id.
@@ -219,6 +276,7 @@ pub enum WhatsAppRichContent {
/// Newest-first timeline page; `before` is the last returned message id.
#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
pub struct WhatsAppGroupMessages {
/// Messages in descending sent_at, id order.
@@ -228,6 +286,7 @@ pub struct WhatsAppGroupMessages {
}
/// Mark messages through this message read.
#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
pub struct MarkRead {
/// Message in the addressed group.
@@ -235,15 +294,76 @@ pub struct MarkRead {
}
/// Adoption response.
#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
pub struct AdoptedGroup {
/// Shareable entity identifier.
pub group_id: Uuid,
}
+/// Most unread messages counted per chat; the list shows more as this many.
+pub const UNREAD_COUNT_CAP: i64 = 100;
+
+/// What the store knows about one chat for one viewer; the domain turns it
+/// into a [`WhatsAppGroupSummary`] for both the list and the detail.
+#[derive(Debug, Clone)]
+pub struct GroupFacts {
+ /// Entity identifier.
+ pub id: Uuid,
+ /// Display name.
+ pub name: String,
+ /// Group or direct chat.
+ pub kind: ChatKind,
+ /// Owner.
+ pub user_id: String,
+ /// Unread live messages for this viewer, at most [`UNREAD_COUNT_CAP`].
+ pub unread_count: i64,
+ /// Latest message timestamp.
+ pub last_message_at: Option<DateTime<Utc>>,
+ /// History import progress.
+ pub backfill: Option<Backfill>,
+ /// The community the newest roster any observer reported names.
+ pub community: Option<CommunityFacts>,
+}
+
+/// A chat's community as its observers' rosters report it.
+#[derive(Debug, Clone)]
+pub struct CommunityFacts {
+ /// The community's JID.
+ pub jid: String,
+ /// The community's own name, when an observer has its metadata.
+ pub name: Option<String>,
+ /// The chat is the community's announcement group.
+ pub announcements: bool,
+}
+
+impl GroupFacts {
+ /// The chat as the list and the detail show it.
+ pub fn summary(self, send_reason: Option<ReplyBlock>) -> WhatsAppGroupSummary {
+ WhatsAppGroupSummary {
+ id: self.id,
+ name: self.name,
+ kind: self.kind,
+ user_id: self.user_id,
+ unread_count: self.unread_count,
+ last_message_at: self.last_message_at,
+ can_send: send_reason.is_none(),
+ send_reason,
+ backfill: self.backfill,
+ community: self.community.map(|community| {
+ CommunityReference::named(
+ community.jid,
+ community.name.as_deref(),
+ community.announcements,
+ )
+ }),
+ }
+ }
+}
+
/// Batched facts for one visible entity and the caller's own remote roster.
pub struct VisibleGroup {
- /// Shared entity metadata.
- pub summary: WhatsAppGroupSummary,
+ /// Shared entity facts.
+ pub facts: GroupFacts,
/// Lifecycle and remote group identity.
pub binding: Binding,
/// Caller-account roster, absent when not connected or not a remote member.
@@ -254,19 +374,32 @@ pub struct VisibleGroup {
#[async_trait]
pub trait TimelineRepository: Send + Sync {
/// Candidate list already filtered by generic sharing.
- async fn visible_groups(&self, user: &str) -> LinkedResult<Vec<VisibleGroup>>;
- /// Metadata for an authorized group.
- async fn summary(&self, group: Uuid, user: &str) -> LinkedResult<WhatsAppGroupSummary>;
- /// Bounded, stable pagination.
+ async fn visible_groups(&self, user: &MacroUserIdStr<'_>) -> LinkedResult<Vec<VisibleGroup>>;
+ /// Facts for an authorized group, for a viewer principal (a person or a
+ /// bot, whose id is not a Macro user id).
+ async fn group_facts(&self, group: Uuid, viewer: &str) -> LinkedResult<GroupFacts>;
+ /// Bounded, stable pagination for a viewer principal.
async fn messages(
&self,
group: Uuid,
- user: &str,
+ viewer: &str,
before: Option<Uuid>,
limit: i64,
) -> LinkedResult<WhatsAppGroupMessages>;
+ /// One message of the timeline, shaped like a page entry.
+ async fn message(
+ &self,
+ group: Uuid,
+ viewer: &str,
+ message: Uuid,
+ ) -> LinkedResult<Option<WhatsAppGroupMessage>>;
/// Monotone viewer read cursor, scoped to this group.
- async fn mark_read(&self, group: Uuid, user: &str, message: Uuid) -> LinkedResult<()>;
+ async fn mark_read(
+ &self,
+ group: Uuid,
+ user: &MacroUserIdStr<'_>,
+ message: Uuid,
+ ) -> LinkedResult<()>;
/// Standard permission object.
async fn permissions(&self, group: Uuid) -> LinkedResult<SharePermissionV2>;
/// Guarded canonical team-sharing facts for domain authorization.
@@ -278,7 +411,7 @@ pub trait TimelineRepository: Send + Sync {
async fn update_permissions(
&self,
group: Uuid,
- user: &str,
+ user: &MacroUserIdStr<'_>,
update: &UpdateSharePermissionRequestV2,
command: Option<
&models_permissions::share_permission::team_share::AuthorizedTeamShareCommand,
diff --git a/crates/whatsapp_linked/src/domain/timeline/view.rs b/crates/whatsapp_linked/src/domain/timeline/view.rs
index c4e05707b0..14a146bf7c 100644
--- a/crates/whatsapp_linked/src/domain/timeline/view.rs
+++ b/crates/whatsapp_linked/src/domain/timeline/view.rs
@@ -29,9 +29,7 @@ impl People {
return person.clone();
}
WhatsAppPersonRef {
- name: jid
- .strip_suffix("@s.whatsapp.net")
- .map(|phone| format!("+{phone}"))
+ name: crate::domain::jid::phone_number(jid)
.unwrap_or_else(|| UNKNOWN_PERSON.to_owned()),
user_id: None,
}
diff --git a/crates/whatsapp_linked/src/inbound/router.rs b/crates/whatsapp_linked/src/inbound/router.rs
index fee171116f..3107d6ba35 100644
--- a/crates/whatsapp_linked/src/inbound/router.rs
+++ b/crates/whatsapp_linked/src/inbound/router.rs
@@ -62,7 +62,7 @@ impl From<rootcause::Report<LinkedError>> for ApiError {
fn from(error: rootcause::Report<LinkedError>) -> Self {
if matches!(
error.current_context(),
- LinkedError::Unavailable | LinkedError::Fenced
+ LinkedError::Unavailable | LinkedError::Fenced | LinkedError::Internal
) {
tracing::error!(error = ?error, "WhatsApp linked request failed");
}
@@ -77,12 +77,11 @@ impl IntoResponse for ApiError {
LinkedError::Forbidden => StatusCode::FORBIDDEN,
LinkedError::RateLimited => StatusCode::TOO_MANY_REQUESTS,
LinkedError::NotFound | LinkedError::ConfigurationRequired => StatusCode::NOT_FOUND,
- LinkedError::Conflict
- | LinkedError::IdentityConflict
- | LinkedError::Disconnected
- | LinkedError::SendExpired => StatusCode::CONFLICT,
- LinkedError::Unavailable => StatusCode::SERVICE_UNAVAILABLE,
- LinkedError::Fenced => StatusCode::INTERNAL_SERVER_ERROR,
+ LinkedError::Conflict | LinkedError::Disconnected | LinkedError::SendExpired => {
+ StatusCode::CONFLICT
+ }
+ LinkedError::Unavailable | LinkedError::Backlogged => StatusCode::SERVICE_UNAVAILABLE,
+ LinkedError::Fenced | LinkedError::Internal => StatusCode::INTERNAL_SERVER_ERROR,
};
let mut response = (
status,
@@ -100,6 +99,7 @@ impl IntoResponse for ApiError {
/// Explicit pairing intent; replacement is a separate deliberate action.
#[derive(Deserialize, utoipa::ToSchema)]
+#[serde(rename_all = "camelCase")]
#[schema(as = LinkedConnect)]
pub struct Connect {
/// Replace the retained identity with a different WhatsApp account.
@@ -109,6 +109,7 @@ pub struct Connect {
/// The consent generation the owner deliberately disconnects.
#[derive(Deserialize, Serialize, utoipa::ToSchema)]
+#[serde(rename_all = "camelCase")]
#[schema(as = LinkedDisconnectRequest)]
pub struct DisconnectRequest {
/// Fences retries against a later reconnect or replacement.
@@ -153,6 +154,10 @@ where
"/whatsapp-groups/{group_id}/messages",
get(messages::<Eas, Auth>),
)
+ .route(
+ "/whatsapp-groups/{group_id}/messages/{message_id}",
+ get(message::<Eas, Auth>),
+ )
.route(
"/whatsapp-groups/{group_id}/read",
post(mark_read::<Eas, Auth>),
@@ -210,7 +215,7 @@ pub async fn account<Eas, Auth: MacroAuthorizationService>(
Ok(Json(AccountView {
account: state
.service
- .account(auth.authorization.macro_user_id.as_ref())
+ .account(&auth.authorization.macro_user_id)
.await?,
}))
}
@@ -226,7 +231,7 @@ pub async fn connect<Eas, Auth: MacroAuthorizationService>(
state
.service
.connect(
- auth.authorization.macro_user_id.as_ref(),
+ &auth.authorization.macro_user_id,
body.replace,
authority(&auth.authorization),
)
@@ -245,7 +250,7 @@ pub async fn pairing<Eas, Auth: MacroAuthorizationService>(
state
.service
.pair_state(
- auth.authorization.macro_user_id.as_ref(),
+ &auth.authorization.macro_user_id,
id,
authority(&auth.authorization),
)
@@ -263,7 +268,7 @@ pub async fn cancel<Eas, Auth: MacroAuthorizationService>(
state
.service
.cancel(
- auth.authorization.macro_user_id.as_ref(),
+ &auth.authorization.macro_user_id,
id,
authority(&auth.authorization),
)
@@ -282,7 +287,7 @@ pub async fn passkey<Eas, Auth: MacroAuthorizationService>(
state
.service
.passkey(
- auth.authorization.macro_user_id.as_ref(),
+ &auth.authorization.macro_user_id,
id,
&body,
authority(&auth.authorization),
@@ -354,7 +359,7 @@ pub async fn disconnect<Eas, Auth: MacroAuthorizationService>(
state
.service
.disconnect(
- auth.authorization.macro_user_id.as_ref(),
+ &auth.authorization.macro_user_id,
body.authorization_generation,
authority(&auth.authorization),
)
@@ -372,7 +377,7 @@ pub async fn chats<Eas, Auth: MacroAuthorizationService>(
Ok(Json(
state
.service
- .chats(auth.authorization.macro_user_id.as_ref())
+ .chats(&auth.authorization.macro_user_id)
.await?,
))
}
@@ -387,7 +392,7 @@ pub async fn adopt<Eas, Auth: MacroAuthorizationService>(
let binding = state
.service
.adopt(
- auth.authorization.macro_user_id.as_ref(),
+ &auth.authorization.macro_user_id,
&body,
authority(&auth.authorization),
)
@@ -461,29 +466,25 @@ pub async fn message_attachments<Eas: EntityAccessService, Auth: MacroAuthorizat
))
}
-/// Stop syncing the group, locally.
+/// Stop syncing the group, locally. Owner only, in their own session.
#[utoipa::path(delete, path = "/meta/linked/whatsapp-groups/{group_id}", operation_id = "linked_detach", params(("group_id" = Uuid, Path)), responses((status = 204)))]
-pub async fn detach<Eas, Auth: MacroAuthorizationService>(
+pub async fn detach<Eas: EntityAccessService, Auth: MacroAuthorizationService>(
State(state): State<LinkedRouterState<Eas, Auth>>,
auth: MacroAuthorizationExtractor<Auth, UserOnly>,
- Path(group_id): Path<Uuid>,
+ access: WhatsAppGroupAccessLevelExtractor<OwnerAccessLevel, Eas, Auth>,
) -> Result<StatusCode, ApiError> {
state
.service
.detach(
- auth.authorization.macro_user_id.as_ref(),
- group_id,
+ &access.entity_access_receipt,
authority(&auth.authorization),
)
.await?;
Ok(StatusCode::NO_CONTENT)
}
-#[cfg(test)]
-mod test;
-
/// List adopted groups the caller can view, including without WhatsApp.
-#[utoipa::path(get,path="/meta/linked/whatsapp-groups",operation_id="whatsapp_groups",responses((status=200,body=Vec<WhatsAppGroupSummary>)))]
+#[utoipa::path(get, path = "/meta/linked/whatsapp-groups", operation_id = "whatsapp_groups", responses((status = 200, body = Vec<WhatsAppGroupSummary>)))]
pub async fn adopted_groups<Eas, Auth: MacroAuthorizationService>(
State(state): State<LinkedRouterState<Eas, Auth>>,
auth: MacroAuthorizationExtractor<Auth, UserOnly>,
@@ -491,20 +492,23 @@ pub async fn adopted_groups<Eas, Auth: MacroAuthorizationService>(
Ok(Json(
state
.service
- .adopted_groups(auth.authorization.macro_user_id.as_ref())
+ .adopted_groups(&auth.authorization.macro_user_id)
.await?,
))
}
+
/// Stable timeline pagination.
#[derive(Deserialize, utoipa::IntoParams)]
+#[serde(rename_all = "camelCase")]
pub struct TimelineQuery {
/// Last message id in the previous page.
pub before: Option<Uuid>,
- /// Page size, 1 through 100.
+ /// Page size, up to [`PAGE_LIMIT`]; [`DEFAULT_PAGE`] when absent.
pub limit: Option<i64>,
}
+
/// Newest-first timeline through ordinary view access.
-#[utoipa::path(get,path="/meta/linked/whatsapp-groups/{group_id}/messages",operation_id="whatsapp_group_messages",params(("group_id"=Uuid,Path),TimelineQuery),responses((status=200,body=WhatsAppGroupMessages)))]
+#[utoipa::path(get, path = "/meta/linked/whatsapp-groups/{group_id}/messages", operation_id = "whatsapp_group_messages", params(("group_id" = Uuid, Path), TimelineQuery), responses((status = 200, body = WhatsAppGroupMessages)))]
pub async fn messages<Eas: EntityAccessService, Auth: MacroAuthorizationService>(
State(state): State<LinkedRouterState<Eas, Auth>>,
access: WhatsAppGroupAccessLevelExtractor<ViewAccessLevel, Eas, Auth>,
@@ -513,16 +517,37 @@ pub async fn messages<Eas: EntityAccessService, Auth: MacroAuthorizationService>
Ok(Json(
state
.service
- .messages(
- &access.entity_access_receipt,
- query.before,
- query.limit.unwrap_or(50),
- )
+ .messages(&access.entity_access_receipt, query.before, query.limit)
.await?,
))
}
+
+/// Path of one timeline message.
+#[derive(Deserialize)]
+pub struct MessagePath {
+ /// Unused here; the access extractor reads it.
+ pub group_id: Uuid,
+ /// The message.
+ pub message_id: Uuid,
+}
+
+/// One message of the timeline, as the timeline shows it.
+#[utoipa::path(get, path = "/meta/linked/whatsapp-groups/{group_id}/messages/{message_id}", operation_id = "whatsapp_group_message", params(("group_id" = Uuid, Path), ("message_id" = Uuid, Path)), responses((status = 200, body = WhatsAppGroupMessage)))]
+pub async fn message<Eas: EntityAccessService, Auth: MacroAuthorizationService>(
+ State(state): State<LinkedRouterState<Eas, Auth>>,
+ access: WhatsAppGroupAccessLevelExtractor<ViewAccessLevel, Eas, Auth>,
+ Path(path): Path<MessagePath>,
+) -> Result<Json<WhatsAppGroupMessage>, ApiError> {
+ Ok(Json(
+ state
+ .service
+ .message(&access.entity_access_receipt, path.message_id)
+ .await?,
+ ))
+}
+
/// Advance this viewer's read position.
-#[utoipa::path(post,path="/meta/linked/whatsapp-groups/{group_id}/read",operation_id="whatsapp_group_read",params(("group_id"=Uuid,Path)),request_body=MarkRead,responses((status=204)))]
+#[utoipa::path(post, path = "/meta/linked/whatsapp-groups/{group_id}/read", operation_id = "whatsapp_group_read", params(("group_id" = Uuid, Path)), request_body = MarkRead, responses((status = 204)))]
pub async fn mark_read<Eas: EntityAccessService, Auth: MacroAuthorizationService>(
State(state): State<LinkedRouterState<Eas, Auth>>,
access: WhatsAppGroupAccessLevelExtractor<ViewAccessLevel, Eas, Auth>,
@@ -534,8 +559,9 @@ pub async fn mark_read<Eas: EntityAccessService, Auth: MacroAuthorizationService
.await?;
Ok(StatusCode::NO_CONTENT)
}
+
/// Caller-owned pending, failed and uncertain sends.
-#[utoipa::path(get,path="/meta/linked/whatsapp-groups/{group_id}/sends",operation_id="whatsapp_group_sends",params(("group_id"=Uuid,Path)),responses((status=200,body=Vec<SendProgress>)))]
+#[utoipa::path(get, path = "/meta/linked/whatsapp-groups/{group_id}/sends", operation_id = "whatsapp_group_sends", params(("group_id" = Uuid, Path)), responses((status = 200, body = Vec<SendProgress>)))]
pub async fn open_sends<Eas: EntityAccessService, Auth: MacroAuthorizationService>(
State(state): State<LinkedRouterState<Eas, Auth>>,
access: WhatsAppGroupAccessLevelExtractor<ViewAccessLevel, Eas, Auth>,
@@ -547,8 +573,9 @@ pub async fn open_sends<Eas: EntityAccessService, Auth: MacroAuthorizationServic
.await?,
))
}
+
/// Generic Share dialog policy.
-#[utoipa::path(get,path="/meta/linked/whatsapp-groups/{group_id}/permissions",operation_id="whatsapp_group_permissions",params(("group_id"=Uuid,Path)),responses((status=200,body=SharePermissionV2)))]
+#[utoipa::path(get, path = "/meta/linked/whatsapp-groups/{group_id}/permissions", operation_id = "whatsapp_group_permissions", params(("group_id" = Uuid, Path)), responses((status = 200, body = SharePermissionV2)))]
pub async fn permissions<Eas: EntityAccessService, Auth: MacroAuthorizationService>(
State(state): State<LinkedRouterState<Eas, Auth>>,
access: WhatsAppGroupAccessLevelExtractor<ViewAccessLevel, Eas, Auth>,
@@ -560,8 +587,9 @@ pub async fn permissions<Eas: EntityAccessService, Auth: MacroAuthorizationServi
.await?,
))
}
+
/// The owner, in their own session, updates link, team and channel sharing.
-#[utoipa::path(patch,path="/meta/linked/whatsapp-groups/{group_id}/permissions",operation_id="whatsapp_group_update_permissions",params(("group_id"=Uuid,Path)),request_body=UpdateSharePermissionRequestV2,responses((status=204)))]
+#[utoipa::path(patch, path = "/meta/linked/whatsapp-groups/{group_id}/permissions", operation_id = "whatsapp_group_update_permissions", params(("group_id" = Uuid, Path)), request_body = UpdateSharePermissionRequestV2, responses((status = 204)))]
pub async fn update_permissions<Eas: EntityAccessService, Auth: MacroAuthorizationService>(
State(state): State<LinkedRouterState<Eas, Auth>>,
auth: MacroAuthorizationExtractor<Auth, UserOnly>,
@@ -578,3 +606,6 @@ pub async fn update_permissions<Eas: EntityAccessService, Auth: MacroAuthorizati
.await?;
Ok(StatusCode::NO_CONTENT)
}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/whatsapp_linked/src/inbound/router/test.rs b/crates/whatsapp_linked/src/inbound/router/test.rs
index ece9fd2a81..a28b866062 100644
--- a/crates/whatsapp_linked/src/inbound/router/test.rs
+++ b/crates/whatsapp_linked/src/inbound/router/test.rs
@@ -1,5 +1,7 @@
use super::*;
+mod http;
+
#[tokio::test]
async fn a_rate_limited_request_returns_429_with_retry_after() {
let response = ApiError(LinkedError::RateLimited).into_response();
diff --git a/crates/whatsapp_linked/src/inbound/router/test/http.rs b/crates/whatsapp_linked/src/inbound/router/test/http.rs
new file mode 100644
index 0000000000..3d0df60d02
--- /dev/null
+++ b/crates/whatsapp_linked/src/inbound/router/test/http.rs
@@ -0,0 +1,498 @@
+//! Every route's credential rules, over HTTP, against the real router,
+//! repository and entity access.
+
+use super::*;
+use crate::domain::{
+ events::{InboundEvent, InboundKind, Message, MessageKind, PairingUpdate},
+ ports::{LinkedResult, SendRateLimiter},
+ session::SessionService,
+};
+use crate::outbound::pg::PgLinkedRepository;
+use async_trait::async_trait;
+use axum::body::Body;
+use axum::http::{Method, Request};
+use entity_access::{
+ domain::{models::EntityType, service::EntityAccessServiceImpl},
+ outbound::PgAccessRepository,
+};
+use macro_authorization::{
+ BotActingUserClaims, BotAuthentication, BotScope, HarnessAuthentication,
+ HarnessAuthorizationOwner, InternalIdentityClaims, MacroAuthorizationError,
+ ValidatedCredential, ValidatedIdentity,
+};
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use model_user::UserContext;
+use rootcause::Report;
+use sqlx::PgPool;
+use tower::ServiceExt;
+
+const GROUP: &str = "[email protected]";
+/// A test user's id, typed.
+fn person(user: &str) -> macro_user_id::user_id::MacroUserIdStr<'static> {
+ user.to_owned().try_into().expect("test user ids are valid")
+}
+
+const ALICE: &str = "macro|[email protected]";
+const BOB: &str = "macro|[email protected]";
+const ALICE_JID: &str = "[email protected]";
+const CUSTOMER_JID: &str = "[email protected]";
+
+/// Bearer tokens and keys the fake authorizer knows. Every one acts for Alice,
+/// the chat's owner, except Bob's session.
+const ALICE_SESSION: &str = "alice-session";
+const BOB_SESSION: &str = "bob-session";
+const ALICE_API_JWT: &str = "alice-api-jwt";
+const ALICE_API_KEY: &str = "alice-api-key";
+const BOT_TOKEN: &str = "bot-token";
+const HARNESS_TOKEN: &str = "harness-token";
+
+fn context(user: &str) -> UserContext {
+ UserContext {
+ user_id: user.to_owned(),
+ fusion_user_id: "fusion-user-id".to_owned(),
+ organization_id: None,
+ permissions: None,
+ }
+}
+
+fn acting(user: &str, origin: CredentialOrigin) -> MacroUserAuthentication {
+ MacroUserAuthentication {
+ origin,
+ agent_id: None,
+ macro_user_id: user.to_owned().try_into().unwrap(),
+ user_context: context(user),
+ }
+}
+
+#[derive(Clone)]
+struct Credentials;
+
+impl MacroAuthorizationService for Credentials {
+ async fn authorize(&self, jwt: &str) -> Result<UserContext, Report<MacroAuthorizationError>> {
+ self.authorize_identity(jwt)
+ .await
+ .map(|credential| UserContext {
+ user_id: credential.identity.user_id,
+ fusion_user_id: credential.identity.fusion_user_id,
+ organization_id: credential.identity.organization_id,
+ permissions: credential.identity.permissions,
+ })
+ }
+
+ async fn authorize_identity(
+ &self,
+ jwt: &str,
+ ) -> Result<ValidatedCredential, Report<MacroAuthorizationError>> {
+ let (user, origin) = match jwt {
+ ALICE_SESSION => (ALICE, CredentialOrigin::Session),
+ BOB_SESSION => (BOB, CredentialOrigin::Session),
+ ALICE_API_JWT => (ALICE, CredentialOrigin::MacroApiJwt),
+ _ => return Err(Report::new(MacroAuthorizationError::InvalidCredentials)),
+ };
+ Ok(ValidatedCredential {
+ identity: ValidatedIdentity {
+ agent_id: None,
+ user_id: user.to_owned(),
+ fusion_user_id: "fusion-user-id".to_owned(),
+ organization_id: None,
+ permissions: None,
+ },
+ origin,
+ })
+ }
+
+ async fn authorize_user_api_key(
+ &self,
+ api_key: &str,
+ ) -> Result<UserContext, Report<MacroAuthorizationError>> {
+ match api_key {
+ ALICE_API_KEY => Ok(context(ALICE)),
+ _ => Err(Report::new(MacroAuthorizationError::InvalidCredentials)),
+ }
+ }
+
+ async fn authorize_bot(
+ &self,
+ token: &str,
+ bot_scope: BotScope,
+ _claims: Option<BotActingUserClaims>,
+ ) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {
+ if token != BOT_TOKEN {
+ return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
+ }
+ Ok(BotAuthentication {
+ bot_id: serde_json::from_value(serde_json::json!(Uuid::from_u128(1))).unwrap(),
+ token_id: Uuid::from_u128(2),
+ bot_scope,
+ team_id: None,
+ acting_user: Some(acting(ALICE, CredentialOrigin::Bot)),
+ })
+ }
+
+ async fn authorize_harness(
+ &self,
+ token: &str,
+ _claim: Option<String>,
+ ) -> Result<HarnessAuthentication, Report<MacroAuthorizationError>> {
+ if token != HARNESS_TOKEN {
+ return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
+ }
+ Ok(HarnessAuthentication {
+ harness_id: harness_id::HarnessId::new_from_uuid(Uuid::from_u128(3)),
+ token_id: Uuid::from_u128(4),
+ owner: HarnessAuthorizationOwner::User {
+ user_id: ALICE.to_owned(),
+ },
+ acting_user: acting(ALICE, CredentialOrigin::Harness),
+ })
+ }
+
+ async fn authorize_internal(
+ &self,
+ _provided_key: &str,
+ _claims: InternalIdentityClaims,
+ ) -> Result<Option<UserContext>, Report<MacroAuthorizationError>> {
+ Err(Report::new(MacroAuthorizationError::InvalidCredentials))
+ }
+}
+
+struct Unlimited;
+
+#[async_trait]
+impl SendRateLimiter for Unlimited {
+ async fn check(&self, _: &macro_user_id::user_id::MacroUserIdStr<'_>) -> LinkedResult<()> {
+ Ok(())
+ }
+}
+
+async fn user(pool: &PgPool, id: &str) {
+ let email = id.trim_start_matches("macro|");
+ let macro_user = Uuid::now_v7();
+ sqlx::query!(
+ "INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES ($1, $2, $3, $2)",
+ macro_user,
+ id,
+ email
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+ sqlx::query!(
+ r#"INSERT INTO "User" (id, email, macro_user_id) VALUES ($1, $2, $3)"#,
+ id,
+ email,
+ macro_user
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+}
+
+#[derive(Clone, Copy, Debug)]
+enum Principal {
+ Session,
+ ApiJwt,
+ ApiKey,
+ Bot,
+ Harness,
+}
+
+fn request(principal: Principal, method: Method, path: &str, body: Body) -> Request<Body> {
+ let builder = Request::builder()
+ .method(method)
+ .uri(path)
+ .header(header::CONTENT_TYPE, "application/json");
+ let builder = match principal {
+ Principal::Session => {
+ builder.header(header::AUTHORIZATION, format!("Bearer {ALICE_SESSION}"))
+ }
+ Principal::ApiJwt => {
+ builder.header(header::AUTHORIZATION, format!("Bearer {ALICE_API_JWT}"))
+ }
+ Principal::ApiKey => {
+ builder.header(macro_authorization::USER_API_KEY_HEADER, ALICE_API_KEY)
+ }
+ Principal::Bot => builder
+ .header(macro_authorization::BOT_TOKEN_HEADER, BOT_TOKEN)
+ .header(macro_authorization::BOT_SCOPE_HEADER, "user"),
+ Principal::Harness => {
+ builder.header(macro_authorization::HARNESS_TOKEN_HEADER, HARNESS_TOKEN)
+ }
+ };
+ builder.body(body).unwrap()
+}
+
+fn upload_body() -> (String, Body) {
+ let boundary = "whatsapp-boundary";
+ let body = format!(
+ "--{boundary}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"note.txt\"\r\nContent-Type: text/plain\r\n\r\nhello\r\n--{boundary}--\r\n"
+ );
+ (
+ format!("multipart/form-data; boundary={boundary}"),
+ Body::from(body),
+ )
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn every_route_enforces_its_credential_rules(pool: PgPool) {
+ for id in [ALICE, BOB] {
+ user(&pool, id).await;
+ }
+ let repository = Arc::new(PgLinkedRepository::new(pool.clone()));
+ let service = Arc::new(LinkedService::new(
+ Features {
+ pairing: true,
+ adoption: true,
+ sending: true,
+ },
+ repository.clone(),
+ Arc::new(Unlimited),
+ ));
+ let session = SessionService::new(repository);
+ let pairing = service
+ .connect(&person(ALICE), false, SendAuthority::Human)
+ .await
+ .unwrap();
+ let lease = session.begin_lease(pairing.account_id).await.unwrap();
+ session
+ .update_pairing(
+ lease.scope,
+ pairing.id,
+ PairingUpdate::Success {
+ identity_jid: ALICE_JID.to_owned(),
+ },
+ )
+ .await
+ .unwrap();
+ let participant = |jid: &str| Participant {
+ identity: Identity {
+ jid: jid.to_owned(),
+ alternate_jid: None,
+ display_name: None,
+ },
+ admin: false,
+ };
+ session
+ .update_groups(
+ lease.scope,
+ &[GroupInfo {
+ jid: GROUP.into(),
+ name: "Customer escalations".into(),
+ participants: vec![participant(ALICE_JID), participant(CUSTOMER_JID)],
+ announce: false,
+ disappearing_seconds: None,
+ community_parent: false,
+ community_jid: None,
+ community_announcements: false,
+ observed_at: chrono::Utc::now(),
+ }],
+ true,
+ )
+ .await
+ .unwrap();
+ let binding = service
+ .adopt(
+ &person(ALICE),
+ &AdoptGroup {
+ group_jid: GROUP.into(),
+ },
+ SendAuthority::Human,
+ )
+ .await
+ .unwrap();
+ let mut tx = pool.begin().await.unwrap();
+ entity_access_db_utils::direct_share::set(
+ &mut tx,
+ &binding.id,
+ EntityType::WhatsAppGroup,
+ &BOB.to_owned().try_into().unwrap(),
+ Some(models_permissions::share_permission::access_level::AccessLevel::View),
+ false,
+ )
+ .await
+ .unwrap();
+ tx.commit().await.unwrap();
+ session
+ .ingest_event(
+ lease.scope,
+ &InboundEvent {
+ event_id: Uuid::from_u128(10),
+ group_jid: GROUP.into(),
+ chat_alternate_jid: None,
+ source_at: chrono::Utc::now(),
+ observed_at: chrono::Utc::now(),
+ kind: InboundKind::Message(Message {
+ source_id: "FIRST".into(),
+ sender: Identity {
+ jid: CUSTOMER_JID.into(),
+ alternate_jid: None,
+ display_name: Some("Customer".into()),
+ },
+ kind: MessageKind::Text,
+ text: "hello".into(),
+ history: false,
+ from_me: false,
+ revision: 0,
+ target: None,
+ media: vec![],
+ mentions: vec![],
+ forwarded: false,
+ view_once: false,
+ rich: None,
+ }),
+ },
+ )
+ .await
+ .unwrap();
+
+ let app: Router = router(LinkedRouterState {
+ service: service.clone(),
+ entity_access_service: Arc::new(EntityAccessServiceImpl::new(PgAccessRepository::new(
+ pool.clone(),
+ ))),
+ authorization_state: MacroAuthorizationState::new(Arc::new(Credentials)),
+ });
+ let group = binding.id;
+ let generation = service
+ .account(&person(ALICE))
+ .await
+ .unwrap()
+ .unwrap()
+ .authorization_generation;
+
+ // A viewer reads one message; its route sits next to POST
+ // /messages/attachments without conflicting.
+ let viewer = |path: String| {
+ Request::get(path)
+ .header(header::AUTHORIZATION, format!("Bearer {BOB_SESSION}"))
+ .body(Body::empty())
+ .unwrap()
+ };
+ let page = app
+ .clone()
+ .oneshot(viewer(format!("/whatsapp-groups/{group}/messages")))
+ .await
+ .unwrap();
+ assert_eq!(page.status(), StatusCode::OK);
+ let page: serde_json::Value = serde_json::from_slice(
+ &axum::body::to_bytes(page.into_body(), 1 << 20)
+ .await
+ .unwrap(),
+ )
+ .unwrap();
+ let message = page["messages"][0]["id"].as_str().unwrap().to_owned();
+ let one = app
+ .clone()
+ .oneshot(viewer(format!(
+ "/whatsapp-groups/{group}/messages/{message}"
+ )))
+ .await
+ .unwrap();
+ assert_eq!(one.status(), StatusCode::OK);
+ let one: serde_json::Value = serde_json::from_slice(
+ &axum::body::to_bytes(one.into_body(), 1 << 20)
+ .await
+ .unwrap(),
+ )
+ .unwrap();
+ assert_eq!(
+ (one["id"].as_str(), one["body"].as_str()),
+ (Some(message.as_str()), Some("hello"))
+ );
+
+ let reply = || {
+ Body::from(
+ serde_json::json!({
+ "idempotencyKey": Uuid::now_v7(),
+ "message": { "type": "text", "text": "On it", "mentions": [] }
+ })
+ .to_string(),
+ )
+ };
+ use Principal::*;
+ use StatusCode as S;
+ // (principal, method, path, body, expected). Detach and disconnect change
+ // state, so the owner's session runs them last.
+ let sends = format!("/whatsapp-groups/{group}/sends");
+ let attachments = format!("/whatsapp-groups/{group}/attachments");
+ let pairing_path = format!("/pairing/{}", pairing.id);
+ let permissions = format!("/whatsapp-groups/{group}/permissions");
+ let detach = format!("/whatsapp-groups/{group}");
+ let mut outcomes = vec![];
+ for (principal, method, path, expected) in [
+ (Session, Method::POST, sends.as_str(), S::OK),
+ (ApiJwt, Method::POST, &sends, S::OK),
+ (ApiKey, Method::POST, &sends, S::OK),
+ (Bot, Method::POST, &sends, S::FORBIDDEN),
+ (Harness, Method::POST, &sends, S::FORBIDDEN),
+ (Session, Method::POST, &attachments, S::OK),
+ (ApiJwt, Method::POST, &attachments, S::OK),
+ (ApiKey, Method::POST, &attachments, S::OK),
+ (Bot, Method::POST, &attachments, S::FORBIDDEN),
+ (Harness, Method::POST, &attachments, S::FORBIDDEN),
+ // Already connected: the session reaches the domain, which refuses a
+ // second pairing without `replace`.
+ (Session, Method::POST, "/connect", S::CONFLICT),
+ (ApiJwt, Method::POST, "/connect", S::FORBIDDEN),
+ (ApiKey, Method::POST, "/connect", S::FORBIDDEN),
+ (Bot, Method::POST, "/connect", S::FORBIDDEN),
+ (Harness, Method::POST, "/connect", S::FORBIDDEN),
+ (Session, Method::GET, &pairing_path, S::OK),
+ (ApiJwt, Method::GET, &pairing_path, S::FORBIDDEN),
+ (ApiKey, Method::GET, &pairing_path, S::FORBIDDEN),
+ (Bot, Method::GET, &pairing_path, S::FORBIDDEN),
+ (Harness, Method::GET, &pairing_path, S::FORBIDDEN),
+ (Session, Method::POST, "/groups/adopt", S::OK),
+ (ApiJwt, Method::POST, "/groups/adopt", S::FORBIDDEN),
+ (ApiKey, Method::POST, "/groups/adopt", S::FORBIDDEN),
+ (Bot, Method::POST, "/groups/adopt", S::FORBIDDEN),
+ (Harness, Method::POST, "/groups/adopt", S::FORBIDDEN),
+ (Session, Method::PATCH, &permissions, S::NO_CONTENT),
+ (ApiJwt, Method::PATCH, &permissions, S::FORBIDDEN),
+ (ApiKey, Method::PATCH, &permissions, S::FORBIDDEN),
+ (Bot, Method::PATCH, &permissions, S::FORBIDDEN),
+ (Harness, Method::PATCH, &permissions, S::FORBIDDEN),
+ (ApiJwt, Method::DELETE, &detach, S::FORBIDDEN),
+ (ApiKey, Method::DELETE, &detach, S::FORBIDDEN),
+ (Bot, Method::DELETE, &detach, S::FORBIDDEN),
+ (Harness, Method::DELETE, &detach, S::FORBIDDEN),
+ (Session, Method::DELETE, &detach, S::NO_CONTENT),
+ (ApiJwt, Method::POST, "/disconnect", S::FORBIDDEN),
+ (ApiKey, Method::POST, "/disconnect", S::FORBIDDEN),
+ (Bot, Method::POST, "/disconnect", S::FORBIDDEN),
+ (Harness, Method::POST, "/disconnect", S::FORBIDDEN),
+ (Session, Method::POST, "/disconnect", S::OK),
+ ] {
+ let (content_type, body) = match path {
+ path if path == sends => ("application/json".to_owned(), reply()),
+ path if path == attachments => upload_body(),
+ "/connect" => (
+ "application/json".to_owned(),
+ Body::from(r#"{"replace":false}"#),
+ ),
+ "/groups/adopt" => (
+ "application/json".to_owned(),
+ Body::from(serde_json::json!({ "groupJid": GROUP }).to_string()),
+ ),
+ path if path == permissions => ("application/json".to_owned(), Body::from("{}")),
+ "/disconnect" => (
+ "application/json".to_owned(),
+ Body::from(
+ serde_json::json!({ "authorizationGeneration": generation }).to_string(),
+ ),
+ ),
+ _ => ("application/json".to_owned(), Body::empty()),
+ };
+ let mut request = request(principal, method.clone(), path, body);
+ request
+ .headers_mut()
+ .insert(header::CONTENT_TYPE, content_type.parse().unwrap());
+ let status = app.clone().oneshot(request).await.unwrap().status();
+ outcomes.push((principal, method, path.to_owned(), status, expected));
+ }
+ let mismatches: Vec<_> = outcomes
+ .iter()
+ .filter(|(_, _, _, status, expected)| status != expected)
+ .collect();
+ assert!(mismatches.is_empty(), "{mismatches:#?}");
+}
diff --git a/crates/whatsapp_linked/src/lib.rs b/crates/whatsapp_linked/src/lib.rs
index 3b48b6d2f6..6234f17529 100644
--- a/crates/whatsapp_linked/src/lib.rs
+++ b/crates/whatsapp_linked/src/lib.rs
@@ -1,6 +1,6 @@
#![deny(missing_docs)]
-//! Personal WhatsApp accounts linked as devices: pairing, group adoption into
-//! group entitys, inbound ingestion and deliberate sends. DSS serves the HTTP
+//! Personal WhatsApp accounts linked as devices: pairing, adding chats as
+//! independently shared entities, inbound ingestion and deliberate sends. DSS serves the HTTP
//! API; the WhatsApp session service calls [`domain::session::SessionService`]
//! in-process. The two coordinate only through Postgres rows and `NOTIFY`.
@@ -12,3 +12,5 @@ pub mod inbound;
/// Postgres adapters.
#[cfg(feature = "outbound")]
pub mod outbound;
+/// `NOTIFY` channels and payloads shared by DSS and the session service.
+pub mod signals;
diff --git a/crates/whatsapp_linked/src/outbound.rs b/crates/whatsapp_linked/src/outbound.rs
index dc75b884e6..1ed4174965 100644
--- a/crates/whatsapp_linked/src/outbound.rs
+++ b/crates/whatsapp_linked/src/outbound.rs
@@ -1,6 +1,2 @@
-/// Native authorization adapter.
-pub mod access;
-/// Postgres repositories and session signals.
+/// Postgres repositories.
pub mod pg;
-/// Trace context across `NOTIFY` and send rows.
-pub mod trace_context;
diff --git a/crates/whatsapp_linked/src/outbound/access.rs b/crates/whatsapp_linked/src/outbound/access.rs
deleted file mode 100644
index 822ea2130e..0000000000
--- a/crates/whatsapp_linked/src/outbound/access.rs
+++ /dev/null
@@ -1,58 +0,0 @@
-//! Native authorization through the entity access service.
-
-use crate::domain::{
- models::LinkedError,
- ports::{Authorizer, LinkedResult},
-};
-use async_trait::async_trait;
-use entity_access::domain::{
- models::{AccessError, EntityType, OwnerAccessLevel, RequiredPermission},
- ports::EntityAccessService,
-};
-use macro_user_id::user_id::MacroUserIdStr;
-use std::sync::Arc;
-use uuid::Uuid;
-
-/// Mints the receipts the linked use cases require.
-pub struct EntityAccessAuthorizer<E> {
- access: Arc<E>,
-}
-
-impl<E> EntityAccessAuthorizer<E> {
- /// Wrap the hosting service's entity access service.
- pub fn new(access: Arc<E>) -> Self {
- Self { access }
- }
-}
-
-impl<E: EntityAccessService> EntityAccessAuthorizer<E> {
- async fn require<T: RequiredPermission>(
- &self,
- user: &str,
- entity: Uuid,
- entity_type: EntityType,
- ) -> LinkedResult<()> {
- let user = MacroUserIdStr::try_from(user.to_owned()).map_err(|_| LinkedError::Forbidden)?;
- self.access
- .generate_entity_access_receipt::<T>(&user.0, None, &entity.to_string(), entity_type)
- .await
- .map(|_| ())
- .map_err(|error| match error {
- AccessError::Unavailable(_) | AccessError::Internal(_) => {
- rootcause::Report::new(error).context(LinkedError::Unavailable)
- }
- AccessError::Unauthorized
- | AccessError::UnauthorizedWithMessage(_)
- | AccessError::BadRequest(_)
- | AccessError::NotFound(_) => LinkedError::Forbidden.into(),
- })
- }
-}
-
-#[async_trait]
-impl<E: EntityAccessService> Authorizer for EntityAccessAuthorizer<E> {
- async fn require_group_owner(&self, group_id: Uuid, user: &str) -> LinkedResult<()> {
- self.require::<OwnerAccessLevel>(user, group_id, EntityType::WhatsAppGroup)
- .await
- }
-}
diff --git a/crates/whatsapp_linked/src/outbound/pg.rs b/crates/whatsapp_linked/src/outbound/pg.rs
index 1494242b98..2dc21363f4 100644
--- a/crates/whatsapp_linked/src/outbound/pg.rs
+++ b/crates/whatsapp_linked/src/outbound/pg.rs
@@ -18,83 +18,7 @@ mod session;
mod test;
mod timeline;
-/// Signals between DSS and the session service. Each payload is a JSON
-/// [`signals::Signal`] (or [`signals::ChangeSignal`] for `whatsapp_changed`)
-/// carrying the sender's `traceparent`, so the receiver joins its trace.
-pub mod signals {
- use serde::{Deserialize, Serialize};
- use uuid::Uuid;
-
- /// `<pairing_id>`: start, update or stop pairing.
- pub const PAIRING_REQUESTED: &str = "whatsapp_pairing_requested";
- /// `<account_id>`: claim pending sends.
- pub const SEND_REQUESTED: &str = "whatsapp_send_requested";
- /// `<account_id>`: re-read the account's groups.
- pub const GROUPS_REQUESTED: &str = "whatsapp_groups_requested";
- /// `<account_id>`: consent or adopted groups changed; re-read the account.
- pub const ACCOUNT_CHANGED: &str = "whatsapp_account_changed";
- /// `<account_id>`: a replica released the account (session service only).
- pub const ACCOUNT_RELEASED: &str = "whatsapp_account_released";
- /// `<document_id>`: attachment bytes are ready to import (DSS listens).
- pub const MEDIA_READY: &str = "whatsapp_media_ready";
- /// `<message_id>`: a standalone message notification is ready (DSS listens).
- pub const GROUP_EFFECTS: &str = "whatsapp_group_effects";
- /// A [`ChangeSignal`]: something a page shows changed (DSS listens and
- /// pushes `whatsapp_changed` to the people who see it).
- pub const CHANGED: &str = "whatsapp_changed";
-
- /// Payload of every signal except [`CHANGED`].
- #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
- pub struct Signal {
- /// The id the channel documents.
- pub id: Uuid,
- /// The sender's W3C trace context.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub traceparent: Option<String>,
- }
-
- impl Signal {
- /// Read a payload; `None` when malformed.
- pub fn parse(payload: &str) -> Option<Self> {
- serde_json::from_str(payload).ok()
- }
- }
-
- /// What changed.
- #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
- #[serde(tag = "scope", rename_all = "snake_case")]
- pub enum Change {
- /// The account's own group list (roster) changed: its owner's add list.
- Groups {
- /// Account whose roster changed.
- account_id: Uuid,
- },
- /// A group entity's details, timeline or sends changed: everyone who
- /// can view it.
- Group {
- /// Group entity.
- group_id: Uuid,
- },
- }
-
- /// Payload of [`CHANGED`].
- #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
- pub struct ChangeSignal {
- /// What changed.
- #[serde(flatten)]
- pub change: Change,
- /// The sender's W3C trace context.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub traceparent: Option<String>,
- }
-
- impl ChangeSignal {
- /// Read a payload; `None` when malformed.
- pub fn parse(payload: &str) -> Option<Self> {
- serde_json::from_str(payload).ok()
- }
- }
-}
+use crate::signals;
/// Repository over MacroDB.
#[derive(Clone)]
@@ -121,13 +45,19 @@ pub(crate) fn helper_failure(error: impl std::fmt::Display) -> rootcause::Report
rootcause::report!("{error:#}").context(LinkedError::Unavailable)
}
+/// Stored data that breaks an invariant this crate maintains.
+pub(crate) fn corrupt(what: impl std::fmt::Display) -> rootcause::Report<LinkedError> {
+ rootcause::report!("stored WhatsApp data is invalid: {what}").context(LinkedError::Internal)
+}
+
/// Decode a JSON column written by this crate.
pub(crate) fn decode<T: serde::de::DeserializeOwned>(value: serde_json::Value) -> LinkedResult<T> {
- serde_json::from_value(value).map_err(failure)
+ serde_json::from_value(value)
+ .map_err(|error| rootcause::Report::new(error).context(LinkedError::Internal))
}
pub(crate) fn account_state(value: &str) -> LinkedResult<AccountState> {
- AccountState::parse(value).ok_or_else(|| LinkedError::Unavailable.into())
+ AccountState::parse(value).ok_or_else(|| corrupt(format_args!("account state {value:?}")))
}
/// Signal `channel` when the transaction commits, carrying the current trace.
@@ -138,7 +68,7 @@ pub(crate) async fn notify(
) -> LinkedResult<()> {
let payload = serde_json::to_string(&signals::Signal {
id,
- traceparent: super::trace_context::current(),
+ traceparent: signals::trace_context::current(),
})
.map_err(failure)?;
sqlx::query!("SELECT pg_notify($1, $2)", channel, payload)
@@ -155,7 +85,7 @@ pub(crate) async fn notify_change(
) -> LinkedResult<()> {
let payload = serde_json::to_string(&signals::ChangeSignal {
change,
- traceparent: super::trace_context::current(),
+ traceparent: signals::trace_context::current(),
})
.map_err(failure)?;
sqlx::query!("SELECT pg_notify($1, $2)", signals::CHANGED, payload)
@@ -272,5 +202,18 @@ pub(crate) async fn end_consent_in(
.execute(&mut **tx)
.await
.map_err(failure)?;
+ // The chat list and rosters were this consent's view of WhatsApp; a
+ // relink (perhaps with another number) starts from its own history sync.
+ sqlx::query!("DELETE FROM whatsapp_chat WHERE account_id = $1", account)
+ .execute(&mut **tx)
+ .await
+ .map_err(failure)?;
+ sqlx::query!(
+ "DELETE FROM whatsapp_group_roster WHERE account_id = $1",
+ account
+ )
+ .execute(&mut **tx)
+ .await
+ .map_err(failure)?;
Ok(())
}
diff --git a/crates/whatsapp_linked/src/outbound/pg/accounts.rs b/crates/whatsapp_linked/src/outbound/pg/accounts.rs
index 36b89dbf75..7f773f6c51 100644
--- a/crates/whatsapp_linked/src/outbound/pg/accounts.rs
+++ b/crates/whatsapp_linked/src/outbound/pg/accounts.rs
@@ -4,6 +4,7 @@ use super::*;
use crate::domain::ports::AccountRepository;
use async_trait::async_trait;
use chrono::{DateTime, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
/// Pairing transactions last this long.
const PAIRING_SECONDS: f64 = 5.0 * 60.0;
@@ -92,18 +93,25 @@ fn pairing(row: PairingRow) -> LinkedResult<Pairing> {
Ok(Pairing {
id: row.id,
account_id: row.account_id,
- state: PairingState::parse(&row.state).ok_or(LinkedError::Unavailable)?,
+ state: PairingState::parse(&row.state)
+ .ok_or_else(|| corrupt(format_args!("state {:?}", row.state)))?,
expires_at: row.expires_at,
})
}
#[async_trait]
impl AccountRepository for PgLinkedRepository {
- async fn owned_account(&self, user: &str) -> LinkedResult<Option<Account>> {
+ async fn owned_account(&self, user: &MacroUserIdStr<'_>) -> LinkedResult<Option<Account>> {
+ let user = user.as_ref();
account_by_user_in(&self.pool, user).await
}
- async fn begin_pairing(&self, user: &str, replace: bool) -> LinkedResult<Pairing> {
+ async fn begin_pairing(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ replace: bool,
+ ) -> LinkedResult<Pairing> {
+ let user = user.as_ref();
let mut tx = self.pool.begin().await.map_err(failure)?;
// Serialize per person, including before their account row exists.
sqlx::query!(
@@ -194,7 +202,8 @@ impl AccountRepository for PgLinkedRepository {
pairing(row)
}
- async fn pair_state(&self, user: &str, id: Uuid) -> LinkedResult<PairState> {
+ async fn pair_state(&self, user: &MacroUserIdStr<'_>, id: Uuid) -> LinkedResult<PairState> {
+ let user = user.as_ref();
let mut tx = self.pool.begin().await.map_err(failure)?;
expire_pairings_in(&mut tx, Some(user), Some(id), None).await?;
let row = sqlx::query!(
@@ -209,7 +218,8 @@ impl AccountRepository for PgLinkedRepository {
.map_err(failure)?
.ok_or(LinkedError::NotFound)?;
tx.commit().await.map_err(failure)?;
- let state = PairingState::parse(&row.state).ok_or(LinkedError::Unavailable)?;
+ let state = PairingState::parse(&row.state)
+ .ok_or_else(|| corrupt(format_args!("state {:?}", row.state)))?;
Ok(PairState {
state,
qr: row.qr_code,
@@ -224,10 +234,11 @@ impl AccountRepository for PgLinkedRepository {
async fn submit_passkey(
&self,
- user: &str,
+ user: &MacroUserIdStr<'_>,
id: Uuid,
response: &serde_json::Value,
) -> LinkedResult<()> {
+ let user = user.as_ref();
let mut tx = self.pool.begin().await.map_err(failure)?;
expire_pairings_in(&mut tx, Some(user), Some(id), None).await?;
sqlx::query!(
@@ -248,7 +259,8 @@ impl AccountRepository for PgLinkedRepository {
tx.commit().await.map_err(failure)
}
- async fn cancel_pairing(&self, user: &str, id: Uuid) -> LinkedResult<()> {
+ async fn cancel_pairing(&self, user: &MacroUserIdStr<'_>, id: Uuid) -> LinkedResult<()> {
+ let user = user.as_ref();
let mut tx = self.pool.begin().await.map_err(failure)?;
sqlx::query!(
"SELECT id FROM whatsapp_linked_account WHERE user_id = $1 FOR UPDATE",
@@ -294,7 +306,8 @@ impl AccountRepository for PgLinkedRepository {
tx.commit().await.map_err(failure)
}
- async fn disconnect(&self, user: &str, generation: i64) -> LinkedResult<bool> {
+ async fn disconnect(&self, user: &MacroUserIdStr<'_>, generation: i64) -> LinkedResult<bool> {
+ let user = user.as_ref();
let mut tx = self.pool.begin().await.map_err(failure)?;
let account = sqlx::query!(
"SELECT id, state, generation FROM whatsapp_linked_account WHERE user_id = $1 FOR UPDATE",
diff --git a/crates/whatsapp_linked/src/outbound/pg/bindings.rs b/crates/whatsapp_linked/src/outbound/pg/bindings.rs
index 943b7950ba..163c952ad8 100644
--- a/crates/whatsapp_linked/src/outbound/pg/bindings.rs
+++ b/crates/whatsapp_linked/src/outbound/pg/bindings.rs
@@ -18,12 +18,13 @@ pub(super) fn binding(row: BindingRow) -> LinkedResult<Binding> {
Ok(Binding {
id: row.id,
group_jid: row.group_jid,
- kind: ChatKind::parse(&row.kind).ok_or(LinkedError::Unavailable)?,
+ kind: ChatKind::parse(&row.kind)
+ .ok_or_else(|| corrupt(format_args!("kind {:?}", row.kind)))?,
user_id: row.user_id,
state: match row.state.as_str() {
"active" => BindingState::Active,
"detached" => BindingState::Detached,
- _ => return Err(LinkedError::Unavailable.into()),
+ other => return Err(corrupt(format_args!("binding state {other:?}"))),
},
adopted_at: row.adopted_at,
})
@@ -41,6 +42,7 @@ impl BindingRepository for PgLinkedRepository {
account,
adoption,
} = record;
+ let user = user.as_ref();
account
.identity_jid
.as_deref()
@@ -69,7 +71,17 @@ impl BindingRepository for PgLinkedRepository {
share_permission_db_utils::insert_private_permission(&mut *tx, &permission)
.await
.map_err(failure)?;
- let row = sqlx::query_as!(BindingRow,"INSERT INTO whatsapp_group (id, group_jid, kind, name, user_id, state, share_permission_id, backfill_state) VALUES ($1,$2,$3,$4,$5,'active',$6,'pending') RETURNING id, group_jid, kind, user_id, state, adopted_at",id,adoption.jid,adoption.kind.as_str(),adoption.name,user,permission)
+ // Importing starts from a message of the chat; with none known yet
+ // it waits for the first one.
+ let row = sqlx::query_as!(BindingRow,r#"INSERT INTO whatsapp_group (id, group_jid, kind, name, user_id, state, share_permission_id, backfill_state)
+ VALUES ($1,$2,$3,$4,$5,'active',$6,
+ CASE WHEN EXISTS (SELECT 1 FROM whatsapp_chat WHERE account_id = $7 AND chat_jid = $2 AND anchor IS NOT NULL)
+ OR EXISTS (SELECT 1 FROM whatsapp_group_message m JOIN whatsapp_group g ON g.id = m.binding_id
+ WHERE g.group_jid = $2 AND m.kind = 'message' AND m.message_id IS NOT NULL
+ AND EXISTS (SELECT 1 FROM whatsapp_message_observation o WHERE o.binding_id = m.binding_id
+ AND o.person_id = m.person_id AND o.source_id = m.source_id AND o.account_id = $7))
+ THEN 'pending' ELSE 'waiting_for_message' END)
+ RETURNING id, group_jid, kind, user_id, state, adopted_at"#,id,adoption.jid,adoption.kind.as_str(),adoption.name,user,permission,account.id)
.fetch_one(&mut *tx).await.map_err(failure)?;
let owner = Owner::from_principal_str(user).map_err(failure)?;
entity_registry_db_utils::insert_entity(
diff --git a/crates/whatsapp_linked/src/outbound/pg/chats.rs b/crates/whatsapp_linked/src/outbound/pg/chats.rs
index 430e60bc5b..d1ad6e0132 100644
--- a/crates/whatsapp_linked/src/outbound/pg/chats.rs
+++ b/crates/whatsapp_linked/src/outbound/pg/chats.rs
@@ -6,101 +6,165 @@ use crate::domain::events::{BackfillWork, ChatUpdate, HistoryPage, MessageAnchor
use crate::domain::ports::StoredChat;
use chrono::{Duration, Utc};
-/// Upsert chat-list rows; signal the owner's list once if any row changed.
+/// Several updates of one chat in a batch, as one.
+fn merge(into: &mut ChatUpdate, update: &ChatUpdate) {
+ if !into.create && update.create {
+ into.kind = update.kind;
+ }
+ into.create |= update.create;
+ into.name = update.name.clone().or(into.name.take());
+ into.last_activity_at = into.last_activity_at.max(update.last_activity_at);
+ into.archived = update.archived.or(into.archived);
+ into.pinned = update.pinned.or(into.pinned);
+ if update
+ .anchor
+ .as_ref()
+ .is_some_and(|anchor| into.anchor.as_ref().is_none_or(|kept| kept.at <= anchor.at))
+ {
+ into.anchor = update.anchor.clone();
+ }
+}
+
+/// Upsert chat-list rows in a few statements for the whole batch; signal the
+/// owner's list once if any row changed. A message for an added chat that was
+/// waiting for one makes it `pending`; returns whether that happened.
pub(super) async fn update_chats_in(
tx: &mut Transaction<'_, Postgres>,
account: &Fenced,
chats: &[ChatUpdate],
-) -> LinkedResult<()> {
- let mut changed = false;
+) -> LinkedResult<bool> {
+ let mut merged: std::collections::BTreeMap<String, ChatUpdate> = Default::default();
for chat in chats {
- let anchor = chat
- .anchor
- .as_ref()
- .map(serde_json::to_value)
- .transpose()
- .map_err(failure)?;
- let name = chat
+ let mut chat = chat.clone();
+ chat.name = chat
.name
.as_deref()
.map(str::trim)
.filter(|name| !name.is_empty())
.map(|name| name.chars().take(256).collect::<String>());
- let rows = if chat.create {
- sqlx::query!(
- r#"INSERT INTO whatsapp_chat AS c (account_id, chat_jid, kind, name, last_activity_at, archived, pinned, anchor)
- VALUES ($1, $2, $3, $4, $5, COALESCE($6, false), COALESCE($7, false), $8)
- ON CONFLICT (account_id, chat_jid) DO UPDATE SET
- name = COALESCE(excluded.name, c.name),
- last_activity_at = GREATEST(c.last_activity_at, excluded.last_activity_at),
- archived = COALESCE($6, c.archived),
- pinned = COALESCE($7, c.pinned),
- anchor = CASE WHEN excluded.anchor IS NOT NULL AND (c.anchor IS NULL
- OR (excluded.anchor->>'at')::timestamptz >= (c.anchor->>'at')::timestamptz)
- THEN excluded.anchor ELSE c.anchor END,
- updated_at = now()
- WHERE c.name IS DISTINCT FROM COALESCE(excluded.name, c.name)
- OR c.last_activity_at IS DISTINCT FROM GREATEST(c.last_activity_at, excluded.last_activity_at)
- OR c.archived IS DISTINCT FROM COALESCE($6, c.archived)
- OR c.pinned IS DISTINCT FROM COALESCE($7, c.pinned)
- OR (excluded.anchor IS NOT NULL AND c.anchor IS DISTINCT FROM excluded.anchor AND (c.anchor IS NULL
- OR (excluded.anchor->>'at')::timestamptz >= (c.anchor->>'at')::timestamptz))"#,
- account.id,
- chat.jid,
- chat.kind.as_str(),
- name,
- chat.last_activity_at,
- chat.archived,
- chat.pinned,
- anchor
- )
- .execute(&mut **tx)
- .await
- } else {
- sqlx::query!(
- r#"UPDATE whatsapp_chat c SET
- name = COALESCE($3, c.name),
- last_activity_at = GREATEST(c.last_activity_at, $4),
- archived = COALESCE($5, c.archived),
- pinned = COALESCE($6, c.pinned),
- updated_at = now()
- WHERE c.account_id = $1 AND c.chat_jid = $2
- AND (c.name IS DISTINCT FROM COALESCE($3, c.name)
- OR c.last_activity_at IS DISTINCT FROM GREATEST(c.last_activity_at, $4)
- OR c.archived IS DISTINCT FROM COALESCE($5, c.archived)
- OR c.pinned IS DISTINCT FROM COALESCE($6, c.pinned))"#,
- account.id,
- chat.jid,
- name,
- chat.last_activity_at,
- chat.archived,
- chat.pinned
- )
- .execute(&mut **tx)
- .await
- }
- .map_err(failure)?;
- changed |= rows.rows_affected() > 0;
- // The owner's added direct chat follows the person's name.
- if chat.kind == ChatKind::Direct
- && let Some(name) = &name
- {
- let renamed = sqlx::query_scalar!(
- r#"UPDATE whatsapp_group SET name = $3
- WHERE user_id = $1 AND group_jid = $2 AND kind = 'direct' AND state = 'active' AND name <> $3
- RETURNING id"#,
- account.user_id,
- chat.jid,
- name
- )
- .fetch_all(&mut **tx)
- .await
- .map_err(failure)?;
- for group_id in renamed {
- notify_change(tx, signals::Change::Group { group_id }).await?;
+ match merged.get_mut(&chat.jid) {
+ Some(kept) => merge(kept, &chat),
+ None => {
+ merged.insert(chat.jid.clone(), chat);
}
}
}
+ let (created, updated): (Vec<&ChatUpdate>, Vec<&ChatUpdate>) =
+ merged.values().partition(|chat| chat.create);
+ let anchors = created
+ .iter()
+ .map(|chat| chat.anchor.as_ref().map(serde_json::to_value).transpose())
+ .collect::<Result<Vec<_>, _>>()
+ .map_err(failure)?;
+ let inserted = sqlx::query!(
+ r#"WITH input AS (
+ SELECT * FROM UNNEST($2::text[], $3::text[], $4::text[], $5::timestamptz[], $6::bool[], $7::bool[], $8::jsonb[])
+ AS i(chat_jid, kind, name, last_activity_at, archived, pinned, anchor))
+ INSERT INTO whatsapp_chat AS c (account_id, chat_jid, kind, name, last_activity_at, archived, pinned, anchor)
+ SELECT $1, i.chat_jid, i.kind, i.name, i.last_activity_at, COALESCE(i.archived, false), COALESCE(i.pinned, false), i.anchor
+ FROM input i
+ ON CONFLICT (account_id, chat_jid) DO UPDATE SET
+ name = COALESCE(excluded.name, c.name),
+ last_activity_at = GREATEST(c.last_activity_at, excluded.last_activity_at),
+ archived = COALESCE((SELECT i.archived FROM input i WHERE i.chat_jid = excluded.chat_jid), c.archived),
+ pinned = COALESCE((SELECT i.pinned FROM input i WHERE i.chat_jid = excluded.chat_jid), c.pinned),
+ anchor = CASE WHEN excluded.anchor IS NOT NULL AND (c.anchor IS NULL
+ OR (excluded.anchor->>'at')::timestamptz >= (c.anchor->>'at')::timestamptz)
+ THEN excluded.anchor ELSE c.anchor END,
+ updated_at = now()
+ WHERE c.name IS DISTINCT FROM COALESCE(excluded.name, c.name)
+ OR c.last_activity_at IS DISTINCT FROM GREATEST(c.last_activity_at, excluded.last_activity_at)
+ OR c.archived IS DISTINCT FROM COALESCE((SELECT i.archived FROM input i WHERE i.chat_jid = excluded.chat_jid), c.archived)
+ OR c.pinned IS DISTINCT FROM COALESCE((SELECT i.pinned FROM input i WHERE i.chat_jid = excluded.chat_jid), c.pinned)
+ OR (excluded.anchor IS NOT NULL AND c.anchor IS DISTINCT FROM excluded.anchor AND (c.anchor IS NULL
+ OR (excluded.anchor->>'at')::timestamptz >= (c.anchor->>'at')::timestamptz))"#,
+ account.id,
+ &created.iter().map(|chat| chat.jid.clone()).collect::<Vec<_>>(),
+ &created.iter().map(|chat| chat.kind.as_str().to_owned()).collect::<Vec<_>>(),
+ &created.iter().map(|chat| chat.name.clone()).collect::<Vec<_>>() as &[Option<String>],
+ &created.iter().map(|chat| chat.last_activity_at).collect::<Vec<_>>() as &[Option<chrono::DateTime<Utc>>],
+ &created.iter().map(|chat| chat.archived).collect::<Vec<_>>() as &[Option<bool>],
+ &created.iter().map(|chat| chat.pinned).collect::<Vec<_>>() as &[Option<bool>],
+ &anchors as &[Option<serde_json::Value>],
+ )
+ .execute(&mut **tx)
+ .await
+ .map_err(failure)?
+ .rows_affected();
+ let renamed_rows = sqlx::query!(
+ r#"UPDATE whatsapp_chat c SET
+ name = COALESCE(i.name, c.name),
+ last_activity_at = GREATEST(c.last_activity_at, i.last_activity_at),
+ archived = COALESCE(i.archived, c.archived),
+ pinned = COALESCE(i.pinned, c.pinned),
+ updated_at = now()
+ FROM UNNEST($2::text[], $3::text[], $4::timestamptz[], $5::bool[], $6::bool[])
+ AS i(chat_jid, name, last_activity_at, archived, pinned)
+ WHERE c.account_id = $1 AND c.chat_jid = i.chat_jid
+ AND (c.name IS DISTINCT FROM COALESCE(i.name, c.name)
+ OR c.last_activity_at IS DISTINCT FROM GREATEST(c.last_activity_at, i.last_activity_at)
+ OR c.archived IS DISTINCT FROM COALESCE(i.archived, c.archived)
+ OR c.pinned IS DISTINCT FROM COALESCE(i.pinned, c.pinned))"#,
+ account.id,
+ &updated
+ .iter()
+ .map(|chat| chat.jid.clone())
+ .collect::<Vec<_>>(),
+ &updated
+ .iter()
+ .map(|chat| chat.name.clone())
+ .collect::<Vec<_>>() as &[Option<String>],
+ &updated
+ .iter()
+ .map(|chat| chat.last_activity_at)
+ .collect::<Vec<_>>() as &[Option<chrono::DateTime<Utc>>],
+ &updated.iter().map(|chat| chat.archived).collect::<Vec<_>>() as &[Option<bool>],
+ &updated.iter().map(|chat| chat.pinned).collect::<Vec<_>>() as &[Option<bool>],
+ )
+ .execute(&mut **tx)
+ .await
+ .map_err(failure)?
+ .rows_affected();
+ let changed = inserted + renamed_rows > 0;
+ let anchored_jids: Vec<String> = merged
+ .values()
+ .filter(|chat| chat.anchor.is_some())
+ .map(|chat| chat.jid.clone())
+ .collect();
+ let ready = sqlx::query_scalar!(
+ r#"UPDATE whatsapp_group SET backfill_state = 'pending'
+ WHERE user_id = $1 AND group_jid = ANY($2) AND state = 'active'
+ AND backfill_state = 'waiting_for_message'
+ RETURNING id"#,
+ account.user_id,
+ &anchored_jids
+ )
+ .fetch_all(&mut **tx)
+ .await
+ .map_err(failure)?;
+ let anchored = !ready.is_empty();
+ // The owner's added direct chats follow the person's name.
+ let named: Vec<(String, String)> = merged
+ .values()
+ .filter(|chat| chat.kind == ChatKind::Direct)
+ .filter_map(|chat| Some((chat.jid.clone(), chat.name.clone()?)))
+ .collect();
+ let renamed = sqlx::query_scalar!(
+ r#"UPDATE whatsapp_group g SET name = i.name
+ FROM UNNEST($2::text[], $3::text[]) AS i(group_jid, name)
+ WHERE g.user_id = $1 AND g.group_jid = i.group_jid AND g.kind = 'direct' AND g.state = 'active'
+ AND g.name <> i.name
+ RETURNING g.id"#,
+ account.user_id,
+ &named.iter().map(|(jid, _)| jid.clone()).collect::<Vec<_>>(),
+ &named.iter().map(|(_, name)| name.clone()).collect::<Vec<_>>(),
+ )
+ .fetch_all(&mut **tx)
+ .await
+ .map_err(failure)?;
+ for group_id in ready.into_iter().chain(renamed) {
+ notify_change(tx, signals::Change::Group { group_id }).await?;
+ }
if changed {
notify_change(
tx,
@@ -110,7 +174,7 @@ pub(super) async fn update_chats_in(
)
.await?;
}
- Ok(())
+ Ok(anchored)
}
pub(super) async fn account_chats(pool: &PgPool, account: Uuid) -> LinkedResult<Vec<StoredChat>> {
@@ -125,7 +189,8 @@ pub(super) async fn account_chats(pool: &PgPool, account: Uuid) -> LinkedResult<
.into_iter()
.map(|row| {
Ok(StoredChat {
- kind: ChatKind::parse(&row.kind).ok_or(LinkedError::Unavailable)?,
+ kind: ChatKind::parse(&row.kind)
+ .ok_or_else(|| corrupt(format_args!("kind {:?}", row.kind)))?,
jid: row.chat_jid,
name: row.name,
last_activity_at: row.last_activity_at,
@@ -137,23 +202,44 @@ pub(super) async fn account_chats(pool: &PgPool, account: Uuid) -> LinkedResult<
}
fn backfill_state(value: &str) -> LinkedResult<BackfillState> {
- BackfillState::parse(value).ok_or_else(|| LinkedError::Unavailable.into())
+ BackfillState::parse(value).ok_or_else(|| corrupt(format_args!("backfill state {value:?}")))
}
pub(super) async fn backfill_work_in(
tx: &mut Transaction<'_, Postgres>,
account: &Fenced,
) -> LinkedResult<Vec<BackfillWork>> {
+ // The anchor is the chat list's newest message, else the newest message
+ // of the chat stored in Macro that this account saw (in this group, or in
+ // an earlier or someone else's group for the same chat).
sqlx::query!(
r#"SELECT g.id, g.group_jid, g.backfill_state AS "state!", g.backfill_imported, g.backfill_cursor,
- g.adopted_at, g.backfill_requested_at, c.anchor AS "anchor?"
+ g.adopted_at, g.backfill_requested_at, COALESCE(c.anchor, stored.anchor) AS "anchor?"
FROM whatsapp_group g
LEFT JOIN whatsapp_chat c ON c.account_id = $1 AND c.chat_jid = g.group_jid
+ LEFT JOIN LATERAL (
+ SELECT jsonb_build_object(
+ 'id', m.source_id,
+ 'at', m.source_at,
+ 'fromMe', EXISTS (SELECT 1 FROM whatsapp_identity_alias a
+ WHERE a.binding_id = m.binding_id AND a.person_id = m.person_id AND a.jid = $3),
+ 'senderJid', (SELECT a.jid FROM whatsapp_identity_alias a
+ WHERE a.binding_id = m.binding_id AND a.person_id = m.person_id
+ ORDER BY a.jid LIKE '%@lid' DESC, a.jid LIMIT 1)) AS anchor
+ FROM whatsapp_group_message m JOIN whatsapp_group other ON other.id = m.binding_id
+ WHERE c.anchor IS NULL AND other.group_jid = g.group_jid
+ AND m.kind = 'message' AND m.message_id IS NOT NULL
+ AND (m.binding_id = g.id OR EXISTS (SELECT 1 FROM whatsapp_message_observation o
+ WHERE o.binding_id = m.binding_id AND o.person_id = m.person_id
+ AND o.source_id = m.source_id AND o.account_id = $1))
+ ORDER BY m.source_at DESC, m.id DESC LIMIT 1
+ ) stored ON true
WHERE g.user_id = $2 AND g.state = 'active'
- AND g.backfill_state IN ('pending', 'running', 'waiting_for_phone')
+ AND g.backfill_state IN ('waiting_for_message', 'pending', 'running', 'waiting_for_phone')
ORDER BY g.adopted_at, g.id LIMIT 20"#,
account.id,
- account.user_id
+ account.user_id,
+ account.identity_jid
)
.fetch_all(&mut **tx)
.await
@@ -188,7 +274,7 @@ pub(super) async fn set_backfill_in(
backfill_requested_at = CASE WHEN $4 THEN now() ELSE g.backfill_requested_at END
FROM (SELECT id, backfill_state FROM whatsapp_group WHERE id = $1 FOR UPDATE) old
WHERE g.id = old.id AND g.user_id = $2
- AND g.backfill_state IN ('pending', 'running', 'waiting_for_phone')
+ AND g.backfill_state IN ('waiting_for_message', 'pending', 'running', 'waiting_for_phone')
RETURNING old.backfill_state AS "previous!""#,
group,
account.user_id,
@@ -240,7 +326,7 @@ pub(super) async fn backfill_page_in(
let rows = sqlx::query!(
r#"SELECT id, backfill_imported, backfill_cursor, adopted_at FROM whatsapp_group
WHERE user_id = $1 AND group_jid = $2 AND state = 'active'
- AND backfill_state IN ('pending', 'running', 'waiting_for_phone')
+ AND backfill_state IN ('waiting_for_message', 'pending', 'running', 'waiting_for_phone')
ORDER BY id FOR UPDATE"#,
account.user_id,
page.chat_jid
diff --git a/crates/whatsapp_linked/src/outbound/pg/effects.rs b/crates/whatsapp_linked/src/outbound/pg/effects.rs
index 72173b642d..a75b88609a 100644
--- a/crates/whatsapp_linked/src/outbound/pg/effects.rs
+++ b/crates/whatsapp_linked/src/outbound/pg/effects.rs
@@ -32,7 +32,7 @@ impl EffectsRepository for PgLinkedRepository {
"macro" => Origin::Macro,
"history" => Origin::History,
"whatsapp" => Origin::Whatsapp,
- _ => return Err(LinkedError::Unavailable.into()),
+ other => return Err(corrupt(format_args!("message origin {other:?}"))),
},
associated_user: row.user_id,
system: row.kind == "system",
diff --git a/crates/whatsapp_linked/src/outbound/pg/groups.rs b/crates/whatsapp_linked/src/outbound/pg/groups.rs
index 7b4235bbbd..b1635c2d4e 100644
--- a/crates/whatsapp_linked/src/outbound/pg/groups.rs
+++ b/crates/whatsapp_linked/src/outbound/pg/groups.rs
@@ -4,6 +4,7 @@ use super::*;
use crate::domain::ports::{GroupRepository, StoredChat, VisibleAdoption};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
/// The same facts, ignoring when they were read and listing-only fields.
fn same_facts(stored: &GroupInfo, observed: &GroupInfo) -> bool {
@@ -354,9 +355,10 @@ impl GroupRepository for PgLinkedRepository {
async fn visible_adoptions(
&self,
- user: &str,
+ user: &MacroUserIdStr<'_>,
groups: &[String],
) -> LinkedResult<Vec<VisibleAdoption>> {
+ let user = user.as_ref();
sqlx::query_as!(
VisibleAdoption,
r#"SELECT b.group_jid, b.id, b.name, b.user_id AS owner_id
@@ -371,26 +373,6 @@ impl GroupRepository for PgLinkedRepository {
.map_err(failure)
}
- async fn binding_community(
- &self,
- binding: &Binding,
- community_jid: &str,
- ) -> LinkedResult<Option<GroupInfo>> {
- sqlx::query_scalar!(
- r#"SELECT r.metadata FROM whatsapp_group_roster r
- JOIN whatsapp_group_membership m ON m.account_id = r.account_id
- WHERE m.binding_id = $1 AND m.consent_ended_at IS NULL AND r.group_jid = $2
- ORDER BY r.observed_at DESC LIMIT 1"#,
- binding.id,
- community_jid
- )
- .fetch_optional(&self.pool)
- .await
- .map_err(failure)?
- .map(decode::<GroupInfo>)
- .transpose()
- }
-
async fn binding_roster(&self, binding: &Binding) -> LinkedResult<Option<GroupInfo>> {
let roster = sqlx::query_scalar!(
r#"SELECT r.metadata FROM whatsapp_group_roster r
diff --git a/crates/whatsapp_linked/src/outbound/pg/ingest.rs b/crates/whatsapp_linked/src/outbound/pg/ingest.rs
index ee28fba664..013339a872 100644
--- a/crates/whatsapp_linked/src/outbound/pg/ingest.rs
+++ b/crates/whatsapp_linked/src/outbound/pg/ingest.rs
@@ -38,7 +38,7 @@ pub(super) struct Reservation {
pub(super) enum Reserve {
/// Persist through this reservation.
Reserved(Box<Reservation>),
- /// Retry later: the target has not arrived or the binding needs an owner.
+ /// Retry later: the target has not arrived.
Defer,
/// The sender identity is ambiguous.
Quarantine,
@@ -106,14 +106,14 @@ pub(super) async fn reserve_in(
message: &Message,
accepted_send: Option<Uuid>,
) -> LinkedResult<Reserve> {
- let current = sqlx::query!(
+ let current = sqlx::query_scalar!(
"SELECT state FROM whatsapp_group WHERE id = $1 FOR UPDATE",
binding.id
)
.fetch_one(&mut **tx)
.await
.map_err(failure)?;
- if current.state != "active" && accepted_send.is_none() {
+ if current != "active" && accepted_send.is_none() {
return Ok(Reserve::Skip);
}
let sender = &message.sender;
@@ -609,7 +609,7 @@ async fn retain_in(
.await
.map_err(failure)?;
if retained >= MAX_RETAINED_EVENTS {
- return Err(LinkedError::Unavailable.into());
+ return Err(LinkedError::Backlogged.into());
}
let payload = serde_json::to_value(event).map_err(failure)?;
sqlx::query!(
@@ -760,6 +760,7 @@ impl PgLinkedRepository {
tracing::warn!(
event_id = %event.event_id,
code = error.current_context().code(),
+ error = %error,
"WhatsApp event deferred after a persistence failure"
);
Ok(IngestOutcome::Deferred)
@@ -812,7 +813,7 @@ impl PgLinkedRepository {
.await
.map_err(failure)?;
if retained >= MAX_RETAINED_EVENTS {
- return Err(LinkedError::Unavailable.into());
+ return Err(LinkedError::Backlogged.into());
}
let payload = serde_json::to_value(event).map_err(failure)?;
sqlx::query!(
diff --git a/crates/whatsapp_linked/src/outbound/pg/media.rs b/crates/whatsapp_linked/src/outbound/pg/media.rs
index 07def6dbc1..d148ea68cc 100644
--- a/crates/whatsapp_linked/src/outbound/pg/media.rs
+++ b/crates/whatsapp_linked/src/outbound/pg/media.rs
@@ -116,7 +116,7 @@ impl PgLinkedRepository {
sha256: row
.sha256
.try_into()
- .map_err(|_| LinkedError::Unavailable)?,
+ .map_err(|_| corrupt("sha256 is not 32 bytes"))?,
locator: row.locator,
})
})
@@ -231,7 +231,7 @@ impl MediaRepository for PgLinkedRepository {
ORDER BY retry_at LIMIT $1 FOR UPDATE SKIP LOCKED)
AND blob.document_id = a.document_id
RETURNING a.binding_id, a.person_id, a.source_id, a.ordinal, a.document_id, a.attempts,
- blob.group_id, blob.user_id, blob.filename, blob.mime, blob.sha256, blob.bytes"#,
+ blob.group_id, blob.user_id, blob.filename, blob.mime, blob.sha256"#,
limit
)
.fetch_all(&self.pool)
@@ -254,14 +254,23 @@ impl MediaRepository for PgLinkedRepository {
sha256: row
.sha256
.try_into()
- .map_err(|_| LinkedError::Unavailable)?,
- bytes: row.bytes,
+ .map_err(|_| corrupt("sha256 is not 32 bytes"))?,
attempts: row.attempts,
})
})
.collect()
}
+ async fn import_bytes(&self, import: &DocumentImport) -> LinkedResult<Option<Vec<u8>>> {
+ sqlx::query_scalar!(
+ "SELECT bytes FROM whatsapp_media_blob WHERE document_id = $1",
+ import.document_id
+ )
+ .fetch_optional(&self.pool)
+ .await
+ .map_err(failure)
+ }
+
async fn import_stored(&self, import: &DocumentImport) -> LinkedResult<()> {
let attachment = &import.attachment;
let mut tx = self.pool.begin().await.map_err(failure)?;
@@ -333,6 +342,13 @@ impl MediaRepository for PgLinkedRepository {
.await
.map_err(failure)?
.rows_affected();
- Ok(uploads + receipts)
+ let pairings = sqlx::query!(
+ "DELETE FROM whatsapp_pairing WHERE consumed_at < now() - interval '1 day'"
+ )
+ .execute(&self.pool)
+ .await
+ .map_err(failure)?
+ .rows_affected();
+ Ok(uploads + receipts + pairings)
}
}
diff --git a/crates/whatsapp_linked/src/outbound/pg/sends.rs b/crates/whatsapp_linked/src/outbound/pg/sends.rs
index 0355377e65..b3795695a0 100644
--- a/crates/whatsapp_linked/src/outbound/pg/sends.rs
+++ b/crates/whatsapp_linked/src/outbound/pg/sends.rs
@@ -5,10 +5,11 @@
use super::*;
use crate::domain::{
events::*,
- ports::{MutationTarget, SendIntent, SendRepository, SendingFacts, StagedUpload},
+ ports::{MutationTarget, SendIntent, SendRepository, StagedUpload, StoredSend},
};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
struct SendRow {
id: Uuid,
@@ -27,7 +28,8 @@ fn progress(row: SendRow) -> LinkedResult<SendProgress> {
user_id: row.user_id,
group_id: row.group_id,
payload: decode(row.payload)?,
- state: DeliveryState::parse(&row.state).ok_or(LinkedError::Unavailable)?,
+ state: DeliveryState::parse(&row.state)
+ .ok_or_else(|| corrupt(format_args!("state {:?}", row.state)))?,
message_id: row.message_id,
error_code: row.error_code,
created_at: row.created_at,
@@ -53,7 +55,7 @@ impl SendRepository for PgLinkedRepository {
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)"#,
id,
upload.group_id,
- upload.user,
+ upload.user.as_ref(),
upload.mime,
upload.filename,
&upload.sha256[..],
@@ -68,14 +70,15 @@ impl SendRepository for PgLinkedRepository {
Ok(id)
}
- async fn staged_upload(
+ async fn staged_upload_mime(
&self,
- user: &str,
+ user: &MacroUserIdStr<'_>,
group_id: Uuid,
upload: Uuid,
- ) -> LinkedResult<Option<(String, String)>> {
- Ok(sqlx::query!(
- r#"SELECT mime, filename FROM whatsapp_media_blob b
+ ) -> LinkedResult<Option<String>> {
+ let user = user.as_ref();
+ sqlx::query_scalar!(
+ r#"SELECT mime FROM whatsapp_media_blob b
WHERE document_id = $1 AND group_id = $2 AND user_id = $3
AND NOT EXISTS (SELECT 1 FROM whatsapp_group_attachment a WHERE a.document_id = b.document_id)"#,
upload,
@@ -84,19 +87,15 @@ impl SendRepository for PgLinkedRepository {
)
.fetch_optional(&self.pool)
.await
- .map_err(failure)?
- .map(|row| (row.mime, row.filename)))
+ .map_err(failure)
}
- async fn sending_facts(
+ async fn account_roster(
&self,
account: &Account,
binding: &Binding,
- ) -> LinkedResult<SendingFacts> {
- if binding.kind == ChatKind::Direct {
- return Ok(crate::domain::ports::direct_sending_facts(account, binding));
- }
- let group = sqlx::query_scalar!(
+ ) -> LinkedResult<Option<GroupInfo>> {
+ sqlx::query_scalar!(
"SELECT metadata FROM whatsapp_group_roster WHERE account_id = $1 AND group_jid = $2",
account.id,
binding.group_jid
@@ -105,10 +104,7 @@ impl SendRepository for PgLinkedRepository {
.await
.map_err(failure)?
.map(decode::<GroupInfo>)
- .transpose()?;
- Ok(crate::domain::ports::sending_facts_from_roster(
- account, group,
- ))
+ .transpose()
}
async fn mutation_target(
@@ -138,9 +134,10 @@ impl SendRepository for PgLinkedRepository {
async fn stored_send(
&self,
group_id: Uuid,
- user: &str,
+ user: &MacroUserIdStr<'_>,
idempotency_key: Uuid,
- ) -> LinkedResult<Option<([u8; 32], SendProgress)>> {
+ ) -> LinkedResult<Option<StoredSend>> {
+ let user = user.as_ref();
let Some(row) = sqlx::query!(
r#"SELECT id, user_id, group_id, payload, state, message_id, error_code, created_at, request_sha256
FROM whatsapp_send WHERE group_id = $1 AND user_id = $2 AND idempotency_key = $3"#,
@@ -157,10 +154,10 @@ impl SendRepository for PgLinkedRepository {
let digest: [u8; 32] = row
.request_sha256
.try_into()
- .map_err(|_| LinkedError::Unavailable)?;
- Ok(Some((
- digest,
- progress(SendRow {
+ .map_err(|_| corrupt("sha256 is not 32 bytes"))?;
+ Ok(Some(StoredSend {
+ request_sha256: digest,
+ progress: progress(SendRow {
id: row.id,
user_id: row.user_id,
group_id: row.group_id,
@@ -170,7 +167,7 @@ impl SendRepository for PgLinkedRepository {
error_code: row.error_code,
created_at: row.created_at,
})?,
- )))
+ }))
}
async fn enqueue(&self, intent: SendIntent<'_>) -> LinkedResult<SendProgress> {
@@ -181,6 +178,7 @@ impl SendRepository for PgLinkedRepository {
request,
digest,
} = intent;
+ let user = user.as_ref();
let payload = serde_json::to_value(request).map_err(failure)?;
let mut tx = self.pool.begin().await.map_err(failure)?;
sqlx::query!(
@@ -235,16 +233,15 @@ impl SendRepository for PgLinkedRepository {
} else {
Some(sqlx::query_scalar!(
r#"UPDATE whatsapp_group b SET next_sequence = next_sequence + 1
- WHERE b.id = $1 AND b.id = $2 AND b.state = 'active'
+ WHERE b.id = $1 AND b.state = 'active'
AND EXISTS (
SELECT 1 FROM whatsapp_linked_account a JOIN whatsapp_group_membership m ON m.account_id = a.id
- WHERE a.id = $3 AND a.user_id = $4 AND a.state = 'connected' AND a.generation = $5
+ WHERE a.id = $2 AND a.user_id = $3 AND a.state = 'connected' AND a.generation = $4
AND m.binding_id = b.id AND m.generation = a.generation AND m.consent_ended_at IS NULL
AND m.remote_member AND m.can_post AND m.reconciled)
- AND whatsapp_group_can_view(b.id, $4)
+ AND whatsapp_group_can_view(b.id, $3)
RETURNING next_sequence"#,
binding.id,
- binding.id,
account.id,
user,
account.authorization_generation
@@ -268,7 +265,7 @@ impl SendRepository for PgLinkedRepository {
payload,
account.authorization_generation,
sequence,
- crate::outbound::trace_context::current()
+ crate::signals::trace_context::current()
)
.execute(&mut *tx)
.await
@@ -304,7 +301,12 @@ impl SendRepository for PgLinkedRepository {
})
}
- async fn open_sends(&self, group_id: Uuid, user: &str) -> LinkedResult<Vec<SendProgress>> {
+ async fn open_sends(
+ &self,
+ group_id: Uuid,
+ user: &MacroUserIdStr<'_>,
+ ) -> LinkedResult<Vec<SendProgress>> {
+ let user = user.as_ref();
sqlx::query_as!(
SendRow,
r#"SELECT id, user_id, group_id, payload, state, message_id, error_code, created_at FROM whatsapp_send
@@ -325,9 +327,10 @@ impl SendRepository for PgLinkedRepository {
async fn sends_for(
&self,
group_id: Uuid,
- user: &str,
+ user: &MacroUserIdStr<'_>,
ids: &[Uuid],
) -> LinkedResult<Vec<SendProgress>> {
+ let user = user.as_ref();
sqlx::query_as!(
SendRow,
r#"SELECT id, user_id, group_id, payload, state, message_id, error_code, created_at FROM whatsapp_send
@@ -465,7 +468,7 @@ impl PgLinkedRepository {
SELECT id FROM whatsapp_send WHERE account_id = $1 AND generation = $3 AND state = 'pending'
ORDER BY group_id, group_sequence LIMIT $4 FOR UPDATE SKIP LOCKED)
AND b.id = s.group_id
- RETURNING s.id, s.group_id AS binding_id, s.group_sequence, s.payload, s.traceparent, b.group_jid,
+ RETURNING s.id, s.group_id, s.group_sequence, s.payload, s.traceparent, b.group_jid,
(SELECT r.metadata FROM whatsapp_group_roster r WHERE r.account_id = s.account_id AND r.group_jid = b.group_jid) AS roster"#,
account.id,
scope.lease_epoch,
@@ -480,7 +483,7 @@ impl PgLinkedRepository {
let request: SendReply = decode(row.payload)?;
match content_in(
&mut tx,
- row.binding_id,
+ row.group_id,
&request,
account.identity_jid.as_deref(),
)
@@ -506,7 +509,7 @@ impl PgLinkedRepository {
.execute(&mut *tx)
.await
.map_err(failure)?;
- failed.push(row.binding_id);
+ failed.push(row.group_id);
}
}
}
@@ -598,7 +601,7 @@ impl PgLinkedRepository {
.ok_or(LinkedError::NotFound)?;
lock_group_in(&mut tx, binding).await?;
let row = sqlx::query!(
- r#"SELECT s.group_id AS binding_id, s.payload, s.allocated_source_id, s.state, s.created_at
+ r#"SELECT s.group_id, s.payload, s.allocated_source_id, s.state, s.created_at
FROM whatsapp_send s WHERE s.id = $1 AND s.account_id = $2 AND s.dispatch_started_at IS NOT NULL FOR UPDATE"#,
send,
account.id
@@ -628,7 +631,9 @@ impl PgLinkedRepository {
.map_err(failure)?;
}
SendOutcome::Accepted { server_at } => {
- let source = row.allocated_source_id.ok_or(LinkedError::Unavailable)?;
+ let source = row
+ .allocated_source_id
+ .ok_or_else(|| corrupt("a dispatched send has no source id"))?;
let identity = account
.identity_jid
.clone()
@@ -637,7 +642,7 @@ impl PgLinkedRepository {
let binding = sqlx::query_as!(
bindings::BindingRow,
"SELECT id, group_jid, kind, user_id, state, adopted_at FROM whatsapp_group WHERE id = $1",
- row.binding_id
+ row.group_id
)
.fetch_one(&mut *tx)
.await
@@ -661,7 +666,7 @@ impl PgLinkedRepository {
sha256: blob
.sha256
.try_into()
- .map_err(|_| LinkedError::Unavailable)?,
+ .map_err(|_| corrupt("sha256 is not 32 bytes"))?,
locator: vec![],
width: unsigned(blob.width),
height: unsigned(blob.height),
@@ -745,7 +750,7 @@ impl PgLinkedRepository {
}),
};
let InboundKind::Message(message) = &event.kind else {
- return Err(LinkedError::Unavailable.into());
+ return Err(corrupt("an accepted send is not a message"));
};
sqlx::query!(
"UPDATE whatsapp_send SET state = 'accepted', claimed_epoch = NULL, updated_at = now() WHERE id = $1 AND state IN ('sending', 'unknown')",
@@ -801,7 +806,7 @@ impl PgLinkedRepository {
let account = fence_in(&mut tx, scope).await?;
let row = sqlx::query!(
r#"SELECT b.mime, b.filename, b.sha256, b.bytes FROM whatsapp_send s
- JOIN whatsapp_media_blob b ON b.document_id = (s.payload->'message'->>'upload_id')::uuid
+ JOIN whatsapp_media_blob b ON b.document_id = (s.payload->'message'->>'uploadId')::uuid
AND b.user_id = s.user_id AND b.group_id = s.group_id
WHERE s.id = $1 AND s.account_id = $2 AND s.claimed_epoch = $3 AND s.state = 'sending'
AND s.payload->'message'->>'type' = 'media'"#,
@@ -815,13 +820,14 @@ impl PgLinkedRepository {
.ok_or(LinkedError::NotFound)?;
tx.commit().await.map_err(failure)?;
Ok(OutboundMedia {
- kind: MediaKind::of(&row.mime).ok_or(LinkedError::Unavailable)?,
+ kind: MediaKind::of(&row.mime)
+ .ok_or_else(|| corrupt(format_args!("staged upload type {:?}", row.mime)))?,
mime: row.mime,
filename: row.filename,
sha256: row
.sha256
.try_into()
- .map_err(|_| LinkedError::Unavailable)?,
+ .map_err(|_| corrupt("sha256 is not 32 bytes"))?,
bytes: row.bytes,
})
}
diff --git a/crates/whatsapp_linked/src/outbound/pg/session.rs b/crates/whatsapp_linked/src/outbound/pg/session.rs
index 8fb9e72739..f64ee7a83c 100644
--- a/crates/whatsapp_linked/src/outbound/pg/session.rs
+++ b/crates/whatsapp_linked/src/outbound/pg/session.rs
@@ -18,7 +18,8 @@ fn work(row: WorkRow) -> LinkedResult<PairingWork> {
Ok(PairingWork {
id: row.id,
account_id: row.account_id,
- state: PairingState::parse(&row.state).ok_or(LinkedError::Unavailable)?,
+ state: PairingState::parse(&row.state)
+ .ok_or_else(|| corrupt(format_args!("state {:?}", row.state)))?,
expected_identity_jid: row.expected_identity_jid,
expires_at: row.expires_at,
passkey_response: row.passkey_response,
@@ -31,10 +32,22 @@ async fn fail_pairing_in(
pairing: Uuid,
account: Uuid,
generation: i64,
+) -> LinkedResult<()> {
+ end_pairing_in(tx, pairing, account, generation, PairingState::Failed).await
+}
+
+/// Ends a live transaction as `state` and returns its account to disconnected.
+async fn end_pairing_in(
+ tx: &mut Transaction<'_, Postgres>,
+ pairing: Uuid,
+ account: Uuid,
+ generation: i64,
+ state: PairingState,
) -> LinkedResult<()> {
sqlx::query!(
- "UPDATE whatsapp_pairing SET state = 'failed', consumed_at = clock_timestamp(), qr_code = NULL, pair_code = NULL, passkey_challenge = NULL, passkey_response = NULL, updated_at = now() WHERE id = $1",
- pairing
+ "UPDATE whatsapp_pairing SET state = $2, consumed_at = clock_timestamp(), qr_code = NULL, pair_code = NULL, passkey_challenge = NULL, passkey_response = NULL, updated_at = now() WHERE id = $1",
+ pairing,
+ state.as_str()
)
.execute(&mut **tx)
.await
@@ -86,6 +99,12 @@ impl SessionRepository for PgLinkedRepository {
Ok(accounts)
}
+ async fn announce_released(&self, account: Uuid) -> LinkedResult<()> {
+ let mut tx = self.pool.begin().await.map_err(failure)?;
+ notify(&mut tx, signals::ACCOUNT_RELEASED, account).await?;
+ tx.commit().await.map_err(failure)
+ }
+
async fn fleet_health(&self) -> LinkedResult<FleetHealth> {
let row = sqlx::query!(
r#"WITH needing AS (
@@ -246,6 +265,16 @@ impl SessionRepository for PgLinkedRepository {
.await
.map_err(failure)?;
}
+ PairingUpdate::Expired => {
+ end_pairing_in(
+ &mut tx,
+ pairing,
+ account.id,
+ account.generation,
+ PairingState::Expired,
+ )
+ .await?;
+ }
PairingUpdate::Failed => {
fail_pairing_in(&mut tx, pairing, account.id, account.generation).await?;
}
@@ -428,14 +457,15 @@ impl SessionRepository for PgLinkedRepository {
})
}
- async fn update_chats(&self, scope: SessionScope, chats: &[ChatUpdate]) -> LinkedResult<()> {
+ async fn update_chats(&self, scope: SessionScope, chats: &[ChatUpdate]) -> LinkedResult<bool> {
let mut tx = self.pool.begin().await.map_err(failure)?;
let account = fence_in(&mut tx, scope).await?;
if account.state != AccountState::Connected {
- return Ok(());
+ return Ok(false);
}
- chats::update_chats_in(&mut tx, &account, chats).await?;
- tx.commit().await.map_err(failure)
+ let anchored = chats::update_chats_in(&mut tx, &account, chats).await?;
+ tx.commit().await.map_err(failure)?;
+ Ok(anchored)
}
async fn backfill_work(&self, scope: SessionScope) -> LinkedResult<Vec<BackfillWork>> {
@@ -449,6 +479,24 @@ impl SessionRepository for PgLinkedRepository {
Ok(work)
}
+ async fn backfill_waiting_for_message(
+ &self,
+ scope: SessionScope,
+ group: Uuid,
+ ) -> LinkedResult<()> {
+ let mut tx = self.pool.begin().await.map_err(failure)?;
+ let account = fence_in(&mut tx, scope).await?;
+ chats::set_backfill_in(
+ &mut tx,
+ &account,
+ group,
+ BackfillState::WaitingForMessage,
+ false,
+ )
+ .await?;
+ tx.commit().await.map_err(failure)
+ }
+
async fn backfill_requested(&self, scope: SessionScope, group: Uuid) -> LinkedResult<()> {
let mut tx = self.pool.begin().await.map_err(failure)?;
let account = fence_in(&mut tx, scope).await?;
diff --git a/crates/whatsapp_linked/src/outbound/pg/test.rs b/crates/whatsapp_linked/src/outbound/pg/test.rs
index 868a7a7944..bb57e49ca0 100644
--- a/crates/whatsapp_linked/src/outbound/pg/test.rs
+++ b/crates/whatsapp_linked/src/outbound/pg/test.rs
@@ -2,7 +2,7 @@ use super::*;
use crate::domain::timeline::TimelineRepository;
use crate::domain::{
events::*,
- ports::{Authorizer, EffectsRepository, GroupEffect, GroupPublisher, Origin, SendRateLimiter},
+ ports::{EffectsRepository, GroupEffect, GroupPublisher, Origin, SendRateLimiter},
service::LinkedService,
session::SessionService,
};
@@ -19,12 +19,18 @@ use std::sync::Arc;
mod changes;
mod concurrency;
+mod deletion;
mod media;
mod pairing;
mod rich;
mod timeline;
const GROUP: &str = "[email protected]";
+/// A test user's id, typed.
+fn person(user: &str) -> macro_user_id::user_id::MacroUserIdStr<'static> {
+ user.to_owned().try_into().expect("test user ids are valid")
+}
+
const ALICE: &str = "macro|[email protected]";
const BOB: &str = "macro|[email protected]";
const CAROL: &str = "macro|[email protected]";
@@ -34,13 +40,6 @@ const CUSTOMER_JID: &str = "[email protected]";
struct Allow;
-#[async_trait]
-impl Authorizer for Allow {
- async fn require_group_owner(&self, _: Uuid, _: &str) -> LinkedResult<()> {
- Ok(())
- }
-}
-
const ALL_ON: Features = Features {
pairing: true,
adoption: true,
@@ -50,7 +49,7 @@ const ALL_ON: Features = Features {
fn services(pool: &PgPool) -> (LinkedService, SessionService, Arc<PgLinkedRepository>) {
let repository = Arc::new(PgLinkedRepository::new(pool.clone()));
(
- LinkedService::new(ALL_ON, repository.clone(), Arc::new(Allow), Arc::new(Allow)),
+ LinkedService::new(ALL_ON, repository.clone(), Arc::new(Allow)),
SessionService::new(repository.clone()),
repository,
)
@@ -115,7 +114,7 @@ async fn pair(
jid: &str,
) -> SessionScope {
let pairing = linked
- .connect(user, false, SendAuthority::Human)
+ .connect(&person(user), false, SendAuthority::Human)
.await
.unwrap();
let lease = session.begin_lease(pairing.account_id).await.unwrap();
@@ -229,7 +228,7 @@ async fn adopted(
.unwrap();
let binding = linked
.adopt(
- ALICE,
+ &person(ALICE),
&AdoptGroup {
group_jid: GROUP.into(),
},
@@ -258,7 +257,7 @@ async fn adopted(
async fn adoption_creates_a_shared_entity_and_leaving_whatsapp_keeps_view_access(pool: PgPool) {
let (linked, session, _, binding, _, bob) = adopted(&pool).await;
assert_eq!(binding.user_id, ALICE);
- let mine = &linked.chats(ALICE).await.unwrap().chats[0];
+ let mine = &linked.chats(&person(ALICE)).await.unwrap().chats[0];
assert_eq!(
(mine.group.clone(), mine.shared.clone()),
(
@@ -269,7 +268,7 @@ async fn adoption_creates_a_shared_entity_and_leaving_whatsapp_keeps_view_access
None
)
);
- let shared = &linked.chats(BOB).await.unwrap().chats[0];
+ let shared = &linked.chats(&person(BOB)).await.unwrap().chats[0];
assert_eq!(
(shared.group.clone(), shared.shared.clone()),
(
@@ -306,7 +305,7 @@ async fn adoption_creates_a_shared_entity_and_leaving_whatsapp_keeps_view_access
let mut left = text(9, BOB_JID, "unused", "");
left.kind = InboundKind::Left;
session.ingest_event(bob, &left).await.unwrap();
- assert_eq!(linked.adopted_groups(BOB).await.unwrap().len(), 1);
+ assert_eq!(linked.adopted_groups(&person(BOB)).await.unwrap().len(), 1);
assert!(
!linked
.group_detail(&receipt::<MessageView>(BOB, binding.id))
@@ -324,17 +323,17 @@ async fn each_person_adds_their_own_group_once(pool: PgPool) {
group_jid: GROUP.into(),
};
let again = linked
- .adopt(ALICE, &request, SendAuthority::Human)
+ .adopt(&person(ALICE), &request, SendAuthority::Human)
.await
.unwrap();
assert_eq!(again.id, binding.id, "adding twice returns the same group");
let bobs = linked
- .adopt(BOB, &request, SendAuthority::Human)
+ .adopt(&person(BOB), &request, SendAuthority::Human)
.await
.unwrap();
assert_ne!(bobs.id, binding.id);
assert_eq!(bobs.user_id, BOB);
- let listed = &linked.chats(BOB).await.unwrap().chats[0];
+ let listed = &linked.chats(&person(BOB)).await.unwrap().chats[0];
assert_eq!(
(listed.group.as_ref().map(|g| g.id), listed.shared.clone()),
(Some(bobs.id), None),
@@ -342,7 +341,7 @@ async fn each_person_adds_their_own_group_once(pool: PgPool) {
);
assert!(matches!(
linked
- .adopt(CAROL, &request, SendAuthority::Human)
+ .adopt(&person(CAROL), &request, SendAuthority::Human)
.await
.unwrap_err()
.current_context(),
@@ -891,10 +890,10 @@ async fn disconnecting_fails_undispatched_sends_and_stops_observation(pool: PgPo
)
.await
.unwrap();
- let account = linked.account(ALICE).await.unwrap().unwrap();
+ let account = linked.account(&person(ALICE)).await.unwrap().unwrap();
let result = linked
.disconnect(
- ALICE,
+ &person(ALICE),
account.authorization_generation,
SendAuthority::Human,
)
@@ -904,7 +903,7 @@ async fn disconnecting_fails_undispatched_sends_and_stops_observation(pool: PgPo
assert!(
!linked
.disconnect(
- ALICE,
+ &person(ALICE),
account.authorization_generation,
SendAuthority::Human
)
@@ -944,7 +943,7 @@ async fn stored_group_facts_authorize_adoption_and_sending_however_old(pool: PgP
group_jid: GROUP.into(),
};
let binding = linked
- .adopt(ALICE, &request, SendAuthority::Human)
+ .adopt(&person(ALICE), &request, SendAuthority::Human)
.await
.unwrap();
let detail = linked
@@ -987,7 +986,7 @@ async fn stored_group_facts_authorize_adoption_and_sending_however_old(pool: PgP
assert!(matches!(
linked
.adopt(
- ALICE,
+ &person(ALICE),
&AdoptGroup {
group_jid: "[email protected]".into()
},
@@ -1031,7 +1030,7 @@ async fn messages_stamped_around_adoption_follow_the_second_granular_boundary(po
#[async_trait]
impl SendRateLimiter for Allow {
- async fn check(&self, _: &str) -> LinkedResult<()> {
+ async fn check(&self, _: &macro_user_id::user_id::MacroUserIdStr<'_>) -> LinkedResult<()> {
Ok(())
}
}
@@ -1042,13 +1041,13 @@ async fn rate_limited_send_never_creates_a_dispatchable_intent(pool: PgPool) {
#[async_trait]
impl SendRateLimiter for Denied {
- async fn check(&self, _: &str) -> LinkedResult<()> {
+ async fn check(&self, _: &macro_user_id::user_id::MacroUserIdStr<'_>) -> LinkedResult<()> {
Err(LinkedError::RateLimited.into())
}
}
let (_, session, repository, binding, alice, _) = adopted(&pool).await;
- let linked = LinkedService::new(ALL_ON, repository, Arc::new(Allow), Arc::new(Denied));
+ let linked = LinkedService::new(ALL_ON, repository, Arc::new(Denied));
let request = SendReply {
idempotency_key: Uuid::now_v7(),
message: ReplyContent::Text {
diff --git a/crates/whatsapp_linked/src/outbound/pg/test/changes.rs b/crates/whatsapp_linked/src/outbound/pg/test/changes.rs
index 6b88d75564..d311686786 100644
--- a/crates/whatsapp_linked/src/outbound/pg/test/changes.rs
+++ b/crates/whatsapp_linked/src/outbound/pg/test/changes.rs
@@ -61,7 +61,7 @@ async fn rosters_signal_only_real_changes_and_rename_the_owners_group(pool: PgPo
);
assert!(
linked
- .chats(ALICE)
+ .chats(&person(ALICE))
.await
.unwrap()
.chats
@@ -191,7 +191,7 @@ async fn change_audiences_come_from_the_store(pool: PgPool) {
.await
.unwrap();
let message = linked
- .messages(&receipt::<MessageView>(ALICE, binding.id), None, 1)
+ .messages(&receipt::<MessageView>(ALICE, binding.id), None, Some(1))
.await
.unwrap()
.messages[0]
diff --git a/crates/whatsapp_linked/src/outbound/pg/test/chats.rs b/crates/whatsapp_linked/src/outbound/pg/test/chats.rs
index f5695e7154..fd300821c9 100644
--- a/crates/whatsapp_linked/src/outbound/pg/test/chats.rs
+++ b/crates/whatsapp_linked/src/outbound/pg/test/chats.rs
@@ -72,7 +72,7 @@ async fn the_chat_list_merges_history_activity_and_the_roster(pool: PgPool) {
.await
.unwrap();
- let chats = linked.chats(ALICE).await.unwrap().chats;
+ let chats = linked.chats(&person(ALICE)).await.unwrap().chats;
let summary: Vec<_> = chats
.iter()
.map(|chat| {
@@ -145,17 +145,33 @@ async fn a_new_adoption_backfills_from_the_chat_anchor_page_by_page(pool: PgPool
work[0].anchor.clone(),
work[0].cursor.clone()
),
- (BackfillState::Pending, None, None),
- "no message seen yet: waits for one"
+ (BackfillState::WaitingForMessage, None, None),
+ "no message known yet: waits for one"
+ );
+ assert!(
+ !session
+ .update_chats(
+ alice,
+ &[chat(GROUP, ChatKind::Group, Some("Renamed"), None)]
+ )
+ .await
+ .unwrap(),
+ "a rename is no message to start from"
+ );
+ assert!(
+ session
+ .update_chats(alice, &[chat(GROUP, ChatKind::Group, None, Some(40))])
+ .await
+ .unwrap(),
+ "the chat's first message makes it ready"
);
- session
- .update_chats(alice, &[chat(GROUP, ChatKind::Group, None, Some(40))])
- .await
- .unwrap();
let work = session.backfill_work(alice).await.unwrap();
assert_eq!(
- work[0].anchor.as_ref().map(|anchor| anchor.id.as_str()),
- Some("3EB00040")
+ (
+ work[0].state,
+ work[0].anchor.as_ref().map(|anchor| anchor.id.as_str())
+ ),
+ (BackfillState::Pending, Some("3EB00040"))
);
session.backfill_requested(alice, binding.id).await.unwrap();
@@ -203,3 +219,98 @@ async fn a_new_adoption_backfills_from_the_chat_anchor_page_by_page(pool: PgPool
);
assert!(session.backfill_work(alice).await.unwrap().is_empty());
}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_chat_without_a_listed_message_starts_from_its_newest_stored_one(pool: PgPool) {
+ let (_, session, _, binding, alice, _) = adopted(&pool).await;
+ // Stored live, but the chat list never heard of it.
+ session
+ .ingest_event(alice, &text(1, CUSTOMER_JID, "3EB0CAFE", "hello"))
+ .await
+ .unwrap();
+ let work = session.backfill_work(alice).await.unwrap();
+ assert_eq!(work[0].state, BackfillState::WaitingForMessage);
+ let anchor = work[0]
+ .anchor
+ .clone()
+ .expect("the stored message anchors it");
+ assert_eq!(
+ (
+ anchor.id.as_str(),
+ anchor.from_me,
+ anchor.sender_jid.as_deref()
+ ),
+ ("3EB0CAFE", false, Some(CUSTOMER_JID))
+ );
+ session.backfill_requested(alice, binding.id).await.unwrap();
+ assert_eq!(
+ session.backfill_work(alice).await.unwrap()[0].state,
+ BackfillState::Running
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn ending_consent_forgets_the_old_numbers_chat_list(pool: PgPool) {
+ let (linked, session, _, _, alice, _) = adopted(&pool).await;
+ session
+ .update_chats(
+ alice,
+ &[chat(DIRECT, ChatKind::Direct, Some("Customer"), Some(30))],
+ )
+ .await
+ .unwrap();
+ let stored = |pool: PgPool| async move {
+ sqlx::query_scalar!(
+ r#"SELECT (SELECT count(*) FROM whatsapp_chat WHERE account_id = $1)
+ + (SELECT count(*) FROM whatsapp_group_roster WHERE account_id = $1) AS "count!""#,
+ alice.account_id
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap()
+ };
+ assert!(stored(pool.clone()).await > 0);
+ let account = linked.account(&person(ALICE)).await.unwrap().unwrap();
+ linked
+ .disconnect(
+ &person(ALICE),
+ account.authorization_generation,
+ SendAuthority::Human,
+ )
+ .await
+ .unwrap();
+ assert_eq!(stored(pool.clone()).await, 0);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn one_batch_may_name_a_chat_twice(pool: PgPool) {
+ let (linked, session, _, _, alice, _) = adopted(&pool).await;
+ let mut renamed = chat(DIRECT, ChatKind::Direct, Some("Customer (work)"), Some(10));
+ renamed.create = false;
+ session
+ .update_chats(
+ alice,
+ &[
+ chat(DIRECT, ChatKind::Direct, Some("Customer"), Some(40)),
+ renamed,
+ chat(DIRECT, ChatKind::Direct, None, Some(20)),
+ ],
+ )
+ .await
+ .unwrap();
+ let listed = linked.chats(&person(ALICE)).await.unwrap().chats;
+ let direct = listed.iter().find(|chat| chat.jid == DIRECT).unwrap();
+ assert_eq!(
+ (direct.name.as_str(), direct.last_activity_at),
+ ("Customer (work)", Some(at(40)))
+ );
+ let anchor = sqlx::query_scalar!(
+ r#"SELECT anchor->>'id' AS "id!" FROM whatsapp_chat WHERE account_id = $1 AND chat_jid = $2"#,
+ alice.account_id,
+ DIRECT
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ assert_eq!(anchor, "3EB00040");
+}
diff --git a/crates/whatsapp_linked/src/outbound/pg/test/communities.rs b/crates/whatsapp_linked/src/outbound/pg/test/communities.rs
index a0b9d24a8c..288758f4f1 100644
--- a/crates/whatsapp_linked/src/outbound/pg/test/communities.rs
+++ b/crates/whatsapp_linked/src/outbound/pg/test/communities.rs
@@ -49,14 +49,10 @@ async fn disappearing_and_community_groups_are_added_like_any_other(pool: PgPool
.await
.unwrap();
- let chats = linked.chats(ALICE).await.unwrap().chats;
+ let chats = linked.chats(&person(ALICE)).await.unwrap().chats;
let listed = |jid: &str| {
let chat = chats.iter().find(|chat| chat.jid == jid).unwrap();
- (
- chat.can_add,
- chat.cannot_add_reason.clone(),
- chat.community.clone(),
- )
+ (chat.can_add, chat.cannot_add_reason, chat.community.clone())
};
let neighbours = |announcements| CommunityReference {
id: COMMUNITY.to_owned(),
@@ -73,7 +69,11 @@ async fn disappearing_and_community_groups_are_added_like_any_other(pool: PgPool
group_jid: jid.to_owned(),
};
let linked = &linked;
- async move { linked.adopt(ALICE, &request, SendAuthority::Human).await }
+ async move {
+ linked
+ .adopt(&person(ALICE), &request, SendAuthority::Human)
+ .await
+ }
};
assert!(matches!(
adopt(COMMUNITY).await.unwrap_err().current_context(),
@@ -92,22 +92,36 @@ async fn disappearing_and_community_groups_are_added_like_any_other(pool: PgPool
let vanishing = adopt(GROUP).await.unwrap();
let shown = detail(vanishing.clone()).await;
assert_eq!(shown.disappearing_seconds, Some(WEEK));
- assert_eq!(shown.community, None);
+ assert_eq!(shown.group.community, None);
assert!(shown.group.can_send);
let garden = detail(adopt(SUBGROUP).await.unwrap()).await;
- assert_eq!(garden.community, Some(neighbours(false)));
+ assert_eq!(garden.group.community, Some(neighbours(false)));
assert_eq!(garden.disappearing_seconds, None);
assert!(garden.group.can_send);
// Everyone reads the announcement group; only admins post.
let notices = detail(adopt(ANNOUNCEMENTS).await.unwrap()).await;
- assert_eq!(notices.community, Some(neighbours(true)));
+ assert_eq!(notices.group.community, Some(neighbours(true)));
assert_eq!(
notices.group.send_reason,
Some(ReplyBlock::NotAllowedInGroup)
);
+ // The list carries the community too, so it can group the chats.
+ let listed = linked.adopted_groups(&person(ALICE)).await.unwrap();
+ let community_of = |id: Uuid| {
+ listed
+ .iter()
+ .find(|group| group.id == id)
+ .unwrap()
+ .community
+ .clone()
+ };
+ assert_eq!(community_of(vanishing.id), None);
+ assert_eq!(community_of(garden.group.id), Some(neighbours(false)));
+ assert_eq!(community_of(notices.group.id), Some(neighbours(true)));
+
// A message in the disappearing group is kept like any other.
assert_eq!(
session
@@ -117,7 +131,7 @@ async fn disappearing_and_community_groups_are_added_like_any_other(pool: PgPool
IngestOutcome::Applied
);
let kept = linked
- .messages(&receipt::<MessageView>(ALICE, vanishing.id), None, 10)
+ .messages(&receipt::<MessageView>(ALICE, vanishing.id), None, Some(10))
.await
.unwrap()
.messages;
diff --git a/crates/whatsapp_linked/src/outbound/pg/test/concurrency.rs b/crates/whatsapp_linked/src/outbound/pg/test/concurrency.rs
index 14b79e4627..8ce5775e89 100644
--- a/crates/whatsapp_linked/src/outbound/pg/test/concurrency.rs
+++ b/crates/whatsapp_linked/src/outbound/pg/test/concurrency.rs
@@ -5,7 +5,11 @@ use tokio::sync::Barrier;
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn sends_and_roster_refreshes_share_a_consistent_lock_order(pool: PgPool) {
let (_, session, repository, binding, alice, _) = adopted(&pool).await;
- let account = repository.owned_account(ALICE).await.unwrap().unwrap();
+ let account = repository
+ .owned_account(&person(ALICE))
+ .await
+ .unwrap()
+ .unwrap();
let barrier = Barrier::new(2);
let sends = async {
for index in 0..64 {
@@ -20,7 +24,7 @@ async fn sends_and_roster_refreshes_share_a_consistent_lock_order(pool: PgPool)
barrier.wait().await;
repository
.enqueue(SendIntent {
- user: ALICE,
+ user: &person(ALICE),
account: &account,
binding: &binding,
request: &request,
@@ -54,7 +58,7 @@ async fn observers_can_refresh_groups_in_opposite_orders(pool: PgPool) {
.unwrap();
linked
.adopt(
- ALICE,
+ &person(ALICE),
&AdoptGroup {
group_jid: second.jid.clone(),
},
diff --git a/crates/whatsapp_linked/src/outbound/pg/test/deletion.rs b/crates/whatsapp_linked/src/outbound/pg/test/deletion.rs
new file mode 100644
index 0000000000..f135edb021
--- /dev/null
+++ b/crates/whatsapp_linked/src/outbound/pg/test/deletion.rs
@@ -0,0 +1,212 @@
+//! Deleting a Macro user removes their WhatsApp data and leaves others' intact.
+use super::*;
+
+fn text_reply(text: &str) -> SendReply {
+ SendReply {
+ idempotency_key: Uuid::now_v7(),
+ message: ReplyContent::Text {
+ text: text.into(),
+ mentions: vec![],
+ },
+ reply_to: None,
+ }
+}
+
+/// Rows still stored for a chat, by table.
+async fn remaining(pool: &PgPool, group: Uuid) -> [i64; 6] {
+ sqlx::query!(
+ r#"SELECT
+ (SELECT count(*) FROM whatsapp_group WHERE id = $1) AS "groups!",
+ (SELECT count(*) FROM whatsapp_group_message WHERE binding_id = $1) AS "messages!",
+ (SELECT count(*) FROM whatsapp_external_person WHERE binding_id = $1) AS "people!",
+ (SELECT count(*) FROM whatsapp_send WHERE group_id = $1) AS "sends!",
+ (SELECT count(*) FROM entity_access WHERE entity_id = $1) AS "grants!",
+ (SELECT count(*) FROM entity WHERE id = $1) AS "entities!""#,
+ group
+ )
+ .fetch_one(pool)
+ .await
+ .map(|row| {
+ [
+ row.groups,
+ row.messages,
+ row.people,
+ row.sends,
+ row.grants,
+ row.entities,
+ ]
+ })
+ .unwrap()
+}
+
+async fn aliases(pool: &PgPool, group: Uuid) -> i64 {
+ sqlx::query_scalar!(
+ r#"SELECT count(*) AS "count!" FROM whatsapp_identity_alias WHERE binding_id = $1"#,
+ group
+ )
+ .fetch_one(pool)
+ .await
+ .unwrap()
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn deleting_people_who_sent_removes_their_whatsapp_data(pool: PgPool) {
+ let (linked, session, _, binding, alice, _) = adopted(&pool).await;
+ session
+ .ingest_event(alice, &text(1, CUSTOMER_JID, "FIRST", "hello"))
+ .await
+ .unwrap();
+ for (user, text) in [(ALICE, "from alice"), (BOB, "from bob")] {
+ linked
+ .send_reply(
+ &receipt::<MessageWrite>(user, binding.id),
+ &text_reply(text),
+ SendAuthority::Human,
+ )
+ .await
+ .unwrap();
+ }
+
+ sqlx::query!(r#"DELETE FROM "User" WHERE id = $1"#, BOB)
+ .execute(&pool)
+ .await
+ .unwrap();
+ assert_eq!(
+ remaining(&pool, binding.id).await[3],
+ 1,
+ "only the deleted sender's send goes"
+ );
+ let permission = sqlx::query_scalar!(
+ "SELECT share_permission_id FROM whatsapp_group WHERE id = $1",
+ binding.id
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ sqlx::query!(r#"DELETE FROM "User" WHERE id = $1"#, ALICE)
+ .execute(&pool)
+ .await
+ .unwrap();
+ assert_eq!(remaining(&pool, binding.id).await, [0; 6]);
+ let sharing = sqlx::query_scalar!(
+ r#"SELECT count(*) AS "count!" FROM "SharePermission" WHERE id = $1"#,
+ permission
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ assert_eq!(sharing, 0);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn an_alias_outlives_the_account_that_saw_it(pool: PgPool) {
+ let (_, session, _, binding, _, bob) = adopted(&pool).await;
+ session
+ .ingest_event(bob, &text(1, CUSTOMER_JID, "SEEN", "hello"))
+ .await
+ .unwrap();
+ let before = aliases(&pool, binding.id).await;
+ assert!(before > 0);
+ sqlx::query!(r#"DELETE FROM "User" WHERE id = $1"#, BOB)
+ .execute(&pool)
+ .await
+ .unwrap();
+ assert_eq!(aliases(&pool, binding.id).await, before);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn receipts_are_stored_once_per_message_and_expire(pool: PgPool) {
+ use crate::domain::{
+ events::{Receipt, ReceiptState},
+ ports::MediaRepository,
+ };
+ let (_, session, repository, binding, alice, _) = adopted(&pool).await;
+ let receipt = InboundEvent {
+ event_id: Uuid::from_u128(77),
+ group_jid: GROUP.into(),
+ chat_alternate_jid: None,
+ source_at: Utc::now() - Duration::days(31),
+ observed_at: Utc::now(),
+ kind: InboundKind::Receipt(Receipt {
+ source_ids: vec!["A".into(), "B".into(), "A".into()],
+ participant_jid: CUSTOMER_JID.into(),
+ state: ReceiptState::Read,
+ }),
+ };
+ assert_eq!(
+ session.ingest_event(alice, &receipt).await.unwrap(),
+ IngestOutcome::Applied
+ );
+ let stored = sqlx::query_scalar!(
+ r#"SELECT receipt_state FROM whatsapp_participant_receipt WHERE binding_id = $1 ORDER BY source_id"#,
+ binding.id
+ )
+ .fetch_all(&pool)
+ .await
+ .unwrap();
+ assert_eq!(stored, vec!["read", "read"]);
+ repository.expire_retained().await.unwrap();
+ let left = sqlx::query_scalar!(
+ r#"SELECT count(*) AS "count!" FROM whatsapp_participant_receipt WHERE binding_id = $1"#,
+ binding.id
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ assert_eq!(left, 0);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn only_the_owners_session_stops_syncing_a_chat(pool: PgPool) {
+ let (linked, _, repository, binding, _, _) = adopted(&pool).await;
+ for (user, authority) in [
+ (ALICE, SendAuthority::UserApiToken),
+ (ALICE, SendAuthority::Automation),
+ (BOB, SendAuthority::Human),
+ ] {
+ let error = linked
+ .detach(&receipt::<MessageView>(user, binding.id), authority)
+ .await
+ .unwrap_err();
+ assert_eq!(error.current_context(), &LinkedError::Forbidden);
+ }
+ linked
+ .detach(
+ &receipt::<MessageView>(ALICE, binding.id),
+ SendAuthority::Human,
+ )
+ .await
+ .unwrap();
+ use crate::domain::ports::BindingRepository;
+ assert_eq!(
+ repository.binding(binding.id).await.unwrap().unwrap().state,
+ BindingState::Detached
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn consumed_pairings_are_pruned_after_a_day(pool: PgPool) {
+ use crate::domain::ports::MediaRepository;
+ let (_, _, repository, _, alice, _) = adopted(&pool).await;
+ let pairings = |pool: PgPool| async move {
+ sqlx::query_scalar!(
+ r#"SELECT count(*) AS "count!" FROM whatsapp_pairing WHERE account_id = $1"#,
+ alice.account_id
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap()
+ };
+ assert_eq!(pairings(pool.clone()).await, 1);
+ repository.expire_retained().await.unwrap();
+ assert_eq!(pairings(pool.clone()).await, 1, "a fresh pairing stays");
+ sqlx::query!(
+ "UPDATE whatsapp_pairing SET consumed_at = now() - interval '2 days' WHERE account_id = $1",
+ alice.account_id
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ repository.expire_retained().await.unwrap();
+ assert_eq!(pairings(pool.clone()).await, 0);
+}
diff --git a/crates/whatsapp_linked/src/outbound/pg/test/direct.rs b/crates/whatsapp_linked/src/outbound/pg/test/direct.rs
index 7d109cdb71..246f17119d 100644
--- a/crates/whatsapp_linked/src/outbound/pg/test/direct.rs
+++ b/crates/whatsapp_linked/src/outbound/pg/test/direct.rs
@@ -41,7 +41,7 @@ async fn a_direct_chat_is_added_kept_and_sent_to_only_by_its_owner(pool: PgPool)
.await
.unwrap();
- let listed = linked.chats(ALICE).await.unwrap().chats;
+ let listed = linked.chats(&person(ALICE)).await.unwrap().chats;
let chat = listed.iter().find(|chat| chat.jid == CUSTOMER_JID).unwrap();
assert_eq!(
(chat.kind, chat.can_add, chat.cannot_add_reason),
@@ -52,7 +52,7 @@ async fn a_direct_chat_is_added_kept_and_sent_to_only_by_its_owner(pool: PgPool)
};
assert!(matches!(
linked
- .adopt(ALICE, &own, SendAuthority::Human)
+ .adopt(&person(ALICE), &own, SendAuthority::Human)
.await
.unwrap_err()
.current_context(),
@@ -62,13 +62,13 @@ async fn a_direct_chat_is_added_kept_and_sent_to_only_by_its_owner(pool: PgPool)
group_jid: CUSTOMER_JID.into(),
};
let binding = linked
- .adopt(ALICE, &request, SendAuthority::Human)
+ .adopt(&person(ALICE), &request, SendAuthority::Human)
.await
.unwrap();
assert_eq!(binding.kind, ChatKind::Direct);
assert_eq!(
linked
- .adopt(ALICE, &request, SendAuthority::Human)
+ .adopt(&person(ALICE), &request, SendAuthority::Human)
.await
.unwrap()
.id,
@@ -89,7 +89,7 @@ async fn a_direct_chat_is_added_kept_and_sent_to_only_by_its_owner(pool: PgPool)
(ChatKind::Direct, "Customer", true)
);
assert!(detail.roster.is_none());
- let bobs_list = linked.chats(BOB).await.unwrap().chats;
+ let bobs_list = linked.chats(&person(BOB)).await.unwrap().chats;
let bobs = bobs_list
.iter()
.find(|chat| chat.jid == CUSTOMER_JID)
@@ -111,7 +111,7 @@ async fn a_direct_chat_is_added_kept_and_sent_to_only_by_its_owner(pool: PgPool)
);
}
let messages = linked
- .messages(&receipt::<MessageView>(ALICE, binding.id), None, 10)
+ .messages(&receipt::<MessageView>(ALICE, binding.id), None, Some(10))
.await
.unwrap()
.messages;
diff --git a/crates/whatsapp_linked/src/outbound/pg/test/media.rs b/crates/whatsapp_linked/src/outbound/pg/test/media.rs
index 112121ec84..9ce8258e6d 100644
--- a/crates/whatsapp_linked/src/outbound/pg/test/media.rs
+++ b/crates/whatsapp_linked/src/outbound/pg/test/media.rs
@@ -15,17 +15,16 @@ struct Documents {
#[async_trait]
impl DocumentStore for Documents {
- async fn store(&self, import: &DocumentImport) -> LinkedResult<()> {
+ async fn store(&self, import: &DocumentImport, bytes: Vec<u8>) -> LinkedResult<()> {
let mut fail = self.fail.lock().unwrap();
if *fail > 0 {
*fail -= 1;
return Err(LinkedError::Unavailable.into());
}
- self.stored.lock().unwrap().push((
- import.document_id,
- import.owner.clone(),
- import.bytes.clone(),
- ));
+ self.stored
+ .lock()
+ .unwrap()
+ .push((import.document_id, import.owner.clone(), bytes));
Ok(())
}
}
@@ -400,14 +399,14 @@ async fn a_passkey_assertion_is_forwarded_once(pool: PgPool) {
workspace(&pool).await;
let (linked, session, _) = services(&pool);
let pairing = linked
- .connect(ALICE, false, SendAuthority::Human)
+ .connect(&person(ALICE), false, SendAuthority::Human)
.await
.unwrap();
let lease = session.begin_lease(pairing.account_id).await.unwrap();
let assertion = serde_json::json!({ "id": "credential", "response": {} });
assert!(
linked
- .passkey(ALICE, pairing.id, &assertion, SendAuthority::Human)
+ .passkey(&person(ALICE), pairing.id, &assertion, SendAuthority::Human)
.await
.is_err(),
"only a transaction waiting on a passkey accepts one"
@@ -423,7 +422,7 @@ async fn a_passkey_assertion_is_forwarded_once(pool: PgPool) {
.await
.unwrap();
let state = linked
- .pair_state(ALICE, pairing.id, SendAuthority::Human)
+ .pair_state(&person(ALICE), pairing.id, SendAuthority::Human)
.await
.unwrap();
assert_eq!(
@@ -432,12 +431,12 @@ async fn a_passkey_assertion_is_forwarded_once(pool: PgPool) {
);
assert!(
linked
- .passkey(BOB, pairing.id, &assertion, SendAuthority::Human)
+ .passkey(&person(BOB), pairing.id, &assertion, SendAuthority::Human)
.await
.is_err()
);
linked
- .passkey(ALICE, pairing.id, &assertion, SendAuthority::Human)
+ .passkey(&person(ALICE), pairing.id, &assertion, SendAuthority::Human)
.await
.unwrap();
assert_eq!(
diff --git a/crates/whatsapp_linked/src/outbound/pg/test/pairing.rs b/crates/whatsapp_linked/src/outbound/pg/test/pairing.rs
index 991410c539..12cbc9a176 100644
--- a/crates/whatsapp_linked/src/outbound/pg/test/pairing.rs
+++ b/crates/whatsapp_linked/src/outbound/pg/test/pairing.rs
@@ -6,13 +6,13 @@ async fn pairing_is_owner_bound_and_a_verified_identity_cannot_change_hands(pool
workspace(&pool).await;
let (linked, session, _) = services(&pool);
let pairing = linked
- .connect(ALICE, false, SendAuthority::Human)
+ .connect(&person(ALICE), false, SendAuthority::Human)
.await
.unwrap();
assert_eq!(pairing.state, PairingState::Waiting);
assert_eq!(
linked
- .connect(ALICE, false, SendAuthority::Human)
+ .connect(&person(ALICE), false, SendAuthority::Human)
.await
.unwrap()
.id,
@@ -21,7 +21,7 @@ async fn pairing_is_owner_bound_and_a_verified_identity_cannot_change_hands(pool
);
assert!(matches!(
linked
- .pair_state(BOB, pairing.id, SendAuthority::Human)
+ .pair_state(&person(BOB), pairing.id, SendAuthority::Human)
.await
.err()
.unwrap()
@@ -40,7 +40,7 @@ async fn pairing_is_owner_bound_and_a_verified_identity_cannot_change_hands(pool
assert!(
matches!(
linked
- .pair_state(ALICE, pairing.id, SendAuthority::UserApiToken)
+ .pair_state(&person(ALICE), pairing.id, SendAuthority::UserApiToken)
.await
.err()
.unwrap()
@@ -50,7 +50,7 @@ async fn pairing_is_owner_bound_and_a_verified_identity_cannot_change_hands(pool
"automation cannot read live enrollment material"
);
let state = linked
- .pair_state(ALICE, pairing.id, SendAuthority::Human)
+ .pair_state(&person(ALICE), pairing.id, SendAuthority::Human)
.await
.unwrap();
assert_eq!(state.state, PairingState::Qr);
@@ -66,7 +66,7 @@ async fn pairing_is_owner_bound_and_a_verified_identity_cannot_change_hands(pool
.await
.unwrap();
let state = linked
- .pair_state(ALICE, pairing.id, SendAuthority::Human)
+ .pair_state(&person(ALICE), pairing.id, SendAuthority::Human)
.await
.unwrap();
assert_eq!(state.state, PairingState::Success);
@@ -77,7 +77,7 @@ async fn pairing_is_owner_bound_and_a_verified_identity_cannot_change_hands(pool
assert_eq!(state.identity_jid.as_deref(), Some(ALICE_JID));
assert!(matches!(
linked
- .connect(ALICE, false, SendAuthority::Human)
+ .connect(&person(ALICE), false, SendAuthority::Human)
.await
.unwrap_err()
.current_context(),
@@ -86,7 +86,7 @@ async fn pairing_is_owner_bound_and_a_verified_identity_cannot_change_hands(pool
// Bob cannot pair Alice's WhatsApp account.
let bob = linked
- .connect(BOB, false, SendAuthority::Human)
+ .connect(&person(BOB), false, SendAuthority::Human)
.await
.unwrap();
let bob_lease = session.begin_lease(bob.account_id).await.unwrap();
@@ -103,29 +103,29 @@ async fn pairing_is_owner_bound_and_a_verified_identity_cannot_change_hands(pool
assert!(matches!(stolen.current_context(), LinkedError::Forbidden));
assert_eq!(
linked
- .pair_state(BOB, bob.id, SendAuthority::Human)
+ .pair_state(&person(BOB), bob.id, SendAuthority::Human)
.await
.unwrap()
.state,
PairingState::Failed
);
assert_eq!(
- linked.account(BOB).await.unwrap().unwrap().state,
+ linked.account(&person(BOB)).await.unwrap().unwrap().state,
AccountState::Disconnected
);
// A reconnect must come back as the same identity.
- let account = linked.account(ALICE).await.unwrap().unwrap();
+ let account = linked.account(&person(ALICE)).await.unwrap().unwrap();
linked
.disconnect(
- ALICE,
+ &person(ALICE),
account.authorization_generation,
SendAuthority::Human,
)
.await
.unwrap();
let reconnect = linked
- .connect(ALICE, false, SendAuthority::Human)
+ .connect(&person(ALICE), false, SendAuthority::Human)
.await
.unwrap();
let lease = session.begin_lease(reconnect.account_id).await.unwrap();
@@ -147,33 +147,76 @@ async fn cancelling_pairing_ends_consent_and_signals_the_replica(pool: PgPool) {
workspace(&pool).await;
let (linked, session, _) = services(&pool);
let pairing = linked
- .connect(ALICE, false, SendAuthority::Human)
+ .connect(&person(ALICE), false, SendAuthority::Human)
.await
.unwrap();
assert_eq!(
linked
- .cancel(ALICE, pairing.id, SendAuthority::Automation)
+ .cancel(&person(ALICE), pairing.id, SendAuthority::Automation)
.await
.unwrap_err()
.current_context(),
&LinkedError::Forbidden
);
linked
- .cancel(ALICE, pairing.id, SendAuthority::Human)
+ .cancel(&person(ALICE), pairing.id, SendAuthority::Human)
.await
.unwrap();
linked
- .cancel(ALICE, pairing.id, SendAuthority::Human)
+ .cancel(&person(ALICE), pairing.id, SendAuthority::Human)
.await
.unwrap();
let work = session.pairing_work(pairing.id).await.unwrap().unwrap();
assert_eq!(work.state, PairingState::Cancelled);
assert_eq!(
- linked.account(ALICE).await.unwrap().unwrap().state,
+ linked.account(&person(ALICE)).await.unwrap().unwrap().state,
AccountState::Disconnected
);
}
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn an_expired_qr_session_reads_as_expired_and_a_new_connect_starts_fresh(pool: PgPool) {
+ workspace(&pool).await;
+ let (linked, session, _) = services(&pool);
+ let pairing = linked
+ .connect(&person(ALICE), false, SendAuthority::Human)
+ .await
+ .unwrap();
+ let lease = session.begin_lease(pairing.account_id).await.unwrap();
+ session
+ .update_pairing(
+ lease.scope,
+ pairing.id,
+ PairingUpdate::Qr("2@qr-ref".into()),
+ )
+ .await
+ .unwrap();
+ let work = session
+ .update_pairing(lease.scope, pairing.id, PairingUpdate::Expired)
+ .await
+ .unwrap();
+ assert_eq!(work.state, PairingState::Expired);
+ let state = linked
+ .pair_state(&person(ALICE), pairing.id, SendAuthority::Human)
+ .await
+ .unwrap();
+ assert_eq!(state.state, PairingState::Expired);
+ assert!(state.qr.is_none(), "an expired code is not scannable");
+ assert_eq!(
+ linked.account(&person(ALICE)).await.unwrap().unwrap().state,
+ AccountState::Disconnected
+ );
+ let next = linked
+ .connect(&person(ALICE), false, SendAuthority::Human)
+ .await
+ .unwrap();
+ assert_ne!(
+ next.id, pairing.id,
+ "the expired transaction is not resumed"
+ );
+ assert_eq!(next.state, PairingState::Waiting);
+}
+
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn a_newer_lease_fences_the_previous_replica(pool: PgPool) {
workspace(&pool).await;
diff --git a/crates/whatsapp_linked/src/outbound/pg/test/rich.rs b/crates/whatsapp_linked/src/outbound/pg/test/rich.rs
index 73693d5a0d..0dfaf5a95f 100644
--- a/crates/whatsapp_linked/src/outbound/pg/test/rich.rs
+++ b/crates/whatsapp_linked/src/outbound/pg/test/rich.rs
@@ -46,7 +46,7 @@ async fn a_system_line_names_people_and_never_notifies_or_counts_as_unread(pool:
session.ingest_event(alice, &added).await.unwrap();
let messages = linked
- .messages(&receipt::<MessageView>(BOB, binding.id), None, 50)
+ .messages(&receipt::<MessageView>(BOB, binding.id), None, Some(50))
.await
.unwrap()
.messages;
@@ -60,7 +60,7 @@ async fn a_system_line_names_people_and_never_notifies_or_counts_as_unread(pool:
assert_eq!(line.participants, vec![person("+15550000002", None)]);
assert_eq!(
repository
- .summary(binding.id, BOB)
+ .group_facts(binding.id, BOB)
.await
.unwrap()
.unread_count,
@@ -110,7 +110,7 @@ fn vote(event: u128, voter: &str, source: &str, revision: i64, selected: &[&str]
async fn tallies(linked: &LinkedService, group: Uuid) -> Vec<WhatsAppPollOption> {
let messages = linked
- .messages(&receipt::<MessageView>(ALICE, group), None, 50)
+ .messages(&receipt::<MessageView>(ALICE, group), None, Some(50))
.await
.unwrap()
.messages;
@@ -213,7 +213,7 @@ async fn a_re_imported_placeholder_gains_its_content_and_mentions_read_as_names(
session.ingest_event(alice, &mention).await.unwrap();
let messages = linked
- .messages(&receipt::<MessageView>(ALICE, binding.id), None, 50)
+ .messages(&receipt::<MessageView>(ALICE, binding.id), None, Some(50))
.await
.unwrap()
.messages;
@@ -258,7 +258,7 @@ async fn a_change_whatsapp_made_without_naming_anyone_is_the_groups_own_line(poo
session.ingest_event(alice, &renamed).await.unwrap();
let messages = linked
- .messages(&receipt::<MessageView>(ALICE, binding.id), None, 50)
+ .messages(&receipt::<MessageView>(ALICE, binding.id), None, Some(50))
.await
.unwrap()
.messages;
diff --git a/crates/whatsapp_linked/src/outbound/pg/test/timeline.rs b/crates/whatsapp_linked/src/outbound/pg/test/timeline.rs
index 5e61ee6552..310a5e813e 100644
--- a/crates/whatsapp_linked/src/outbound/pg/test/timeline.rs
+++ b/crates/whatsapp_linked/src/outbound/pg/test/timeline.rs
@@ -38,7 +38,7 @@ async fn shared_viewer_without_whatsapp_reads_history_and_unread_but_cannot_send
assert_eq!(detail.group.unread_count, 1);
assert_eq!(detail.group.send_reason, Some(ReplyBlock::NoAccount));
assert!(detail.sending_identity.is_none());
- let messages = linked.messages(&receipt, None, 50).await.unwrap();
+ let messages = linked.messages(&receipt, None, Some(50)).await.unwrap();
assert_eq!(messages.messages[0].body, "Shared history");
let bot_access = EntityAccessReceipt::<MessageView>::try_new_bot(
"bot|00000000-0000-0000-0000-000000000123"
@@ -59,7 +59,7 @@ async fn shared_viewer_without_whatsapp_reads_history_and_unread_but_cannot_send
.unwrap();
assert_eq!(
linked
- .messages(&bot_access, None, 50)
+ .messages(&bot_access, None, Some(50))
.await
.unwrap()
.messages[0]
@@ -81,7 +81,7 @@ async fn shared_viewer_without_whatsapp_reads_history_and_unread_but_cannot_send
.unwrap();
assert_eq!(
repository
- .summary(binding.id, CAROL)
+ .group_facts(binding.id, CAROL)
.await
.unwrap()
.unread_count,
@@ -152,10 +152,10 @@ async fn timeline_cursor_and_read_cursor_are_group_scoped_and_monotone(pool: PgP
session.ingest_event(alice, &early).await.unwrap();
session.ingest_event(alice, &late).await.unwrap();
let receipt = receipt::<MessageView>(BOB, binding.id);
- let page = linked.messages(&receipt, None, 1).await.unwrap();
+ let page = linked.messages(&receipt, None, Some(1)).await.unwrap();
assert_eq!(page.messages[0].body, "newer");
let next = linked
- .messages(&receipt, page.next_cursor, 1)
+ .messages(&receipt, page.next_cursor, Some(1))
.await
.unwrap();
assert_eq!(next.messages[0].body, "older");
@@ -170,7 +170,7 @@ async fn timeline_cursor_and_read_cursor_are_group_scoped_and_monotone(pool: PgP
.unwrap();
assert_eq!(
repository
- .summary(binding.id, BOB)
+ .group_facts(binding.id, BOB)
.await
.unwrap()
.unread_count,
@@ -178,7 +178,7 @@ async fn timeline_cursor_and_read_cursor_are_group_scoped_and_monotone(pool: PgP
);
assert!(
repository
- .mark_read(Uuid::now_v7(), BOB, page.messages[0].id)
+ .mark_read(Uuid::now_v7(), &person(BOB), page.messages[0].id)
.await
.is_err()
);
@@ -258,12 +258,18 @@ async fn canonical_team_sharing_is_owner_only_and_reversible(pool: PgPool) {
.await
.is_err()
);
- assert!(linked.adopted_groups(CAROL).await.unwrap().is_empty());
+ assert!(
+ linked
+ .adopted_groups(&person(CAROL))
+ .await
+ .unwrap()
+ .is_empty()
+ );
linked
.update_permissions(&owner, &update, SendAuthority::Human)
.await
.unwrap();
- let shared = linked.adopted_groups(CAROL).await.unwrap();
+ let shared = linked.adopted_groups(&person(CAROL)).await.unwrap();
assert_eq!(shared[0].id, binding.id);
assert_eq!(shared[0].send_reason, Some(ReplyBlock::NoAccount));
assert_eq!(
@@ -285,7 +291,13 @@ async fn canonical_team_sharing_is_owner_only_and_reversible(pool: PgPool) {
)
.await
.unwrap();
- assert!(linked.adopted_groups(CAROL).await.unwrap().is_empty());
+ assert!(
+ linked
+ .adopted_groups(&person(CAROL))
+ .await
+ .unwrap()
+ .is_empty()
+ );
session
.ingest_event(alice, &text(50, CUSTOMER_JID, "PUBLIC", "Link sharing"))
.await
@@ -316,7 +328,13 @@ async fn canonical_team_sharing_is_owner_only_and_reversible(pool: PgPool) {
.await
.unwrap();
// Public links grant known-ID access, never global group discovery.
- assert!(linked.adopted_groups(CAROL).await.unwrap().is_empty());
+ assert!(
+ linked
+ .adopted_groups(&person(CAROL))
+ .await
+ .unwrap()
+ .is_empty()
+ );
use entity_access::domain::ports::EntityAccessService;
let access = entity_access::domain::service::EntityAccessServiceImpl::new(
entity_access::outbound::PgAccessRepository::new(pool.clone()),
@@ -342,12 +360,15 @@ async fn canonical_team_sharing_is_owner_only_and_reversible(pool: PgPool) {
)
.await
.unwrap();
- let page = linked.messages(&shared, None, 50).await.unwrap();
+ let page = linked.messages(&shared, None, Some(50)).await.unwrap();
linked
.mark_read(&shared, page.messages[0].id)
.await
.unwrap();
- assert_eq!(linked.adopted_groups(CAROL).await.unwrap().len(), 1);
+ assert_eq!(
+ linked.adopted_groups(&person(CAROL)).await.unwrap().len(),
+ 1
+ );
linked
.update_permissions(
&owner,
@@ -397,7 +418,13 @@ async fn canonical_team_sharing_is_owner_only_and_reversible(pool: PgPool) {
.unwrap(),
None
);
- assert!(linked.adopted_groups(CAROL).await.unwrap().is_empty());
+ assert!(
+ linked
+ .adopted_groups(&person(CAROL))
+ .await
+ .unwrap()
+ .is_empty()
+ );
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
@@ -456,7 +483,13 @@ async fn a_group_mentioned_in_a_channel_is_readable_by_its_current_members(pool:
.execute(&pool)
.await
.unwrap();
- assert!(linked.adopted_groups(CAROL).await.unwrap().is_empty());
+ assert!(
+ linked
+ .adopted_groups(&person(CAROL))
+ .await
+ .unwrap()
+ .is_empty()
+ );
// What mentioning the group in the channel writes.
let mut tx = pool.begin().await.unwrap();
entity_access_db_utils::channel_share::insert_if_absent(
@@ -469,7 +502,7 @@ async fn a_group_mentioned_in_a_channel_is_readable_by_its_current_members(pool:
.await
.unwrap();
tx.commit().await.unwrap();
- let listed = linked.adopted_groups(CAROL).await.unwrap();
+ let listed = linked.adopted_groups(&person(CAROL)).await.unwrap();
assert_eq!(listed.len(), 1);
assert_eq!(listed[0].id, binding.id);
assert_eq!(listed[0].send_reason, Some(ReplyBlock::NoAccount));
@@ -482,7 +515,11 @@ async fn a_group_mentioned_in_a_channel_is_readable_by_its_current_members(pool:
.await
.unwrap();
assert!(
- linked.adopted_groups(CAROL).await.unwrap().is_empty(),
+ linked
+ .adopted_groups(&person(CAROL))
+ .await
+ .unwrap()
+ .is_empty(),
"leaving the channel ends access"
);
}
@@ -579,3 +616,21 @@ async fn the_owner_sees_and_revokes_channel_grants(pool: PgPool) {
Some(vec![])
);
}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn one_message_reads_like_its_timeline_entry(pool: PgPool) {
+ let (linked, session, _, binding, alice, _) = adopted(&pool).await;
+ for (event, source) in [(1, "ONE"), (2, "TWO")] {
+ session
+ .ingest_event(alice, &text(event, CUSTOMER_JID, source, source))
+ .await
+ .unwrap();
+ }
+ let viewer = receipt::<MessageView>(BOB, binding.id);
+ let page = linked.messages(&viewer, None, Some(50)).await.unwrap();
+ let older = page.messages.last().unwrap();
+ let one = linked.message(&viewer, older.id).await.unwrap();
+ assert_eq!((one.id, one.body.as_str()), (older.id, older.body.as_str()));
+ let missing = linked.message(&viewer, Uuid::now_v7()).await.unwrap_err();
+ assert_eq!(missing.current_context(), &LinkedError::NotFound);
+}
diff --git a/crates/whatsapp_linked/src/outbound/pg/timeline.rs b/crates/whatsapp_linked/src/outbound/pg/timeline.rs
index 9599f1482f..e84afe2f30 100644
--- a/crates/whatsapp_linked/src/outbound/pg/timeline.rs
+++ b/crates/whatsapp_linked/src/outbound/pg/timeline.rs
@@ -9,6 +9,7 @@ use crate::domain::{
},
};
use async_trait::async_trait;
+use macro_user_id::user_id::MacroUserIdStr;
use models_permissions::share_permission::{
LinkShare, SharePermissionV2, UpdateSharePermissionRequestV2, access_level::AccessLevel,
};
@@ -97,82 +98,13 @@ impl PgLinkedRepository {
}
Ok(people)
}
-}
-
-#[async_trait]
-impl TimelineRepository for PgLinkedRepository {
- async fn visible_groups(&self, user: &str) -> LinkedResult<Vec<VisibleGroup>> {
- let rows = sqlx::query!(r#"SELECT g.id,g.name,g.kind,g.user_id,g.group_jid,g.state,g.adopted_at,g.backfill_state,g.backfill_imported,
- (SELECT count(*) FROM whatsapp_group_message m WHERE m.binding_id=g.id AND m.message_id IS NOT NULL
- AND m.deleted_at IS NULL AND m.origin<>'history' AND m.kind<>'system'
- AND NOT EXISTS(SELECT 1 FROM whatsapp_external_person p WHERE p.id=m.person_id AND p.user_id=$1)
- AND (r.message_id IS NULL OR (m.source_at,m.id)>(r.read_at,r.message_id))) AS "unread_count!",
- (SELECT max(source_at) FROM whatsapp_group_message WHERE binding_id=g.id AND message_id IS NOT NULL) AS last_message_at,
- roster.metadata AS "metadata?"
- FROM whatsapp_group g
- LEFT JOIN whatsapp_group_read_state r ON r.group_id=g.id AND r.user_id=$1
- LEFT JOIN whatsapp_linked_account a ON a.user_id=$1
- LEFT JOIN whatsapp_group_roster roster ON roster.account_id=a.id AND roster.group_jid=g.group_jid
- WHERE whatsapp_group_can_view(g.id,$1)
- AND (r.user_id IS NOT NULL OR EXISTS (SELECT 1 FROM entity_access ea
- WHERE ea.entity_id=g.id AND ea.entity_type='whatsapp_group'
- AND (ea.source_id=$1 OR ea.source_id IN (SELECT team_id::text FROM team_user WHERE user_id=$1)
- OR ea.source_id IN (SELECT channel_id::text FROM comms_channel_participants WHERE user_id=$1 AND left_at IS NULL))))
- ORDER BY g.adopted_at DESC LIMIT 2000"#,user)
- .fetch_all(&self.pool).await.map_err(failure)?;
- rows.into_iter()
- .map(|row| {
- Ok(VisibleGroup {
- summary: WhatsAppGroupSummary {
- id: row.id,
- name: row.name,
- kind: ChatKind::parse(&row.kind).ok_or(LinkedError::Unavailable)?,
- user_id: row.user_id.clone(),
- unread_count: row.unread_count,
- last_message_at: row.last_message_at,
- can_send: false,
- send_reason: None,
- backfill: backfill(row.backfill_state.as_deref(), row.backfill_imported),
- },
- binding: bindings::binding(bindings::BindingRow {
- id: row.id,
- group_jid: row.group_jid,
- kind: row.kind,
- user_id: row.user_id,
- state: row.state,
- adopted_at: row.adopted_at,
- })?,
- roster: row.metadata.map(decode).transpose()?,
- })
- })
- .collect()
- }
- async fn summary(&self, group: Uuid, user: &str) -> LinkedResult<WhatsAppGroupSummary> {
- let row = sqlx::query!(r#"SELECT g.id,g.name,g.kind,g.user_id,g.backfill_state,g.backfill_imported,
- (SELECT count(*) FROM whatsapp_group_message m WHERE m.binding_id = g.id AND m.message_id IS NOT NULL
- AND m.deleted_at IS NULL AND m.origin <> 'history' AND m.kind <> 'system'
- AND NOT EXISTS (SELECT 1 FROM whatsapp_external_person p WHERE p.id = m.person_id AND p.user_id = $2)
- AND (r.message_id IS NULL OR (m.source_at,m.id) > (r.read_at,r.message_id))) AS "unread_count!",
- (SELECT max(source_at) FROM whatsapp_group_message WHERE binding_id = g.id AND message_id IS NOT NULL) AS last_message_at
- FROM whatsapp_group g LEFT JOIN whatsapp_group_read_state r ON r.group_id = g.id AND r.user_id = $2
- WHERE g.id = $1"#,group,user).fetch_optional(&self.pool).await.map_err(failure)?.ok_or(LinkedError::NotFound)?;
- Ok(WhatsAppGroupSummary {
- id: row.id,
- name: row.name,
- kind: ChatKind::parse(&row.kind).ok_or(LinkedError::Unavailable)?,
- user_id: row.user_id,
- unread_count: row.unread_count,
- last_message_at: row.last_message_at,
- can_send: false,
- send_reason: None,
- backfill: backfill(row.backfill_state.as_deref(), row.backfill_imported),
- })
- }
- async fn messages(
+ /// A newest-first page of the timeline, or only the message `only`.
+ async fn timeline_page(
&self,
group: Uuid,
user: &str,
before: Option<Uuid>,
+ only: Option<Uuid>,
limit: i64,
) -> LinkedResult<WhatsAppGroupMessages> {
let rows = sqlx::query!(r#"SELECT m.id,m.person_id,p.user_id,COALESCE(p.display_name,'WhatsApp participant') AS "name!",
@@ -181,7 +113,8 @@ impl TimelineRepository for PgLinkedRepository {
FROM whatsapp_group_message m JOIN whatsapp_external_person p ON p.id = m.person_id
WHERE m.binding_id = $1 AND m.message_id IS NOT NULL
AND ($3::uuid IS NULL OR (m.source_at,m.id) < (SELECT source_at,id FROM whatsapp_group_message WHERE id = $3 AND binding_id = $1 AND message_id IS NOT NULL))
- ORDER BY m.source_at DESC,m.id DESC LIMIT $4"#,group,user,before,limit+1)
+ AND ($5::uuid IS NULL OR m.id = $5)
+ ORDER BY m.source_at DESC,m.id DESC LIMIT $4"#,group,user,before,limit+1,only)
.fetch_all(&self.pool).await.map_err(failure)?;
let more = rows.len() > limit as usize;
let mut messages = Vec::with_capacity(rows.len());
@@ -296,7 +229,120 @@ impl TimelineRepository for PgLinkedRepository {
next_cursor,
})
}
- async fn mark_read(&self, group: Uuid, user: &str, message: Uuid) -> LinkedResult<()> {
+
+ /// The chats `user` can see (or just `only`, already authorized), with
+ /// the caller's own roster. Candidates come from the viewer's grants and
+ /// read cursors before the visibility check, so a viewer who sees few
+ /// chats never scans every chat.
+ async fn group_rows(&self, user: &str, only: Option<Uuid>) -> LinkedResult<Vec<VisibleGroup>> {
+ let rows = sqlx::query!(r#"WITH sources AS MATERIALIZED (
+ SELECT array_append(ARRAY(SELECT team_id::text FROM team_user WHERE user_id = $1)
+ || ARRAY(SELECT channel_id::text FROM comms_channel_participants WHERE user_id = $1 AND left_at IS NULL), $1) AS ids),
+ candidates AS MATERIALIZED (
+ SELECT $2::uuid AS id WHERE $2::uuid IS NOT NULL
+ UNION
+ SELECT ea.entity_id FROM entity_access ea, sources s
+ WHERE $2::uuid IS NULL AND ea.entity_type = 'whatsapp_group' AND ea.source_id = ANY(s.ids)
+ UNION
+ SELECT rs.group_id FROM whatsapp_group_read_state rs WHERE $2::uuid IS NULL AND rs.user_id = $1)
+ SELECT g.id,g.name,g.kind,g.user_id,g.group_jid,g.state,g.adopted_at,g.backfill_state,g.backfill_imported,
+ (SELECT count(*) FROM (SELECT 1 FROM whatsapp_group_message m WHERE m.binding_id=g.id AND m.message_id IS NOT NULL
+ AND m.deleted_at IS NULL AND m.origin<>'history' AND m.kind<>'system'
+ AND NOT EXISTS(SELECT 1 FROM whatsapp_external_person p WHERE p.id=m.person_id AND p.user_id=$1)
+ AND (r.message_id IS NULL OR (m.source_at,m.id)>(r.read_at,r.message_id)) LIMIT $3) unread) AS "unread_count!",
+ (SELECT max(source_at) FROM whatsapp_group_message WHERE binding_id=g.id AND message_id IS NOT NULL) AS last_message_at,
+ roster.metadata AS "metadata?",
+ seen.community_jid AS "community_jid?",seen.community_announcements AS "community_announcements?",parent.name AS "community_name?"
+ FROM candidates c JOIN whatsapp_group g ON g.id=c.id
+ LEFT JOIN whatsapp_group_read_state r ON r.group_id=g.id AND r.user_id=$1
+ LEFT JOIN whatsapp_linked_account a ON a.user_id=$1
+ LEFT JOIN whatsapp_group_roster roster ON roster.account_id=a.id AND roster.group_jid=g.group_jid
+ LEFT JOIN LATERAL (SELECT r.metadata->>'communityJid' AS community_jid,COALESCE((r.metadata->>'communityAnnouncements')::boolean,false) AS community_announcements
+ FROM whatsapp_group_roster r JOIN whatsapp_group_membership m ON m.account_id=r.account_id
+ WHERE m.binding_id=g.id AND m.consent_ended_at IS NULL AND r.group_jid=g.group_jid
+ ORDER BY r.observed_at DESC LIMIT 1) seen ON true
+ LEFT JOIN LATERAL (SELECT r.metadata->>'name' AS name
+ FROM whatsapp_group_roster r JOIN whatsapp_group_membership m ON m.account_id=r.account_id
+ WHERE m.binding_id=g.id AND m.consent_ended_at IS NULL AND r.group_jid=seen.community_jid
+ ORDER BY r.observed_at DESC LIMIT 1) parent ON true
+ -- On the candidate, not the chat: Postgres would otherwise check every chat.
+ WHERE ($2::uuid IS NOT NULL OR whatsapp_group_can_view(c.id,$1))
+ ORDER BY g.adopted_at DESC LIMIT 2000"#,user,only,UNREAD_COUNT_CAP)
+ .fetch_all(&self.pool).await.map_err(failure)?;
+ rows.into_iter()
+ .map(|row| {
+ Ok(VisibleGroup {
+ facts: GroupFacts {
+ id: row.id,
+ name: row.name,
+ kind: ChatKind::parse(&row.kind)
+ .ok_or_else(|| corrupt(format_args!("kind {:?}", row.kind)))?,
+ user_id: row.user_id.clone(),
+ unread_count: row.unread_count,
+ last_message_at: row.last_message_at,
+ backfill: backfill(row.backfill_state.as_deref(), row.backfill_imported),
+ community: row.community_jid.map(|jid| CommunityFacts {
+ jid,
+ name: row.community_name,
+ announcements: row.community_announcements.unwrap_or(false),
+ }),
+ },
+ binding: bindings::binding(bindings::BindingRow {
+ id: row.id,
+ group_jid: row.group_jid,
+ kind: row.kind,
+ user_id: row.user_id,
+ state: row.state,
+ adopted_at: row.adopted_at,
+ })?,
+ roster: row.metadata.map(decode).transpose()?,
+ })
+ })
+ .collect()
+ }
+}
+
+#[async_trait]
+impl TimelineRepository for PgLinkedRepository {
+ async fn visible_groups(&self, user: &MacroUserIdStr<'_>) -> LinkedResult<Vec<VisibleGroup>> {
+ let user = user.as_ref();
+ self.group_rows(user, None).await
+ }
+ async fn group_facts(&self, group: Uuid, user: &str) -> LinkedResult<GroupFacts> {
+ self.group_rows(user, Some(group))
+ .await?
+ .pop()
+ .map(|visible| visible.facts)
+ .ok_or_else(|| LinkedError::NotFound.into())
+ }
+ async fn messages(
+ &self,
+ group: Uuid,
+ user: &str,
+ before: Option<Uuid>,
+ limit: i64,
+ ) -> LinkedResult<WhatsAppGroupMessages> {
+ self.timeline_page(group, user, before, None, limit).await
+ }
+ async fn message(
+ &self,
+ group: Uuid,
+ user: &str,
+ message: Uuid,
+ ) -> LinkedResult<Option<WhatsAppGroupMessage>> {
+ Ok(self
+ .timeline_page(group, user, None, Some(message), 1)
+ .await?
+ .messages
+ .pop())
+ }
+ async fn mark_read(
+ &self,
+ group: Uuid,
+ user: &MacroUserIdStr<'_>,
+ message: Uuid,
+ ) -> LinkedResult<()> {
+ let user = user.as_ref();
let changed = sqlx::query!(r#"INSERT INTO whatsapp_group_read_state (user_id,group_id,message_id,read_at)
SELECT $2,$1,id,source_at FROM whatsapp_group_message WHERE id = $3 AND binding_id = $1 AND message_id IS NOT NULL
ON CONFLICT (user_id,group_id) DO UPDATE SET message_id = excluded.message_id,read_at = excluded.read_at
@@ -347,12 +393,13 @@ impl TimelineRepository for PgLinkedRepository {
async fn update_permissions(
&self,
group: Uuid,
- user: &str,
+ user: &MacroUserIdStr<'_>,
update: &UpdateSharePermissionRequestV2,
command: Option<
&models_permissions::share_permission::team_share::AuthorizedTeamShareCommand,
>,
) -> LinkedResult<()> {
+ let user = user.as_ref();
let mut tx = self.pool.begin().await.map_err(failure)?;
share_permission_db_utils::team_share::acquire_guard(&mut tx)
.await
diff --git a/crates/whatsapp_linked/src/signals.rs b/crates/whatsapp_linked/src/signals.rs
new file mode 100644
index 0000000000..0392cf1928
--- /dev/null
+++ b/crates/whatsapp_linked/src/signals.rs
@@ -0,0 +1,84 @@
+//! Signals between DSS and the session service over Postgres `NOTIFY`, and
+//! the trace context they carry. Each payload is a JSON [`Signal`] (or
+//! [`ChangeSignal`] for [`CHANGED`]) with the sender's `traceparent`, so the
+//! receiver joins its trace. Shared by both sides; not an adapter.
+
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+/// `<pairing_id>`: start, update or stop pairing.
+pub const PAIRING_REQUESTED: &str = "whatsapp_pairing_requested";
+/// `<account_id>`: claim pending sends.
+pub const SEND_REQUESTED: &str = "whatsapp_send_requested";
+/// `<account_id>`: re-read the account's groups.
+pub const GROUPS_REQUESTED: &str = "whatsapp_groups_requested";
+/// `<account_id>`: consent or adopted groups changed; re-read the account.
+pub const ACCOUNT_CHANGED: &str = "whatsapp_account_changed";
+/// `<account_id>`: a replica released the account (session service only).
+pub const ACCOUNT_RELEASED: &str = "whatsapp_account_released";
+/// `<document_id>`: attachment bytes are ready to import (DSS listens).
+pub const MEDIA_READY: &str = "whatsapp_media_ready";
+/// `<message_id>`: a standalone message notification is ready (DSS listens).
+pub const GROUP_EFFECTS: &str = "whatsapp_group_effects";
+/// A [`ChangeSignal`]: something a page shows changed (DSS listens and
+/// pushes `whatsapp_changed` to the people who see it).
+pub const CHANGED: &str = "whatsapp_changed";
+
+/// Payload of every signal except [`CHANGED`].
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct Signal {
+ /// The id the channel documents.
+ pub id: Uuid,
+ /// The sender's W3C trace context.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub traceparent: Option<String>,
+}
+
+impl Signal {
+ /// Read a payload; `None` when malformed.
+ pub fn parse(payload: &str) -> Option<Self> {
+ serde_json::from_str(payload).ok()
+ }
+}
+
+/// What changed.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
+#[serde(tag = "scope", rename_all = "snake_case")]
+pub enum Change {
+ /// The account's own group list (roster) changed: its owner's add list.
+ Groups {
+ /// Account whose roster changed.
+ account_id: Uuid,
+ },
+ /// A group entity's details, timeline or sends changed: everyone who
+ /// can view it.
+ Group {
+ /// Group entity.
+ group_id: Uuid,
+ },
+}
+
+/// Payload of [`CHANGED`].
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct ChangeSignal {
+ /// What changed.
+ #[serde(flatten)]
+ pub change: Change,
+ /// The sender's W3C trace context.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub traceparent: Option<String>,
+}
+
+impl ChangeSignal {
+ /// Read a payload; `None` when malformed.
+ pub fn parse(payload: &str) -> Option<Self> {
+ serde_json::from_str(payload).ok()
+ }
+}
+
+/// W3C trace context across the Postgres hops.
+#[cfg(feature = "outbound")]
+pub mod trace_context;
+
+#[cfg(test)]
+mod test;
diff --git a/crates/whatsapp_linked/src/signals/test.rs b/crates/whatsapp_linked/src/signals/test.rs
new file mode 100644
index 0000000000..24f3c59cae
--- /dev/null
+++ b/crates/whatsapp_linked/src/signals/test.rs
@@ -0,0 +1,24 @@
+use super::Signal;
+use uuid::Uuid;
+
+#[test]
+fn a_signal_reads_only_from_json() {
+ let id = Uuid::now_v7();
+ assert_eq!(
+ Signal::parse(&format!(r#"{{"id":"{id}","traceparent":"00-ab-cd-01"}}"#)),
+ Some(Signal {
+ id,
+ traceparent: Some("00-ab-cd-01".to_owned()),
+ })
+ );
+ assert_eq!(
+ Signal::parse(&format!(r#"{{"id":"{id}"}}"#)),
+ Some(Signal {
+ id,
+ traceparent: None,
+ })
+ );
+ assert_eq!(Signal::parse(&id.to_string()), None);
+ assert_eq!(Signal::parse("not-an-id"), None);
+ assert_eq!(Signal::parse(r#"{"id":"nope"}"#), None);
+}
diff --git a/crates/whatsapp_linked/src/outbound/trace_context.rs b/crates/whatsapp_linked/src/signals/trace_context.rs
similarity index 100%
rename from crates/whatsapp_linked/src/outbound/trace_context.rs
rename to crates/whatsapp_linked/src/signals/trace_context.rs
diff --git a/crates/whatsapp_store_pg/src/error.rs b/crates/whatsapp_store_pg/src/error.rs
index 6ba8f96a87..bf9cf78b6a 100644
--- a/crates/whatsapp_store_pg/src/error.rs
+++ b/crates/whatsapp_store_pg/src/error.rs
@@ -45,6 +45,22 @@ pub enum WhatsAppStoreError {
Database(#[from] sqlx::Error),
}
+impl WhatsAppStoreError {
+ /// Whether the account's stored device can never be read again: KMS
+ /// refused its data key (a lost or replaced key, another context), or the
+ /// device row does not decrypt or parse. Only a fresh device helps; a
+ /// retryable KMS failure is not this.
+ pub fn is_unreadable_device(&self) -> bool {
+ match self {
+ WhatsAppStoreError::Kms(error) => !error.is_retryable(),
+ WhatsAppStoreError::Decrypt
+ | WhatsAppStoreError::Malformed
+ | WhatsAppStoreError::UnsupportedVersion(_) => true,
+ _ => false,
+ }
+ }
+}
+
impl From<WhatsAppStoreError> for StoreError {
fn from(error: WhatsAppStoreError) -> Self {
match error {
diff --git a/crates/whatsapp_store_pg/src/kms.rs b/crates/whatsapp_store_pg/src/kms.rs
index 660874b0df..252b26b03c 100644
--- a/crates/whatsapp_store_pg/src/kms.rs
+++ b/crates/whatsapp_store_pg/src/kms.rs
@@ -53,12 +53,56 @@ impl std::fmt::Debug for GeneratedDataKey {
/// A KMS operation failed.
///
-/// Deliberately opaque: the AWS error can tell "wrong encryption context"
-/// from "no permission", and a caller that can tell them apart can probe. The
-/// detail belongs in CloudTrail.
+/// Deliberately opaque about why KMS refused: the AWS error can tell "wrong
+/// encryption context" from "no permission", and a caller that can tell them
+/// apart can probe. The detail belongs in CloudTrail. It only says whether
+/// trying again can help.
#[derive(Debug, thiserror::Error)]
#[error("whatsapp data key kms operation failed")]
-pub struct WhatsAppKmsError;
+pub struct WhatsAppKmsError {
+ retryable: bool,
+}
+
+impl WhatsAppKmsError {
+ /// KMS answered and refused (wrong key or context, key gone or disabled,
+ /// no permission): the same call fails again.
+ pub const fn refused() -> Self {
+ Self { retryable: false }
+ }
+
+ /// KMS could not be reached or asked to slow down: the call can succeed
+ /// later.
+ pub const fn unavailable() -> Self {
+ Self { retryable: true }
+ }
+
+ /// Whether the same call can succeed later.
+ pub const fn is_retryable(&self) -> bool {
+ self.retryable
+ }
+
+ /// Classifies an AWS SDK failure: throttling, KMS-side outages and
+ /// transport failures are retryable; every other service error is a
+ /// refusal.
+ fn from_sdk<Error, Response>(error: &aws_sdk_kms::error::SdkError<Error, Response>) -> Self
+ where
+ Error: aws_sdk_kms::error::ProvideErrorMetadata,
+ {
+ use aws_sdk_kms::error::SdkError;
+ match error {
+ SdkError::ServiceError(service) => match service.err().code() {
+ Some(
+ "ThrottlingException"
+ | "KMSInternalException"
+ | "DependencyTimeoutException"
+ | "KeyUnavailableException",
+ ) => Self::unavailable(),
+ _ => Self::refused(),
+ },
+ _ => Self::unavailable(),
+ }
+ }
+}
/// The KMS operations the store needs, as a seam tests can stand in for.
pub trait WhatsAppKms: Send + Sync {
@@ -128,15 +172,17 @@ impl WhatsAppKms for AwsWhatsAppKms {
.set_encryption_context(Some(encryption_context))
.send()
.await
- .map_err(|_| WhatsAppKmsError)?;
- let plaintext = response.plaintext.ok_or(WhatsAppKmsError)?;
- let ciphertext = response.ciphertext_blob.ok_or(WhatsAppKmsError)?;
+ .map_err(|error| WhatsAppKmsError::from_sdk(&error))?;
+ let plaintext = response.plaintext.ok_or(WhatsAppKmsError::refused())?;
+ let ciphertext = response
+ .ciphertext_blob
+ .ok_or(WhatsAppKmsError::refused())?;
Ok(GeneratedDataKey {
plaintext: Zeroizing::new(plaintext.into_inner()),
ciphertext: ciphertext.into_inner(),
// The response names the fully qualified ARN even when the
// configured id is an alias, which is what the row records.
- kms_key_id: response.key_id.ok_or(WhatsAppKmsError)?,
+ kms_key_id: response.key_id.ok_or(WhatsAppKmsError::refused())?,
})
}
@@ -158,8 +204,8 @@ impl WhatsAppKms for AwsWhatsAppKms {
.set_encryption_context(Some(encryption_context))
.send()
.await
- .map_err(|_| WhatsAppKmsError)?;
- let plaintext = response.plaintext.ok_or(WhatsAppKmsError)?;
+ .map_err(|error| WhatsAppKmsError::from_sdk(&error))?;
+ let plaintext = response.plaintext.ok_or(WhatsAppKmsError::refused())?;
Ok(Zeroizing::new(plaintext.into_inner()))
}
}
diff --git a/crates/whatsapp_store_pg/src/kms/fake.rs b/crates/whatsapp_store_pg/src/kms/fake.rs
index d10fe1121b..4d86ff74fe 100644
--- a/crates/whatsapp_store_pg/src/kms/fake.rs
+++ b/crates/whatsapp_store_pg/src/kms/fake.rs
@@ -74,7 +74,7 @@ impl WhatsAppKms for FakeWhatsAppKms {
aad: &Self::associated_data(encryption_context),
},
)
- .map_err(|_| WhatsAppKmsError)?;
+ .map_err(|_| WhatsAppKmsError::refused())?;
Ok(GeneratedDataKey {
plaintext: Zeroizing::new(plaintext.to_vec()),
ciphertext: [nonce.as_slice(), &wrapped].concat(),
@@ -90,11 +90,11 @@ impl WhatsAppKms for FakeWhatsAppKms {
) -> Result<Zeroizing<Vec<u8>>, WhatsAppKmsError> {
self.decrypt_calls.fetch_add(1, Ordering::SeqCst);
if kms_key_id != self.kms_key_id {
- return Err(WhatsAppKmsError);
+ return Err(WhatsAppKmsError::refused());
}
let (nonce, wrapped) = ciphertext
.split_first_chunk::<NONCE_LENGTH>()
- .ok_or(WhatsAppKmsError)?;
+ .ok_or(WhatsAppKmsError::refused())?;
let plaintext = self
.wrapping_key
.decrypt(
@@ -104,7 +104,7 @@ impl WhatsAppKms for FakeWhatsAppKms {
aad: &Self::associated_data(encryption_context),
},
)
- .map_err(|_| WhatsAppKmsError)?;
+ .map_err(|_| WhatsAppKmsError::refused())?;
Ok(Zeroizing::new(plaintext))
}
}
diff --git a/crates/whatsapp_store_pg/src/store.rs b/crates/whatsapp_store_pg/src/store.rs
index 8a7694c850..84b8e4e14c 100644
--- a/crates/whatsapp_store_pg/src/store.rs
+++ b/crates/whatsapp_store_pg/src/store.rs
@@ -137,6 +137,43 @@ impl PgWhatsAppStore {
})
}
+ /// Deletes the account's device without opening it, so a device whose data
+ /// key KMS no longer unwraps can still be replaced. Every key, session
+ /// and value goes with it (they cascade); the next [`Self::open`]
+ /// generates a new data key. Returns whether there was a device.
+ ///
+ /// # Errors
+ /// [`WhatsAppStoreError::Fenced`] when the account's epoch is not
+ /// `lease_epoch`, and database errors.
+ #[tracing::instrument(
+ name = "whatsapp_store.reset_device",
+ skip(pool),
+ fields(account_id = %account_id, lease_epoch, deleted),
+ err
+ )]
+ pub async fn reset_device(
+ pool: &PgPool,
+ account_id: Uuid,
+ lease_epoch: i64,
+ ) -> Result<bool, WhatsAppStoreError> {
+ let mut transaction = pool.begin().await?;
+ check_lease(&mut transaction, account_id, lease_epoch).await?;
+ let deleted = sqlx::query!(
+ r#"
+ DELETE FROM whatsapp_device
+ WHERE account_id = $1
+ "#,
+ account_id,
+ )
+ .execute(&mut *transaction)
+ .await?
+ .rows_affected()
+ > 0;
+ transaction.commit().await?;
+ tracing::Span::current().record("deleted", deleted);
+ Ok(deleted)
+ }
+
/// The account this store belongs to.
pub fn account_id(&self) -> Uuid {
self.account_id
diff --git a/crates/whatsapp_store_pg/src/store/test.rs b/crates/whatsapp_store_pg/src/store/test.rs
index 27fa59e217..3afbfa9061 100644
--- a/crates/whatsapp_store_pg/src/store/test.rs
+++ b/crates/whatsapp_store_pg/src/store/test.rs
@@ -361,6 +361,60 @@ async fn a_data_key_does_not_unwrap_for_another_owner_or_kms_key(pool: Pool<Post
assert!(matches!(error, WhatsAppStoreError::Kms(_)), "{error:?}");
}
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_device_whose_key_kms_lost_is_reset_without_unwrapping_it(pool: Pool<Postgres>) {
+ let account_id = insert_account(&pool, "macro|lost-key").await;
+ let lost = FakeWhatsAppKms::new(KMS_KEY_ID);
+ PgWhatsAppStore::open(pool.clone(), account_id, 0, &lost)
+ .await
+ .unwrap()
+ .put_session("111:0", b"session".to_vec())
+ .await
+ .unwrap();
+
+ // KMS lost the wrapping key (a new LocalStack, a deleted key): the stored
+ // data key never unwraps again, and the failure says so.
+ let kms = FakeWhatsAppKms::new(KMS_KEY_ID);
+ let error = PgWhatsAppStore::open(pool.clone(), account_id, 0, &kms)
+ .await
+ .unwrap_err();
+ assert!(error.is_unreadable_device(), "{error:?}");
+
+ // A replica that lost the lease cannot reset it.
+ let error = PgWhatsAppStore::reset_device(&pool, account_id, 1)
+ .await
+ .unwrap_err();
+ assert!(matches!(error, WhatsAppStoreError::Fenced), "{error:?}");
+
+ assert!(
+ PgWhatsAppStore::reset_device(&pool, account_id, 0)
+ .await
+ .unwrap()
+ );
+ assert!(
+ !PgWhatsAppStore::reset_device(&pool, account_id, 0)
+ .await
+ .unwrap(),
+ "nothing left to reset"
+ );
+ assert_eq!(kms.decrypt_calls(), 1, "resetting never calls KMS");
+ let fresh = PgWhatsAppStore::open(pool.clone(), account_id, 0, &kms)
+ .await
+ .unwrap();
+ assert_eq!(kms.generate_calls(), 1);
+ assert_eq!(fresh.get_session("111:0").await.unwrap(), None);
+}
+
+#[test]
+fn only_refusals_and_undecryptable_devices_are_unreadable() {
+ use crate::kms::WhatsAppKmsError;
+ assert!(WhatsAppStoreError::Kms(WhatsAppKmsError::refused()).is_unreadable_device());
+ assert!(!WhatsAppStoreError::Kms(WhatsAppKmsError::unavailable()).is_unreadable_device());
+ assert!(WhatsAppStoreError::Decrypt.is_unreadable_device());
+ assert!(WhatsAppStoreError::UnsupportedVersion(2).is_unreadable_device());
+ assert!(!WhatsAppStoreError::Fenced.is_unreadable_device());
+}
+
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn an_unknown_encryption_version_is_refused_before_calling_kms(pool: Pool<Postgres>) {
let kms = FakeWhatsAppKms::new(KMS_KEY_ID);
diff --git a/deny.toml b/deny.toml
index 617a359c98..f289ada649 100644
--- a/deny.toml
+++ b/deny.toml
@@ -251,6 +251,7 @@ deny = [
"tracing-tree",
"tracing-web", # External WASM tracing layer
"turso_core", # External Turso crate requires tracing-subscriber directly
+ "whatsapp_session_service", # Notification span propagation test only
"whatsmeow", # Span hierarchy and JID-redaction tests only
"worker-rs-otel", # Cloudflare/WASM OpenTelemetry integration
"workspace-hack", # cargo-hakari generated crate
diff --git a/docs/agent-guide/external.md b/docs/agent-guide/external.md
index 9557f302c6..b6120d1717 100644
--- a/docs/agent-guide/external.md
+++ b/docs/agent-guide/external.md
@@ -11,19 +11,24 @@ it on locally with `VITE_ENABLE_WHATSAPP_LINKED=true`.
- Desktop: the **External** plug button on the sidebar rail (shown by default,
hideable in **More → Customize sidebar**), or `g x`, or **Go to External** in
the command menu.
-- Mobile: **More views → External**. It never takes a dock slot and has no
- back button, like other navigation views; the External sidebar is hidden on
- touch, so the WhatsApp page fills the pane with its added **Groups** first. Opening a
+- Mobile: **External** in the bottom dock (or **More views → External** when
+ the dock is full). It has no back button, like other navigation views; the
+ External sidebar is hidden on touch, so the WhatsApp page fills the pane with its **In Macro** chats first. Opening a
group drills in full-screen; its **Back to WhatsApp** button returns.
## Sidebar
Desktop's External sidebar has **WhatsApp** (the page below) with every
WhatsApp chat the viewer can read (their own and shared ones; a person icon for
-direct chats, a group icon for groups) nested under it,
-each with its unread count and a **Read-only** tag when the viewer's WhatsApp
-can't send there. The caret on WhatsApp folds the groups; folded, WhatsApp shows
-their total unread count. The open group's row is highlighted.
+direct chats, a group icon for groups) nested under it in folding sections like
+Chat's rail: **Direct messages**, **Groups**, and **Communities** with one
+section per community (its groups by their own name, its announcement group as
+"Announcements"), each newest activity first. Rows show the unread count and a
+**Read-only** tag when the viewer's WhatsApp can't send there; a folded section
+shows its unread total, and folded sections are remembered per person. The
+caret on WhatsApp folds everything; folded, WhatsApp shows the total unread
+count. The open group's row is highlighted. On phones the page starts with the
+same sections under **In Macro**.
DSS's `whatsapp_changed` gateway events refresh the lists; without one, External
re-fetches once ~3 s after opening.
@@ -31,14 +36,15 @@ re-fetches once ~3 s after opening.
| State | What shows |
| --- | --- |
-| Not linked | Outlined WhatsApp row, the unofficial-client account-risk note, **Connect** (disabled with a tooltip when the server turns pairing off). A signed-out device reads **Reconnect**. |
+| Not linked | Outlined WhatsApp row, the unofficial-client account-risk note, **Connect** (disabled with a tooltip when the server turns pairing off). A signed-out device reads **Reconnect**. A phone can't scan its own screen, so at phone width (touch, under 640px) there is no **Connect**; the row says to open Macro on a computer and scan its code with the phone. Tablets keep **Connect**. |
| Passkey | When WhatsApp asks for a passkey, the dialog says **Confirm on your desktop**. In Macro desktop, **Confirm with passkey** runs the native `whatsapp_passkey_authenticate` command (its caBLE QR shows in the dialog) and posts the assertion to `pairing/<id>/passkey`; a returned code then shows to type on the phone. In a browser, **Continue in Macro desktop** opens `macro:///external?whatsappPairing=<id>`, which reopens the same pairing there; closing the browser dialog then doesn't cancel it. |
-| Pairing | Dialog **Link WhatsApp**: a locally encoded QR (`role="img"`, name "Scan this code with WhatsApp on your phone"), **Expires in m:ss**, four numbered steps, **Cancel**. The dialog carries `ph-no-capture`. A code confirmation step shows **The codes match**; expiry or failure shows **Show a new code**. |
-| Linked | A full-width list like Drive's. Its header has **Search chats** (filters every section by name or phone digits) and a slim account strip: the phone number, "Connected" and a **WhatsApp account options** menu with **Disconnect** (asks to confirm). One account at a time: to switch, disconnect and connect again. Below, the account's WhatsApp chat list (`GET chats`), newest activity first, one line per chat: a group, person or (announcement group) megaphone icon, the name ("Community · Group", or "Community · Announcements"), "Group" / "Community group" / "Announcement group" / "Direct chat · Archived", and the last activity on the right. Row actions show on hover or keyboard focus (always on touch). While searching, **In Macro** lists matching added groups with **Open** (otherwise they are only in the sidebar). **Add to Macro**: addable chats (direct chats, community groups and disappearing-message groups included), with a one-click **Add to Macro** (no dialog, no name: the Macro group follows the WhatsApp name; unnamed groups show member names), and groups someone already shared with the viewer as "Shared with you by <owner>" with **Open**. **Can't be added (n)** is collapsed (searching unfolds it) and lists the chat with yourself, communities themselves ("A community has no messages of its own; add one of its groups"), and groups the account left, with DSS's reason. A refused add shows DSS's specific reason in that chat's row. An account paired before the chat list existed shows only groups and chats with new messages until it is re-linked. |
+| Pairing | Dialog **Link WhatsApp**: a locally encoded QR (`role="img"`, name "Scan this code with WhatsApp on your phone") that follows WhatsApp's rotating codes, four numbered steps, **Cancel**. The dialog carries `ph-no-capture`. When a pairing expires (WhatsApp ran out of codes, ~2.7 minutes, or the 5-minute deadline) while the tab stays visible, the dialog shows **Refreshing code…** and starts a new pairing on its own, up to three times; after that, or if the tab was hidden, the QR square reads **Code expired** with **Show a new code**. A failure (not expiry) says **Linking didn't finish.** with **Show a new code**. |
+| Linked | A full-width list like Drive's. Its header has **Search chats** (filters every section by name or phone digits) and a slim account strip: the phone number, "Connected" and a **WhatsApp account options** menu with **Disconnect** (asks to confirm). One account at a time: to switch, disconnect and connect again. Below, the account's WhatsApp chat list (`GET chats`), newest activity first, one line per chat: a group, person or (announcement group) megaphone icon, the name ("Community · Group", or "Community · Announcements"), "Group" / "Community group" / "Announcement group" / "Direct chat · Archived", and the last activity on the right. Row actions show on hover or keyboard focus (always on touch). Chats sit in folding sections like the sidebar's (**Direct messages**, **Groups**, **Communities** with one section per community), remembered per person; a search opens every section and also lists matching added chats with **Open** (otherwise they are only in the sidebar). Addable chats (direct chats, community groups and disappearing-message groups included) have a one-click **Add to Macro** (no dialog, no name: the Macro group follows the WhatsApp name; unnamed groups show member names), and groups someone already shared with the viewer as "Shared with you by <owner>" with **Open**. **Can't be added (n)** is collapsed (searching unfolds it) and lists the chat with yourself, communities themselves ("A community has no messages of its own; add one of its groups"), and groups the account left, each with its reason. A refused add shows DSS's specific reason in that chat's row. An account paired before the chat list existed shows only groups and chats with new messages until it is re-linked. |
Cancel sends `DELETE /meta/linked/pairing/<id>`; closing after the phone links
-does not. Disconnect that WhatsApp did not confirm tells the person to remove
-Macro under Linked devices on their phone.
+does not; closing while a new code is starting cancels that pairing too.
+Disconnect results show as a toast; one WhatsApp did not confirm tells the
+person to remove Macro under Linked devices on their phone.
## Driving it without a WhatsApp backend
@@ -54,8 +60,8 @@ automated run.
A group and a direct (one-to-one) chat open in the same view; API routes and
the `whatsapp_group` entity type keep "group" for both, user-facing copy says
-"chat". A direct chat's header is the person (no **N members** button, no
-roster); only its owner can send, and anyone it's shared with reads "Only
+"chat". A direct chat's header is the person and its details have no **Members**;
+only its owner can send, and anyone it's shared with reads "Only
<owner> can reply in this chat" in place of the composer.
Open the adopted group from External's sidebar or a shared link at
@@ -96,8 +102,16 @@ call"): no avatar, no actions, never unread. View-once media show like any
media; unknown types keep DSS's placeholder text. The header has the group name ("Community · Group"
for a community's group), a timer icon when WhatsApp's disappearing messages
are on (the timeline's start also says "Disappearing messages are on in
-WhatsApp (7 days). Macro keeps them."), a **N members** button that
-toggles the WhatsApp roster, and **Share**. The layout supports phone-width panes.
+WhatsApp (7 days). Macro keeps them."), **Share**, and the standard side panel
+toggle (**Show Side Panel**, `]`; **Show details** on touch). Like an in-view
+email thread, the details float over the timeline (`aside[aria-label="Block
+details"]`, outside click or the toggle closes them, starts closed; on a
+pane 900px or wider the timeline and composer move left to make room) and are a
+bottom sheet on touch. Sections: **Members (n)** (groups only; list
+`WhatsApp members`, you first, then admins, then by name, each with number and
+an **Admin** badge, a search box past 12), **Sharing** (**Share…** opens the
+same share dialog), **Syncing** (owner only: **Stop syncing** asks to confirm),
+and "Owned by <owner>". The layout supports phone-width panes.
The composer placeholder names the caller's own sending phone ("Message Test 11
as +1…"); otherwise the reason replies are unavailable shows in its place. Sending requires view access, the caller's own connected account,
@@ -110,13 +124,16 @@ them. Text/media/replies,
reactions, and edits/deletes of the caller's own recent messages use
`POST /meta/linked/whatsapp-groups/<id>/sends`; files stage through `/attachments`.
The detail's `limits` supplies allowed MIME types, bytes and the edit window.
-The owner may stop syncing with `DELETE` on the group; history remains readable.
+The owner may stop syncing (details → **Syncing**, groups and direct chats) with
+`DELETE` on the group; history remains readable.
After adding, DSS imports earlier messages from the owner's phone (up to 500
messages or 90 days). The detail's `backfill` drives the header's subtitle:
**WhatsApp · Importing history…** while `pending`/`running`, **WhatsApp · Waiting
for your phone to import history** (or *the owner's phone* for shared viewers)
-while `waiting_for_phone`; the same line shows above the oldest message. Imported
+while `waiting_for_phone`; the same line shows above the oldest message.
+`waiting_for_message` (nobody has posted since adding, so nothing to import
+from yet) shows nothing; the first message starts the import. Imported
messages appear older than what is shown as each page lands (pushed as
`whatsapp_changed`), without moving the viewer's scroll position. `done` is
silent; `partial` leaves **Earlier messages stay in WhatsApp** above the oldest
diff --git a/docs/architecture/whatsapp-linked-devices.md b/docs/architecture/whatsapp-linked-devices.md
index 8cc1853a65..a4cc7ef304 100644
--- a/docs/architecture/whatsapp-linked-devices.md
+++ b/docs/architecture/whatsapp-linked-devices.md
@@ -110,14 +110,19 @@ them apart.
An account paired before the list existed only gets groups and chats with new
messages: WhatsApp sends the full list once, at pairing.
-Adding a group sets `backfill_state = 'pending'`. The owner's account then
+Adding a group sets `backfill_state = 'pending'` when a message of the chat is
+known to start from (the chat list's anchor, or a stored message the account
+saw), else `waiting_for_message`: nothing to import from until someone posts.
+The chat's first message (live, history sync or chat-list update) makes it
+`pending` and starts the import at once. The owner's account then
imports the chat's earlier messages from the phone, on demand only: it asks for
the anchor message itself when it predates adoption (a placeholder resend) and
for pages of 50 messages before the oldest imported one (history sync on
demand), until the phone has nothing older (`done`) or 500 messages / 90 days
(`partial`). An unanswered request (60 s) means `waiting_for_phone`, retried
-every 5 minutes and at once on reconnect; a chat without an anchor waits for its
-first live message. Imported messages are ingested as history (origin
+every 5 minutes and at once on reconnect. WhatsApp's group info carries no
+message id, so a quiet chat of an account paired before the chat list existed
+has no other anchor. Imported messages are ingested as history (origin
`history`): no notifications, no unread, deduplicated with live messages by
source id, and only into the owner's own groups, which replaces the
adoption-time boundary for them.
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/README.md b/packages/sdk-docs/reference/generated/storage/types.gen/README.md
index 274dbaa5af..1c5392c0d0 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/README.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/README.md
@@ -1379,9 +1379,7 @@
- [LinkedDisconnectResponse](type-aliases/LinkedDisconnectResponse.md)
- [LinkedDisconnectResponses](type-aliases/LinkedDisconnectResponses.md)
- [LinkedFeatures](type-aliases/LinkedFeatures.md)
-- [LinkedGroupInfo](type-aliases/LinkedGroupInfo.md)
- [LinkedGroupReference](type-aliases/LinkedGroupReference.md)
-- [LinkedIdentity](type-aliases/LinkedIdentity.md)
- [LinkedMediaKind](type-aliases/LinkedMediaKind.md)
- [LinkedMediaPresentation](type-aliases/LinkedMediaPresentation.md)
- [LinkedMessageAttachments](type-aliases/LinkedMessageAttachments.md)
@@ -1395,7 +1393,6 @@
- [LinkedPairingResponses](type-aliases/LinkedPairingResponses.md)
- [LinkedPairingState](type-aliases/LinkedPairingState.md)
- [LinkedPairState](type-aliases/LinkedPairState.md)
-- [LinkedParticipant](type-aliases/LinkedParticipant.md)
- [LinkedPasskeyData](type-aliases/LinkedPasskeyData.md)
- [LinkedPasskeyResponse](type-aliases/LinkedPasskeyResponse.md)
- [LinkedPasskeyResponses](type-aliases/LinkedPasskeyResponses.md)
@@ -2259,6 +2256,9 @@
- [WhatsappGroupData](type-aliases/WhatsappGroupData.md)
- [WhatsAppGroupDetail](type-aliases/WhatsAppGroupDetail.md)
- [WhatsAppGroupMessage](type-aliases/WhatsAppGroupMessage.md)
+- [WhatsappGroupMessageData](type-aliases/WhatsappGroupMessageData.md)
+- [WhatsappGroupMessageResponse](type-aliases/WhatsappGroupMessageResponse.md)
+- [WhatsappGroupMessageResponses](type-aliases/WhatsappGroupMessageResponses.md)
- [WhatsAppGroupMessages](type-aliases/WhatsAppGroupMessages.md)
- [WhatsappGroupMessagesData](type-aliases/WhatsappGroupMessagesData.md)
- [WhatsappGroupMessagesResponse](type-aliases/WhatsappGroupMessagesResponse.md)
@@ -2286,10 +2286,12 @@
- [WhatsAppLocation](type-aliases/WhatsAppLocation.md)
- [WhatsAppMention](type-aliases/WhatsAppMention.md)
- [WhatsAppMessageKind](type-aliases/WhatsAppMessageKind.md)
+- [WhatsAppParticipant](type-aliases/WhatsAppParticipant.md)
- [WhatsAppPersonRef](type-aliases/WhatsAppPersonRef.md)
- [WhatsAppPoll](type-aliases/WhatsAppPoll.md)
- [WhatsAppPollOption](type-aliases/WhatsAppPollOption.md)
- [WhatsAppRichContent](type-aliases/WhatsAppRichContent.md)
+- [WhatsAppRoster](type-aliases/WhatsAppRoster.md)
- [WhatsAppSystemAction](type-aliases/WhatsAppSystemAction.md)
- [WhatsAppSystemLine](type-aliases/WhatsAppSystemLine.md)
- [Widget](type-aliases/Widget.md)
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/AdoptedGroup.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/AdoptedGroup.md
index bd16560083..b2d63ea3b9 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/AdoptedGroup.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/AdoptedGroup.md
@@ -1,6 +1,6 @@
# Type Alias: AdoptedGroup
-> **AdoptedGroup** = \{ `group_id`: `string`; \}
+> **AdoptedGroup** = \{ `groupId`: `string`; \}
Adoption response.
@@ -8,4 +8,4 @@ Adoption response.
| Property | Type | Description |
| ------ | ------ | ------ |
-| <a id="property-group_id"></a> `group_id` | `string` | Shareable entity identifier. |
+| <a id="property-groupid"></a> `groupId` | `string` | Shareable entity identifier. |
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedAccount.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedAccount.md
index fa8441aad8..d9eff487df 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedAccount.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedAccount.md
@@ -1,6 +1,6 @@
# Type Alias: LinkedAccount
-> **LinkedAccount** = \{ `authorization_generation`: `number`; `id`: `string`; `identity_jid?`: `string` \| `null`; `state`: [`LinkedAccountState`](LinkedAccountState.md); `user_id`: `string`; \}
+> **LinkedAccount** = \{ `authorizationGeneration`: `number`; `id`: `string`; `identityJid?`: `string` \| `null`; `state`: [`LinkedAccountState`](LinkedAccountState.md); `userId`: `string`; \}
One person's account, never owned by a workspace.
@@ -8,8 +8,8 @@ One person's account, never owned by a workspace.
| Property | Type | Description |
| ------ | ------ | ------ |
-| <a id="property-authorization_generation"></a> `authorization_generation` | `number` | Explicit consent generation; reconnecting a socket never changes it. |
+| <a id="property-authorizationgeneration"></a> `authorizationGeneration` | `number` | Explicit consent generation; reconnecting a socket never changes it. |
| <a id="property-id"></a> `id` | `string` | Stable account identity. |
-| <a id="property-identity_jid"></a> `identity_jid?` | `string` \| `null` | WhatsApp-verified identity, absent until the first pairing succeeds. |
+| <a id="property-identityjid"></a> `identityJid?` | `string` \| `null` | WhatsApp-verified identity, absent until the first pairing succeeds. |
| <a id="property-state"></a> `state` | [`LinkedAccountState`](LinkedAccountState.md) | Lifecycle. |
-| <a id="property-user_id"></a> `user_id` | `string` | Authenticated owner. |
+| <a id="property-userid"></a> `userId` | `string` | Authenticated owner. |
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedAdoptGroup.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedAdoptGroup.md
index e857850838..188ba8b992 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedAdoptGroup.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedAdoptGroup.md
@@ -1,6 +1,6 @@
# Type Alias: LinkedAdoptGroup
-> **LinkedAdoptGroup** = \{ `group_jid`: `string`; \}
+> **LinkedAdoptGroup** = \{ `groupJid`: `string`; \}
Explicit adoption request; the account is selected server-side. The
group's name always follows WhatsApp.
@@ -9,4 +9,4 @@ group's name always follows WhatsApp.
| Property | Type | Description |
| ------ | ------ | ------ |
-| <a id="property-group_jid"></a> `group_jid` | `string` | A group the requester's account has joined, or a direct chat from their chat list (the other person's JID, as the list names it). |
+| <a id="property-groupjid"></a> `groupJid` | `string` | A group the requester's account has joined, or a direct chat from their chat list (the other person's JID, as the list names it). |
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedAttachment.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedAttachment.md
index 8481457f4b..3da7210bb3 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedAttachment.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedAttachment.md
@@ -1,6 +1,6 @@
# Type Alias: LinkedAttachment
-> **LinkedAttachment** = \{ `document_id?`: `string` \| `null`; `duration_seconds?`: `number` \| `null`; `file_name`: `string`; `height?`: `number` \| `null`; `mime`: `string`; `ordinal`: `number`; `presentation?`: `null` \| [`LinkedMediaPresentation`](LinkedMediaPresentation.md); `size`: `number`; `state`: [`LinkedAttachmentState`](LinkedAttachmentState.md); `width?`: `number` \| `null`; \}
+> **LinkedAttachment** = \{ `documentId?`: `string` \| `null`; `durationSeconds?`: `number` \| `null`; `fileName`: `string`; `height?`: `number` \| `null`; `mime`: `string`; `ordinal`: `number`; `presentation?`: `null` \| [`LinkedMediaPresentation`](LinkedMediaPresentation.md); `size`: `number`; `state`: [`LinkedAttachmentState`](LinkedAttachmentState.md); `width?`: `number` \| `null`; \}
One attachment of a linked message.
@@ -8,9 +8,9 @@ One attachment of a linked message.
| Property | Type | Description |
| ------ | ------ | ------ |
-| <a id="property-document_id"></a> `document_id?` | `string` \| `null` | The private document, once ready. |
-| <a id="property-duration_seconds"></a> `duration_seconds?` | `number` \| `null` | Length of audio or video in whole seconds, when declared. |
-| <a id="property-file_name"></a> `file_name` | `string` | Display filename. |
+| <a id="property-documentid"></a> `documentId?` | `string` \| `null` | The private document, once ready. |
+| <a id="property-durationseconds"></a> `durationSeconds?` | `number` \| `null` | Length of audio or video in whole seconds, when declared. |
+| <a id="property-filename"></a> `fileName` | `string` | Display filename. |
| <a id="property-height"></a> `height?` | `number` \| `null` | Pixel height, when declared. |
| <a id="property-mime"></a> `mime` | `string` | Declared MIME type. |
| <a id="property-ordinal"></a> `ordinal` | `number` | Position within the message. |
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedBackfillState.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedBackfillState.md
index 69bdf6e640..ec9015699c 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedBackfillState.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedBackfillState.md
@@ -1,5 +1,5 @@
# Type Alias: LinkedBackfillState
-> **LinkedBackfillState** = `"pending"` \| `"running"` \| `"waiting_for_phone"` \| `"done"` \| `"partial"`
+> **LinkedBackfillState** = `"waiting_for_message"` \| `"pending"` \| `"running"` \| `"waiting_for_phone"` \| `"done"` \| `"partial"`
Where importing a group's earlier messages stands.
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedCapabilities.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedCapabilities.md
index 9338947b52..8ba23b1449 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedCapabilities.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedCapabilities.md
@@ -1,6 +1,6 @@
# Type Alias: LinkedCapabilities
-> **LinkedCapabilities** = \{ `attachment_limit_bytes`: `number`; `attachment_types`: `string`[]; `max_attachments`: `number`; `mutation_window_seconds`: `number`; `mutations`: [`LinkedMutation`](LinkedMutation.md)[]; `text_limit_bytes`: `number`; \}
+> **LinkedCapabilities** = \{ `attachmentLimitBytes`: `number`; `attachmentTypes`: `string`[]; `maxAttachments`: `number`; `mutations`: [`LinkedMutation`](LinkedMutation.md)[]; `mutationWindowSeconds`: `number`; `textLimitBytes`: `number`; \}
Operations implemented for linked groups, independent of current permission.
@@ -8,9 +8,9 @@ Operations implemented for linked groups, independent of current permission.
| Property | Type | Description |
| ------ | ------ | ------ |
-| <a id="property-attachment_limit_bytes"></a> `attachment_limit_bytes` | `number` | Largest attachment in bytes. |
-| <a id="property-attachment_types"></a> `attachment_types` | `string`[] | Supported attachment MIME types. |
-| <a id="property-max_attachments"></a> `max_attachments` | `number` | Attachments per send. |
-| <a id="property-mutation_window_seconds"></a> `mutation_window_seconds` | `number` | Edits and deletes are offered this long after sending. |
+| <a id="property-attachmentlimitbytes"></a> `attachmentLimitBytes` | `number` | Largest attachment in bytes. |
+| <a id="property-attachmenttypes"></a> `attachmentTypes` | `string`[] | Supported attachment MIME types. |
+| <a id="property-maxattachments"></a> `maxAttachments` | `number` | Attachments per send. |
| <a id="property-mutations"></a> `mutations` | [`LinkedMutation`](LinkedMutation.md)[] | Supported message operations. |
-| <a id="property-text_limit_bytes"></a> `text_limit_bytes` | `number` | Maximum UTF-8 bytes per text send. |
+| <a id="property-mutationwindowseconds"></a> `mutationWindowSeconds` | `number` | Edits and deletes are offered this long after sending. |
+| <a id="property-textlimitbytes"></a> `textLimitBytes` | `number` | Maximum UTF-8 bytes per text send. |
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedDeliveryState.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedDeliveryState.md
index 035d86e2bb..d708f955fc 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedDeliveryState.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedDeliveryState.md
@@ -1,6 +1,6 @@
# Type Alias: LinkedDeliveryState
-> **LinkedDeliveryState** = `"pending"` \| `"sending"` \| `"unknown"` \| `"accepted"` \| `"sent"` \| `"delivered"` \| `"read"` \| `"failed"`
+> **LinkedDeliveryState** = `"pending"` \| `"sending"` \| `"unknown"` \| `"accepted"` \| `"failed"`
Observed send state. `unknown` means the request may have reached WhatsApp;
it is never sent again automatically.
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedDisconnect.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedDisconnect.md
index 01796d7b6e..a947a056d8 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedDisconnect.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedDisconnect.md
@@ -1,6 +1,6 @@
# Type Alias: LinkedDisconnect
-> **LinkedDisconnect** = \{ `remote_unlink_requested`: `boolean`; \}
+> **LinkedDisconnect** = \{ `remoteUnlinkRequested`: `boolean`; \}
Result of disconnecting an account.
@@ -8,4 +8,4 @@ Result of disconnecting an account.
| Property | Type | Description |
| ------ | ------ | ------ |
-| <a id="property-remote_unlink_requested"></a> `remote_unlink_requested` | `boolean` | The session service was asked to log the device out of WhatsApp. It unlinks asynchronously; WhatsApp's Linked devices list is authoritative. |
+| <a id="property-remoteunlinkrequested"></a> `remoteUnlinkRequested` | `boolean` | The session service was asked to log the device out of WhatsApp. It unlinks asynchronously; WhatsApp's Linked devices list is authoritative. |
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedDisconnectRequest.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedDisconnectRequest.md
index 30658aa099..c0a188cd80 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedDisconnectRequest.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedDisconnectRequest.md
@@ -1,6 +1,6 @@
# Type Alias: LinkedDisconnectRequest
-> **LinkedDisconnectRequest** = \{ `authorization_generation`: `number`; \}
+> **LinkedDisconnectRequest** = \{ `authorizationGeneration`: `number`; \}
The consent generation the owner deliberately disconnects.
@@ -8,4 +8,4 @@ The consent generation the owner deliberately disconnects.
| Property | Type | Description |
| ------ | ------ | ------ |
-| <a id="property-authorization_generation"></a> `authorization_generation` | `number` | Fences retries against a later reconnect or replacement. |
+| <a id="property-authorizationgeneration"></a> `authorizationGeneration` | `number` | Fences retries against a later reconnect or replacement. |
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedGroupInfo.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedGroupInfo.md
deleted file mode 100644
index cad885c773..0000000000
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedGroupInfo.md
+++ /dev/null
@@ -1,19 +0,0 @@
-# Type Alias: LinkedGroupInfo
-
-> **LinkedGroupInfo** = \{ `announce`: `boolean`; `communityAnnouncements?`: `boolean`; `communityJid?`: `string` \| `null`; `communityParent?`: `boolean`; `disappearingSeconds?`: `number` \| `null`; `jid`: `string`; `name`: `string`; `observedAt`: `string`; `participants`: [`LinkedParticipant`](LinkedParticipant.md)[]; \}
-
-One full metadata read of a group, never an incomplete membership delta.
-
-## Properties
-
-| Property | Type | Description |
-| ------ | ------ | ------ |
-| <a id="property-announce"></a> `announce` | `boolean` | Only admins may post. |
-| <a id="property-communityannouncements"></a> `communityAnnouncements?` | `boolean` | The community's announcement group (everyone reads, admins post). |
-| <a id="property-communityjid"></a> `communityJid?` | `string` \| `null` | The community a linked subgroup or announcement group belongs to. |
-| <a id="property-communityparent"></a> `communityParent?` | `boolean` | The community itself: it has no messages of its own and can't be added. |
-| <a id="property-disappearingseconds"></a> `disappearingSeconds?` | `number` \| `null` | Disappearing-messages timer in seconds while it is on. Macro keeps the messages; its sends carry the timer so phones treat them like their own. |
-| <a id="property-jid"></a> `jid` | `string` | Remote group JID. |
-| <a id="property-name"></a> `name` | `string` | Current subject. |
-| <a id="property-observedat"></a> `observedAt` | `string` | When the session service read this metadata. |
-| <a id="property-participants"></a> `participants` | [`LinkedParticipant`](LinkedParticipant.md)[] | Full roster. |
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedIdentity.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedIdentity.md
deleted file mode 100644
index db8f649621..0000000000
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedIdentity.md
+++ /dev/null
@@ -1,13 +0,0 @@
-# Type Alias: LinkedIdentity
-
-> **LinkedIdentity** = \{ `alternateJid?`: `string` \| `null`; `displayName?`: `string` \| `null`; `jid`: `string`; \}
-
-Verified sender aliases, supplied only by protocol metadata.
-
-## Properties
-
-| Property | Type | Description |
-| ------ | ------ | ------ |
-| <a id="property-alternatejid"></a> `alternateJid?` | `string` \| `null` | Verified alternate identity, never inferred from a name or phone typed by a user. |
-| <a id="property-displayname"></a> `displayName?` | `string` \| `null` | Untrusted display name. |
-| <a id="property-jid"></a> `jid` | `string` | Phone-number or LID account JID. |
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedMessageAttachments.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedMessageAttachments.md
index 0e13351811..bd4bea313e 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedMessageAttachments.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedMessageAttachments.md
@@ -1,6 +1,6 @@
# Type Alias: LinkedMessageAttachments
-> **LinkedMessageAttachments** = \{ `linked_attachments`: [`LinkedAttachment`](LinkedAttachment.md)[]; `message_id`: `string`; \}
+> **LinkedMessageAttachments** = \{ `linkedAttachments`: [`LinkedAttachment`](LinkedAttachment.md)[]; `messageId`: `string`; \}
The attachments of one linked group message.
@@ -8,5 +8,5 @@ The attachments of one linked group message.
| Property | Type | Description |
| ------ | ------ | ------ |
-| <a id="property-linked_attachments"></a> `linked_attachments` | [`LinkedAttachment`](LinkedAttachment.md)[] | Its attachments in order; deleted ones are omitted. |
-| <a id="property-message_id"></a> `message_id` | `string` | Group message. |
+| <a id="property-linkedattachments"></a> `linkedAttachments` | [`LinkedAttachment`](LinkedAttachment.md)[] | Its attachments in order; deleted ones are omitted. |
+| <a id="property-messageid"></a> `messageId` | `string` | Group message. |
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedPairing.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedPairing.md
index 1328617f75..1f78809179 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedPairing.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedPairing.md
@@ -1,6 +1,6 @@
# Type Alias: LinkedPairing
-> **LinkedPairing** = \{ `account_id`: `string`; `expires_at`: `string`; `id`: `string`; `state`: [`LinkedPairingState`](LinkedPairingState.md); \}
+> **LinkedPairing** = \{ `accountId`: `string`; `expiresAt`: `string`; `id`: `string`; `state`: [`LinkedPairingState`](LinkedPairingState.md); \}
Owner-bound pairing transaction, without its QR or pairing code.
@@ -8,7 +8,7 @@ Owner-bound pairing transaction, without its QR or pairing code.
| Property | Type | Description |
| ------ | ------ | ------ |
-| <a id="property-account_id"></a> `account_id` | `string` | Account being connected. |
-| <a id="property-expires_at"></a> `expires_at` | `string` | Database-assigned deadline. |
+| <a id="property-accountid"></a> `accountId` | `string` | Account being connected. |
+| <a id="property-expiresat"></a> `expiresAt` | `string` | Database-assigned deadline. |
| <a id="property-id"></a> `id` | `string` | One-use transaction id. |
| <a id="property-state"></a> `state` | [`LinkedPairingState`](LinkedPairingState.md) | Current state. |
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedParticipant.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedParticipant.md
deleted file mode 100644
index 1b9780779a..0000000000
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedParticipant.md
+++ /dev/null
@@ -1,11 +0,0 @@
-# Type Alias: LinkedParticipant
-
-> **LinkedParticipant** = [`LinkedIdentity`](LinkedIdentity.md) & \{ `admin`: `boolean`; \}
-
-Current remote participant; Macro access is a separate grant.
-
-## Type Declaration
-
-| Name | Type | Description |
-| ------ | ------ | ------ |
-| `admin` | `boolean` | Group admin; only admins post in announcement groups. |
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedReplyContent.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedReplyContent.md
index 81fa116f66..d28d0108a5 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedReplyContent.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedReplyContent.md
@@ -1,6 +1,6 @@
# Type Alias: LinkedReplyContent
-> **LinkedReplyContent** = \{ `mentions?`: `string`[]; `text`: `string`; `type`: `"text"`; \} \| \{ `caption?`: `string` \| `null`; `type`: `"media"`; `upload_id`: `string`; \} \| \{ `message_id`: `string`; `operation`: [`LinkedMutation`](LinkedMutation.md); `text?`: `string` \| `null`; `type`: `"mutation"`; \}
+> **LinkedReplyContent** = \{ `mentions?`: `string`[]; `text`: `string`; `type`: `"text"`; \} \| \{ `caption?`: `string` \| `null`; `type`: `"media"`; `uploadId`: `string`; \} \| \{ `messageId`: `string`; `operation`: [`LinkedMutation`](LinkedMutation.md); `text?`: `string` \| `null`; `type`: `"mutation"`; \}
Content of a deliberate send.
@@ -20,23 +20,23 @@ Content of a deliberate send.
### Type Literal
-\{ `caption?`: `string` \| `null`; `type`: `"media"`; `upload_id`: `string`; \}
+\{ `caption?`: `string` \| `null`; `type`: `"media"`; `uploadId`: `string`; \}
| Name | Type | Description |
| ------ | ------ | ------ |
| `caption?` | `string` \| `null` | Optional caption; audio has none. |
| `type` | `"media"` | - |
-| `upload_id` | `string` | The staged upload, which becomes the message's private document. |
+| `uploadId` | `string` | The staged upload, which becomes the message's private document. |
***
### Type Literal
-\{ `message_id`: `string`; `operation`: [`LinkedMutation`](LinkedMutation.md); `text?`: `string` \| `null`; `type`: `"mutation"`; \}
+\{ `messageId`: `string`; `operation`: [`LinkedMutation`](LinkedMutation.md); `text?`: `string` \| `null`; `type`: `"mutation"`; \}
| Name | Type | Description |
| ------ | ------ | ------ |
-| `message_id` | `string` | Existing group message, resolved to its WhatsApp source by the server. |
+| `messageId` | `string` | Existing group message, resolved to its WhatsApp source by the server. |
| `operation` | [`LinkedMutation`](LinkedMutation.md) | Explicit operation. |
| `text?` | `string` \| `null` | Replacement text or emoji; absent for delete, empty to remove a reaction. |
| `type` | `"mutation"` | - |
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedSendProgress.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedSendProgress.md
index 3edf8a53c8..1a5de23f60 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedSendProgress.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedSendProgress.md
@@ -1,6 +1,6 @@
# Type Alias: LinkedSendProgress
-> **LinkedSendProgress** = \{ `created_at`: `string`; `error_code?`: `string` \| `null`; `group_id`: `string`; `id`: `string`; `message_id?`: `string` \| `null`; `payload`: [`LinkedSendReply`](LinkedSendReply.md); `state`: [`LinkedDeliveryState`](LinkedDeliveryState.md); `user_id`: `string`; \}
+> **LinkedSendProgress** = \{ `createdAt`: `string`; `errorCode?`: `string` \| `null`; `groupId`: `string`; `id`: `string`; `messageId?`: `string` \| `null`; `payload`: [`LinkedSendReply`](LinkedSendReply.md); `state`: [`LinkedDeliveryState`](LinkedDeliveryState.md); `userId`: `string`; \}
Durable result of a deliberate send.
@@ -8,11 +8,11 @@ Durable result of a deliberate send.
| Property | Type | Description |
| ------ | ------ | ------ |
-| <a id="property-created_at"></a> `created_at` | `string` | Intent creation time. |
-| <a id="property-error_code"></a> `error_code?` | `string` \| `null` | Sanitized failure code. |
-| <a id="property-group_id"></a> `group_id` | `string` | Group entity. |
+| <a id="property-createdat"></a> `createdAt` | `string` | Intent creation time. |
+| <a id="property-errorcode"></a> `errorCode?` | `string` \| `null` | Sanitized failure code. |
+| <a id="property-groupid"></a> `groupId` | `string` | Group entity. |
| <a id="property-id"></a> `id` | `string` | Stable intent id. |
-| <a id="property-message_id"></a> `message_id?` | `string` \| `null` | Group message, once WhatsApp accepted it. |
+| <a id="property-messageid"></a> `messageId?` | `string` \| `null` | Group message, once WhatsApp accepted it. |
| <a id="property-payload"></a> `payload` | [`LinkedSendReply`](LinkedSendReply.md) | The original request, so a failed draft can be recovered. |
| <a id="property-state"></a> `state` | [`LinkedDeliveryState`](LinkedDeliveryState.md) | Current state. |
-| <a id="property-user_id"></a> `user_id` | `string` | Person who submitted it. |
+| <a id="property-userid"></a> `userId` | `string` | Person who submitted it. |
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedSendReply.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedSendReply.md
index bd1c4cdd3a..6d0b46dd89 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedSendReply.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedSendReply.md
@@ -1,6 +1,6 @@
# Type Alias: LinkedSendReply
-> **LinkedSendReply** = \{ `idempotency_key`: `string`; `message`: [`LinkedReplyContent`](LinkedReplyContent.md); `reply_to?`: `string` \| `null`; \}
+> **LinkedSendReply** = \{ `idempotencyKey`: `string`; `message`: [`LinkedReplyContent`](LinkedReplyContent.md); `replyTo?`: `string` \| `null`; \}
Explicit send action from a person. Only deliberate sends reach WhatsApp.
@@ -8,6 +8,6 @@ Explicit send action from a person. Only deliberate sends reach WhatsApp.
| Property | Type | Description |
| ------ | ------ | ------ |
-| <a id="property-idempotency_key"></a> `idempotency_key` | `string` | Stable client intent key. A changed payload with this key is a conflict. |
+| <a id="property-idempotencykey"></a> `idempotencyKey` | `string` | Stable client intent key. A changed payload with this key is a conflict. |
| <a id="property-message"></a> `message` | [`LinkedReplyContent`](LinkedReplyContent.md) | Content. |
-| <a id="property-reply_to"></a> `reply_to?` | `string` \| `null` | Group message being quoted, within this group. |
+| <a id="property-replyto"></a> `replyTo?` | `string` \| `null` | Group message being quoted, within this group. |
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedUploadedAttachment.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedUploadedAttachment.md
index 381a99db0f..c074a43985 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedUploadedAttachment.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedUploadedAttachment.md
@@ -1,6 +1,6 @@
# Type Alias: LinkedUploadedAttachment
-> **LinkedUploadedAttachment** = \{ `filename`: `string`; `kind`: [`LinkedMediaKind`](LinkedMediaKind.md); `upload_id`: `string`; \}
+> **LinkedUploadedAttachment** = \{ `filename`: `string`; `kind`: [`LinkedMediaKind`](LinkedMediaKind.md); `uploadId`: `string`; \}
A staged attachment, sent only by a later deliberate send.
@@ -10,4 +10,4 @@ A staged attachment, sent only by a later deliberate send.
| ------ | ------ | ------ |
| <a id="property-filename"></a> `filename` | `string` | Display filename. |
| <a id="property-kind"></a> `kind` | [`LinkedMediaKind`](LinkedMediaKind.md) | Category. |
-| <a id="property-upload_id"></a> `upload_id` | `string` | Use as `upload_id` in a media send; also the future document id. |
+| <a id="property-uploadid"></a> `uploadId` | `string` | Use as `upload_id` in a media send; also the future document id. |
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/MarkRead.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/MarkRead.md
index 3421af354a..505a22295e 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/MarkRead.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/MarkRead.md
@@ -1,6 +1,6 @@
# Type Alias: MarkRead
-> **MarkRead** = \{ `message_id`: `string`; \}
+> **MarkRead** = \{ `messageId`: `string`; \}
Mark messages through this message read.
@@ -8,4 +8,4 @@ Mark messages through this message read.
| Property | Type | Description |
| ------ | ------ | ------ |
-| <a id="property-message_id"></a> `message_id` | `string` | Message in the addressed group. |
+| <a id="property-messageid"></a> `messageId` | `string` | Message in the addressed group. |
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppGroupDetail.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppGroupDetail.md
index f45bb0a8b3..3dfd3d0419 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppGroupDetail.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppGroupDetail.md
@@ -1,6 +1,6 @@
# Type Alias: WhatsAppGroupDetail
-> **WhatsAppGroupDetail** = [`WhatsAppGroupSummary`](WhatsAppGroupSummary.md) & \{ `access_level`: [`AccessLevel`](AccessLevel.md); `community?`: `null` \| [`LinkedCommunityReference`](LinkedCommunityReference.md); `disappearing_seconds?`: `number` \| `null`; `limits`: [`LinkedCapabilities`](LinkedCapabilities.md); `roster?`: `null` \| [`LinkedGroupInfo`](LinkedGroupInfo.md); `sending_identity?`: `string` \| `null`; `share_permission`: [`SharePermissionV2`](SharePermissionV2.md); \}
+> **WhatsAppGroupDetail** = [`WhatsAppGroupSummary`](WhatsAppGroupSummary.md) & \{ `accessLevel`: [`AccessLevel`](AccessLevel.md); `disappearingSeconds?`: `number` \| `null`; `limits`: [`LinkedCapabilities`](LinkedCapabilities.md); `roster?`: `null` \| [`WhatsAppRoster`](WhatsAppRoster.md); `sendingIdentity?`: `string` \| `null`; `sharePermission`: [`SharePermissionV2`](SharePermissionV2.md); \}
Full group detail and current viewer capabilities.
@@ -8,10 +8,9 @@ Full group detail and current viewer capabilities.
| Name | Type | Description |
| ------ | ------ | ------ |
-| `access_level` | [`AccessLevel`](AccessLevel.md) | Caller's effective permission. |
-| `community?` | `null` \| [`LinkedCommunityReference`](LinkedCommunityReference.md) | - |
-| `disappearing_seconds?` | `number` \| `null` | WhatsApp's disappearing-messages timer in seconds while it is on; Macro keeps the messages anyway. `null` when off or unknown. |
+| `accessLevel` | [`AccessLevel`](AccessLevel.md) | Caller's effective permission. |
+| `disappearingSeconds?` | `number` \| `null` | WhatsApp's disappearing-messages timer in seconds while it is on; Macro keeps the messages anyway. `null` when off or unknown. |
| `limits` | [`LinkedCapabilities`](LinkedCapabilities.md) | Size and mutation limits. |
-| `roster?` | `null` \| [`LinkedGroupInfo`](LinkedGroupInfo.md) | - |
-| `sending_identity?` | `string` \| `null` | Caller's own phone identity, never another account's identity. |
-| `share_permission` | [`SharePermissionV2`](SharePermissionV2.md) | Owner-controlled standard sharing configuration. |
+| `roster?` | `null` \| [`WhatsAppRoster`](WhatsAppRoster.md) | - |
+| `sendingIdentity?` | `string` \| `null` | Caller's own phone identity, never another account's identity. |
+| `sharePermission` | [`SharePermissionV2`](SharePermissionV2.md) | Owner-controlled standard sharing configuration. |
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppGroupMessage.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppGroupMessage.md
index ae25dd48c3..af8d4caa57 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppGroupMessage.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppGroupMessage.md
@@ -1,6 +1,6 @@
# Type Alias: WhatsAppGroupMessage
-> **WhatsAppGroupMessage** = \{ `attachments`: [`LinkedAttachment`](LinkedAttachment.md)[]; `body`: `string`; `deleted`: `boolean`; `delivery_state?`: `null` \| [`LinkedDeliveryState`](LinkedDeliveryState.md); `edited_at?`: `string` \| `null`; `forwarded`: `boolean`; `id`: `string`; `kind`: [`WhatsAppMessageKind`](WhatsAppMessageKind.md); `mentions`: [`WhatsAppMention`](WhatsAppMention.md)[]; `reactions`: [`WhatsAppGroupReaction`](WhatsAppGroupReaction.md)[]; `received_at`: `string`; `reply_to?`: `string` \| `null`; `rich?`: `null` \| [`WhatsAppRichContent`](WhatsAppRichContent.md); `sender`: [`WhatsAppGroupSender`](WhatsAppGroupSender.md); `sent_at`: `string`; `view_once`: `boolean`; \}
+> **WhatsAppGroupMessage** = \{ `attachments`: [`LinkedAttachment`](LinkedAttachment.md)[]; `body`: `string`; `deleted`: `boolean`; `deliveryState?`: `null` \| [`LinkedDeliveryState`](LinkedDeliveryState.md); `editedAt?`: `string` \| `null`; `forwarded`: `boolean`; `id`: `string`; `kind`: [`WhatsAppMessageKind`](WhatsAppMessageKind.md); `mentions`: [`WhatsAppMention`](WhatsAppMention.md)[]; `reactions`: [`WhatsAppGroupReaction`](WhatsAppGroupReaction.md)[]; `receivedAt`: `string`; `replyTo?`: `string` \| `null`; `rich?`: `null` \| [`WhatsAppRichContent`](WhatsAppRichContent.md); `sender`: [`WhatsAppGroupSender`](WhatsAppGroupSender.md); `sentAt`: `string`; `viewOnce`: `boolean`; \}
One message in an adopted group.
@@ -11,16 +11,16 @@ One message in an adopted group.
| <a id="property-attachments"></a> `attachments` | [`LinkedAttachment`](LinkedAttachment.md)[] | Imported or pending attachments. |
| <a id="property-body"></a> `body` | `string` | Plain WhatsApp text. |
| <a id="property-deleted"></a> `deleted` | `boolean` | Deleted for everyone. |
-| <a id="property-delivery_state"></a> `delivery_state?` | `null` \| [`LinkedDeliveryState`](LinkedDeliveryState.md) | - |
-| <a id="property-edited_at"></a> `edited_at?` | `string` \| `null` | Last edit timestamp. |
+| <a id="property-deliverystate"></a> `deliveryState?` | `null` \| [`LinkedDeliveryState`](LinkedDeliveryState.md) | - |
+| <a id="property-editedat"></a> `editedAt?` | `string` \| `null` | Last edit timestamp. |
| <a id="property-forwarded"></a> `forwarded` | `boolean` | Forwarded from another chat. |
| <a id="property-id"></a> `id` | `string` | Stable message id. |
| <a id="property-kind"></a> `kind` | [`WhatsAppMessageKind`](WhatsAppMessageKind.md) | A message, or a system line. |
| <a id="property-mentions"></a> `mentions` | [`WhatsAppMention`](WhatsAppMention.md)[] | People the body @-mentions. |
| <a id="property-reactions"></a> `reactions` | [`WhatsAppGroupReaction`](WhatsAppGroupReaction.md)[] | Reactions grouped by emoji. |
-| <a id="property-received_at"></a> `received_at` | `string` | Timestamp first received by Macro. |
-| <a id="property-reply_to"></a> `reply_to?` | `string` \| `null` | Message quoted by this one. |
+| <a id="property-receivedat"></a> `receivedAt` | `string` | Timestamp first received by Macro. |
+| <a id="property-replyto"></a> `replyTo?` | `string` \| `null` | Message quoted by this one. |
| <a id="property-rich"></a> `rich?` | `null` \| [`WhatsAppRichContent`](WhatsAppRichContent.md) | - |
| <a id="property-sender"></a> `sender` | [`WhatsAppGroupSender`](WhatsAppGroupSender.md) | Sender. |
-| <a id="property-sent_at"></a> `sent_at` | `string` | Timestamp assigned by WhatsApp. |
-| <a id="property-view_once"></a> `view_once` | `boolean` | Sent as view-once in WhatsApp; Macro shows it like any media. |
+| <a id="property-sentat"></a> `sentAt` | `string` | Timestamp assigned by WhatsApp. |
+| <a id="property-viewonce"></a> `viewOnce` | `boolean` | Sent as view-once in WhatsApp; Macro shows it like any media. |
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppGroupMessages.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppGroupMessages.md
index a88f919e80..26ae9eb01d 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppGroupMessages.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppGroupMessages.md
@@ -1,6 +1,6 @@
# Type Alias: WhatsAppGroupMessages
-> **WhatsAppGroupMessages** = \{ `messages`: [`WhatsAppGroupMessage`](WhatsAppGroupMessage.md)[]; `next_cursor?`: `string` \| `null`; \}
+> **WhatsAppGroupMessages** = \{ `messages`: [`WhatsAppGroupMessage`](WhatsAppGroupMessage.md)[]; `nextCursor?`: `string` \| `null`; \}
Newest-first timeline page; `before` is the last returned message id.
@@ -9,4 +9,4 @@ Newest-first timeline page; `before` is the last returned message id.
| Property | Type | Description |
| ------ | ------ | ------ |
| <a id="property-messages"></a> `messages` | [`WhatsAppGroupMessage`](WhatsAppGroupMessage.md)[] | Messages in descending sent_at, id order. |
-| <a id="property-next_cursor"></a> `next_cursor?` | `string` \| `null` | Cursor for older messages. |
+| <a id="property-nextcursor"></a> `nextCursor?` | `string` \| `null` | Cursor for older messages. |
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppGroupSender.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppGroupSender.md
index ac9e377ee0..2c2dbfd211 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppGroupSender.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppGroupSender.md
@@ -1,6 +1,6 @@
# Type Alias: WhatsAppGroupSender
-> **WhatsAppGroupSender** = \{ `name`: `string`; `person_id`: `string`; `user_id?`: `string` \| `null`; \}
+> **WhatsAppGroupSender** = \{ `name`: `string`; `personId`: `string`; `userId?`: `string` \| `null`; \}
Message sender from protocol-verified identity evidence.
@@ -9,5 +9,5 @@ Message sender from protocol-verified identity evidence.
| Property | Type | Description |
| ------ | ------ | ------ |
| <a id="property-name"></a> `name` | `string` | Display name, never authentication evidence. |
-| <a id="property-person_id"></a> `person_id` | `string` | External person identity. |
-| <a id="property-user_id"></a> `user_id?` | `string` \| `null` | Verified Macro user association, if present. |
+| <a id="property-personid"></a> `personId` | `string` | External person identity. |
+| <a id="property-userid"></a> `userId?` | `string` \| `null` | Verified Macro user association, if present. |
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppGroupSummary.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppGroupSummary.md
index 6b46e28551..df915b2a67 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppGroupSummary.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppGroupSummary.md
@@ -1,6 +1,6 @@
# Type Alias: WhatsAppGroupSummary
-> **WhatsAppGroupSummary** = \{ `backfill?`: `null` \| [`LinkedBackfill`](LinkedBackfill.md); `can_send`: `boolean`; `id`: `string`; `kind`: [`LinkedChatKind`](LinkedChatKind.md); `last_message_at?`: `string` \| `null`; `name`: `string`; `send_reason?`: `null` \| [`LinkedReplyBlock`](LinkedReplyBlock.md); `unread_count`: `number`; `user_id`: `string`; \}
+> **WhatsAppGroupSummary** = \{ `backfill?`: `null` \| [`LinkedBackfill`](LinkedBackfill.md); `canSend`: `boolean`; `community?`: `null` \| [`LinkedCommunityReference`](LinkedCommunityReference.md); `id`: `string`; `kind`: [`LinkedChatKind`](LinkedChatKind.md); `lastMessageAt?`: `string` \| `null`; `name`: `string`; `sendReason?`: `null` \| [`LinkedReplyBlock`](LinkedReplyBlock.md); `unreadCount`: `number`; `userId`: `string`; \}
Adopted group visible through ordinary entity sharing.
@@ -9,11 +9,12 @@ Adopted group visible through ordinary entity sharing.
| Property | Type | Description |
| ------ | ------ | ------ |
| <a id="property-backfill"></a> `backfill?` | `null` \| [`LinkedBackfill`](LinkedBackfill.md) | - |
-| <a id="property-can_send"></a> `can_send` | `boolean` | Caller may currently send from their own account. |
+| <a id="property-cansend"></a> `canSend` | `boolean` | Caller may currently send from their own account. |
+| <a id="property-community"></a> `community?` | `null` \| [`LinkedCommunityReference`](LinkedCommunityReference.md) | - |
| <a id="property-id"></a> `id` | `string` | Entity identifier. |
| <a id="property-kind"></a> `kind` | [`LinkedChatKind`](LinkedChatKind.md) | A group, or a direct chat with one person (only its owner sends). |
-| <a id="property-last_message_at"></a> `last_message_at?` | `string` \| `null` | Latest message timestamp. |
+| <a id="property-lastmessageat"></a> `lastMessageAt?` | `string` \| `null` | Latest message timestamp. |
| <a id="property-name"></a> `name` | `string` | Display name: the group's, or a direct chat's other person. |
-| <a id="property-send_reason"></a> `send_reason?` | `null` \| [`LinkedReplyBlock`](LinkedReplyBlock.md) | - |
-| <a id="property-unread_count"></a> `unread_count` | `number` | Unread live messages for this viewer. |
-| <a id="property-user_id"></a> `user_id` | `string` | Actual entity owner. |
+| <a id="property-sendreason"></a> `sendReason?` | `null` \| [`LinkedReplyBlock`](LinkedReplyBlock.md) | - |
+| <a id="property-unreadcount"></a> `unreadCount` | `number` | Unread live messages for this viewer, counted up to [`UNREAD_COUNT_CAP`]. |
+| <a id="property-userid"></a> `userId` | `string` | Actual entity owner. |
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppParticipant.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppParticipant.md
new file mode 100644
index 0000000000..c9967a71cd
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppParticipant.md
@@ -0,0 +1,14 @@
+# Type Alias: WhatsAppParticipant
+
+> **WhatsAppParticipant** = \{ `admin`: `boolean`; `alternateJid?`: `string` \| `null`; `displayName?`: `string` \| `null`; `jid`: `string`; \}
+
+Someone in a WhatsApp chat; Macro access is a separate grant.
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-admin"></a> `admin` | `boolean` | Group admin. |
+| <a id="property-alternatejid"></a> `alternateJid?` | `string` \| `null` | The other address WhatsApp verified for them. |
+| <a id="property-displayname"></a> `displayName?` | `string` \| `null` | Their WhatsApp name, untrusted. |
+| <a id="property-jid"></a> `jid` | `string` | Phone-number or LID JID. |
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppRoster.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppRoster.md
new file mode 100644
index 0000000000..1f086eff30
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsAppRoster.md
@@ -0,0 +1,14 @@
+# Type Alias: WhatsAppRoster
+
+> **WhatsAppRoster** = \{ `announce`: `boolean`; `name`: `string`; `observedAt`: `string`; `participants`: [`WhatsAppParticipant`](WhatsAppParticipant.md)[]; \}
+
+A chat's WhatsApp metadata as the caller's account last read it.
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-announce"></a> `announce` | `boolean` | Only admins may post. |
+| <a id="property-name"></a> `name` | `string` | WhatsApp subject. |
+| <a id="property-observedat"></a> `observedAt` | `string` | When this was read from WhatsApp. |
+| <a id="property-participants"></a> `participants` | [`WhatsAppParticipant`](WhatsAppParticipant.md)[] | Everyone in the chat. |
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsappGroupMessageData.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsappGroupMessageData.md
new file mode 100644
index 0000000000..74a1b1f264
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsappGroupMessageData.md
@@ -0,0 +1,14 @@
+# Type Alias: WhatsappGroupMessageData
+
+> **WhatsappGroupMessageData** = \{ `body?`: `never`; `path`: \{ `group_id`: `string`; `message_id`: `string`; \}; `query?`: `never`; `url`: `"/meta/linked/whatsapp-groups/{group_id}/messages/{message_id}"`; \}
+
+## Properties
+
+| Property | Type |
+| ------ | ------ |
+| <a id="property-body"></a> `body?` | `never` |
+| <a id="property-path"></a> `path` | \{ `group_id`: `string`; `message_id`: `string`; \} |
+| `path.group_id` | `string` |
+| `path.message_id` | `string` |
+| <a id="property-query"></a> `query?` | `never` |
+| <a id="property-url"></a> `url` | `"/meta/linked/whatsapp-groups/{group_id}/messages/{message_id}"` |
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsappGroupMessageResponse.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsappGroupMessageResponse.md
new file mode 100644
index 0000000000..00aa449368
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsappGroupMessageResponse.md
@@ -0,0 +1,3 @@
+# Type Alias: WhatsappGroupMessageResponse
+
+> **WhatsappGroupMessageResponse** = [`WhatsappGroupMessageResponses`](WhatsappGroupMessageResponses.md)\[keyof [`WhatsappGroupMessageResponses`](WhatsappGroupMessageResponses.md)\]
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsappGroupMessageResponses.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsappGroupMessageResponses.md
new file mode 100644
index 0000000000..8de850b294
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsappGroupMessageResponses.md
@@ -0,0 +1,9 @@
+# Type Alias: WhatsappGroupMessageResponses
+
+> **WhatsappGroupMessageResponses** = \{ `200`: [`WhatsAppGroupMessage`](WhatsAppGroupMessage.md); \}
+
+## Properties
+
+| Property | Type |
+| ------ | ------ |
+| <a id="property-200"></a> `200` | [`WhatsAppGroupMessage`](WhatsAppGroupMessage.md) |
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsappGroupMessagesData.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsappGroupMessagesData.md
index 4af2cbbf1d..3f2b2b14ee 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsappGroupMessagesData.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/WhatsappGroupMessagesData.md
@@ -11,5 +11,5 @@
| `path.group_id` | `string` | - |
| <a id="property-query"></a> `query?` | \{ `before?`: `string` \| `null`; `limit?`: `number` \| `null`; \} | - |
| `query.before?` | `string` \| `null` | Last message id in the previous page. |
-| `query.limit?` | `number` \| `null` | Page size, 1 through 100. |
+| `query.limit?` | `number` \| `null` | Page size, up to [`PAGE_LIMIT`]; [`DEFAULT_PAGE`] when absent. |
| <a id="property-url"></a> `url` | `"/meta/linked/whatsapp-groups/{group_id}/messages"` | - |
diff --git a/packages/sdk-docs/reference/src/entities/whatsapp/group/classes/WhatsAppGroup.md b/packages/sdk-docs/reference/src/entities/whatsapp/group/classes/WhatsAppGroup.md
index e02aafc517..9ca19fa8c1 100644
--- a/packages/sdk-docs/reference/src/entities/whatsapp/group/classes/WhatsAppGroup.md
+++ b/packages/sdk-docs/reference/src/entities/whatsapp/group/classes/WhatsAppGroup.md
@@ -21,7 +21,7 @@ Independently shareable added WhatsApp chat: a group or a direct chat.
| <a id="property-name"></a> `name` | `readonly` | () => `Promise`\<`string`\> | Display name: the group's, or a direct chat's other person. | - | - |
| <a id="property-owner"></a> `owner` | `readonly` | () => `Promise`\<[`User`](../../../users/user/classes/User.md)\> | Actual owner, independent of WhatsApp membership. | - | - |
| <a id="property-participants"></a> `participants` | `readonly` | () => `Promise`\<[`WhatsAppParticipant`](../../participant/classes/WhatsAppParticipant.md)[]\> | Everyone in the chat, from its roster; empty when no roster is known. | - | - |
-| <a id="property-roster"></a> `roster` | `readonly` | () => `Promise`\<[`LinkedGroupInfo`](../../../../../generated/storage/types.gen/type-aliases/LinkedGroupInfo.md) \| `undefined`\> | Current remote roster (name, participants, announce), when available. | - | - |
+| <a id="property-roster"></a> `roster` | `readonly` | () => `Promise`\<[`WhatsAppRoster`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppRoster.md) \| `undefined`\> | Current remote roster (name, participants, announce), when available. | - | - |
| <a id="property-sendingidentity"></a> `sendingIdentity` | `readonly` | () => `Promise`\<`string` \| `undefined`\> | Caller's own verified sending identity. | - | - |
| <a id="property-sendreason"></a> `sendReason` | `readonly` | () => `Promise`\<`NonNullable`\<LinkedReplyBlock \| null \| undefined\> \| `undefined`\> | Reason sending is blocked. | - | - |
| <a id="property-unreadcount"></a> `unreadCount` | `readonly` | () => `Promise`\<`number`\> | Per-user unread count. | - | - |
diff --git a/packages/sdk-docs/reference/src/entities/whatsapp/participant/classes/WhatsAppParticipant.md b/packages/sdk-docs/reference/src/entities/whatsapp/participant/classes/WhatsAppParticipant.md
index f9fa3adb85..97c4727739 100644
--- a/packages/sdk-docs/reference/src/entities/whatsapp/participant/classes/WhatsAppParticipant.md
+++ b/packages/sdk-docs/reference/src/entities/whatsapp/participant/classes/WhatsAppParticipant.md
@@ -102,7 +102,7 @@ Seed a participant from the chat's roster.
| Parameter | Type |
| ------ | ------ |
| `group` | [`WhatsAppGroup`](../../group/classes/WhatsAppGroup.md) |
-| `record` | [`LinkedParticipant`](../../../../../generated/storage/types.gen/type-aliases/LinkedParticipant.md) |
+| `record` | [`WhatsAppParticipant`](../../../../../generated/storage/types.gen/type-aliases/WhatsAppParticipant.md) |
#### Returns
diff --git a/packages/sdk-docs/reference/src/macro/README.md b/packages/sdk-docs/reference/src/macro/README.md
index 09bc8e9211..73f598f201 100644
--- a/packages/sdk-docs/reference/src/macro/README.md
+++ b/packages/sdk-docs/reference/src/macro/README.md
@@ -628,6 +628,12 @@ Re-exports [WhatsAppChat](../entities/whatsapp/chat/classes/WhatsAppChat.md)
***
+### WhatsAppCommunity
+
+Re-exports [WhatsAppCommunity](../entities/whatsapp/chat/type-aliases/WhatsAppCommunity.md)
+
+***
+
### WhatsAppGroup
Re-exports [WhatsAppGroup](../entities/whatsapp/group/classes/WhatsAppGroup.md)
diff --git a/packages/sdk/generated/storage/index.ts b/packages/sdk/generated/storage/index.ts
index c591cdec5c..754a39fd4c 100644
--- a/packages/sdk/generated/storage/index.ts
+++ b/packages/sdk/generated/storage/index.ts
@@ -1,4 +1,4 @@
// This file is auto-generated by @hey-api/openapi-ts
export { type Options, Sdk } from './sdk.gen';
-export type { AccessiblePipeline, AccessLevel, AccessRequest, AccessRequestsCancelData, AccessRequestsCancelErrors, AccessRequestsCancelResponses, AccessRequestsDirectData, AccessRequestsDirectErrors, AccessRequestsDirectResponse, AccessRequestsDirectResponses, AccessRequestsRemoveDirectData, AccessRequestsRemoveDirectErrors, AccessRequestsRemoveDirectResponses, AccessRequestsResolveData, AccessRequestsResolveErrors, AccessRequestsResolveResponse, AccessRequestsResolveResponses, AccessRequestsSetDirectData, AccessRequestsSetDirectErrors, AccessRequestsSetDirectResponses, AccessRequestsStateData, AccessRequestsStateErrors, AccessRequestsStateResponse, AccessRequestsStateResponses, AccessRequestsSubmitData, AccessRequestsSubmitErrors, AccessRequestsSubmitResponse, AccessRequestsSubmitResponses, AccessRequestState, ActiveCallsResponse, ActiveCallSummary, ActiveMeeting, ActiveMeetingsResponse, ActivityType, AddFavoriteData, AddFavoriteError, AddFavoriteErrors, AddFavoriteRequest, AddFavoriteResponse, AddFavoriteResponses, AddParticipantsData, AddParticipantsError, AddParticipantsErrors, AddParticipantsRequest, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerError, AddPinHandlerErrors, AddPinHandlerResponse, AddPinHandlerResponses, AddPinRequest, AdoptedGroup, Agent, AgentActionId, AgentChannelScope, AgentDmProfile, AgentMcpServer, AgentMcpServers, AgentPullRequestState, AgentSessionFilters, AgentSessionLifecycleEvent, AgentSessionSource, AgentSessionVisibility, AgentTyping, AgentTypingPhase, Anchor, AnchorId, AnchorResponse, AnnotationIncrementalUpdate, Answer, ApiActivity, ApiAttachmentChannelReference, ApiAttachmentCommentReference, ApiAttachmentEntityReference, ApiAttachmentGenericReference, ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelDetail, ApiChannelListMessage, ApiChannelListPage, ApiChannelListParticipant, ApiChannelListType, ApiChannelParticipant, ApiChannelWithLatest, ApiEntityFilterAst, ApiGroupByField, ApiGroupMeta, ApiParticipantListRole, ApiParticipantRole, ApiPropertyEntityType, AppliedOps, ApplyCrmPipelineOpsData, ApplyCrmPipelineOpsResponse, ApplyCrmPipelineOpsResponses, ApplyDatabaseOpsData, ApplyDatabaseOpsError, ApplyDatabaseOpsErrors, ApplyDatabaseOpsResponse, ApplyDatabaseOpsResponses, ApplyOpsRequest, ApplyOpsResponse, ApproveHarnessPairingData, ApproveHarnessPairingError, ApproveHarnessPairingErrors, ApproveHarnessPairingResponse, ApproveHarnessPairingResponses, ApprovePairingRequest, AttachmentChange, AttendeeResponseStatus, Audience, Awareness, AwarenessRelay, BasicDocument, BasicDocumentSubType, BomPart, BookingTarget, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotOwnerProfile, BotSenderProfile, BotToken, BranchNameResponse, BTreeMap, BulkWakeupRequest, BulkWakeupResponse, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponse, BulkWakeupSyncServiceDocumentsResponses, CalendarAttendee, CalendarEvent, CalendarEventFilters, CalendarEventSourceContent, CalendarJoinRequest, CalendarJoinRequestApiError, CalendarJoinRequestErrorCode, CalendarJoinRequestsResponse, CalendarJoinRequestStatus, CalendarMentionEvent, CalendarMentionPreviewItem, CalendarMentionPreviewKind, CalendarMentionPreviewRequest, CalendarMentionPreviewRequestItem, CalendarMentionPreviewResponse, CalendarMentionViewerCopy, CalendarOccurrence, CalendarOccurrenceItem, CalendarOccurrenceResponse, CalendarSyncStatus, CallActiveResponse, CallFilters, CallProvider, CallRecord, CallRecordGuest, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordSource, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, CancelSlackImportData, CancelSlackImportErrors, CancelSlackImportResponse, CancelSlackImportResponses, CardPosition, CastVerdict, CellValue, CellWrite, ChangedFileDto, ChangesetDto, ChangesetSourceDto, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelFilters, ChannelJoinCodeResponse, ChannelLabel, ChannelLabelRule, ChannelLabelsList, ChannelMessage, ChannelParticipant, ChannelParticipantAddedMetadata, ChannelParticipantRemovedMetadata, ChannelPictureChangedMetadata, ChannelPreview, ChannelPreviewData, ChannelSender, ChannelSharePermission, ChannelThreadFilters, ChannelTopicEvent, ChannelType, ChannelUpdatedMetadata, ChannelWebhookRequest, ChannelWebhookResponse, ChannelWithParticipants, Chat, ChatFilters, CheckActiveCallData, CheckActiveCallError, CheckActiveCallErrors, CheckActiveCallResponse, CheckActiveCallResponses, ClaimedPairing, ClaimHarnessPairingData, ClaimHarnessPairingError, ClaimHarnessPairingErrors, ClaimHarnessPairingResponse, ClaimHarnessPairingResponses, ClaimPairingRequest, ClientOptions, CloudStorageItemType, CollaborateFormData, CollaborateFormError, CollaborateFormErrors, CollaborateFormResponse, CollaborateFormResponses, CollabSurfaceResponse, CollabSurfaceTokenResponse, Column, ColumnCast, ColumnChange, ColumnChangeKind, ColumnConfig, ColumnConversion, ColumnConversionRequest, ColumnDetail, ColumnId, ColumnKind, ColumnProtection, ColumnResult, CommandFailure, CommandRejectedMetadata, CommittedChange, CompleteSlackImportUploadsData, CompleteSlackImportUploadsErrors, CompleteSlackImportUploadsResponse, CompleteSlackImportUploadsResponses, CompleteUploads, ConferenceProvider, Conjunction, ConversationId, ConversationKind, ConversationMetadata, ConversationProgress, ConversationSeal, ConversationStatus, ConvertDatabaseColumnData, ConvertDatabaseColumnError, ConvertDatabaseColumnErrors, ConvertDatabaseColumnResponse, ConvertDatabaseColumnResponses, ConvertedCell, CopyDocumentData, CopyDocumentError, CopyDocumentErrors, CopyDocumentQueryParams, CopyDocumentRequest, CopyDocumentResponse, CopyDocumentResponse2, CopyDocumentResponses, CountedReaction, CreateAgentData, CreateAgentError, CreateAgentErrors, CreateAgentRequest, CreateAgentResponse, CreateAgentResponses, CreateAnchorData, CreateAnchorError, CreateAnchorErrors, CreateAnchorResponse, CreateAnchorResponses, CreateBotRequest, CreateBulkDocumentResponse, CreateBulkDocumentResponseData, CreateCanvasDocumentRequest, CreateCanvasDocumentResponse, CreateCanvasHandlerData, CreateCanvasHandlerError, CreateCanvasHandlerErrors, CreateCanvasHandlerResponse, CreateCanvasHandlerResponses, CreateChannelData, CreateChannelError, CreateChannelErrors, CreateChannelLabelData, CreateChannelLabelError, CreateChannelLabelErrors, CreateChannelLabelRequest, CreateChannelLabelResponse, CreateChannelLabelResponses, CreateChannelRequest, CreateChannelResponse, CreateChannelResponse2, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotError, CreateChannelScopedBotErrors, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, CreateChannelScopedBotResponse2, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenError, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponse, CreateCollabSurfaceTokenResponses, CreateCrmCompanyData, CreateCrmCompanyError, CreateCrmCompanyErrors, CreateCrmCompanyRequest, CreateCrmCompanyResponse, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactError, CreateCrmContactErrors, CreateCrmContactRequest, CreateCrmContactResponse, CreateCrmContactResponses, CreateCrmPipelineData, CreateCrmPipelineResponse, CreateCrmPipelineResponses, CreateDatabaseData, CreateDatabaseError, CreateDatabaseErrors, CreateDatabaseRequest, CreateDatabaseResponse, CreateDatabaseResponses, CreateDatabaseWebhookData, CreateDatabaseWebhookError, CreateDatabaseWebhookErrors, CreateDatabaseWebhookRequest, CreateDatabaseWebhookResponse, CreateDatabaseWebhookResponses, CreatedDatabaseWebhookResponse, CreateDocumentData, CreateDocumentError, CreateDocumentErrors, CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData, CreateDocumentResponses, CreatedPairing, CreatedUserApiKey, CreateEntityMentionData, CreateEntityMentionError, CreateEntityMentionErrors, CreateEntityMentionRequest, CreateEntityMentionResponse, CreateEntityMentionResponse2, CreateEntityMentionResponses, CreateForm, CreateFormData, CreateFormError, CreateFormErrors, CreateFormResponse, CreateFormResponses, CreateHarnessPairingData, CreateHarnessPairingError, CreateHarnessPairingErrors, CreateHarnessPairingResponse, CreateHarnessPairingResponses, CreateImport, CreateInitiativeData, CreateInitiativeError, CreateInitiativeErrors, CreateInitiativeRequest, CreateInitiativeResponse, CreateInitiativeResponses, CreateInstructionsDocumentResponse, CreateInstructionsHandlerData, CreateInstructionsHandlerError, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponse, CreateInstructionsHandlerResponses, CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, CreateMarkdownHandlerData, CreateMarkdownHandlerError, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponse, CreateMarkdownHandlerResponses, CreateMeetingRequest, CreatePairingRequest, CreatePipeline, CreateProjectHandlerData, CreateProjectHandlerError, CreateProjectHandlerErrors, CreateProjectHandlerResponse, CreateProjectHandlerResponses, CreateProjectRequest, CreateProjectResponse, CreateSkillHandlerData, CreateSkillHandlerError, CreateSkillHandlerErrors, CreateSkillHandlerResponse, CreateSkillHandlerResponses, CreateSkillRequest, CreateSkillResponse, CreateSlackImportData, CreateSlackImportErrors, CreateSlackImportResponse, CreateSlackImportResponses, CreateSnippetHandlerData, CreateSnippetHandlerError, CreateSnippetHandlerErrors, CreateSnippetHandlerResponse, CreateSnippetHandlerResponses, CreateSnippetRequest, CreateSnippetResponse, CreateTaskHandlerData, CreateTaskHandlerError, CreateTaskHandlerErrors, CreateTaskHandlerResponse, CreateTaskHandlerResponses, CreateTaskRequest, CreateTaskResponse, CreateToken, CreateUnthreadedAnchorRequest, CreateUnthreadedAnchorResponse, CreateUnthreadedPdfAnchorRequest, CreateUserApiKeyData, CreateUserApiKeyError, CreateUserApiKeyErrors, CreateUserApiKeyRequest, CreateUserApiKeyResponse, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerError, CreateViewHandlerErrors, CreateViewHandlerResponse, CreateViewHandlerResponses, CreateViewRequest, CreateWebhookData, CreateWebhookError, CreateWebhookErrors, CreateWebhookRequest, CreateWebhookResponse, CreateWebhookResponse2, CreateWebhookResponses, CrmAssociation, CrmCompanyFilters, CrmCompanyResponse, CrmContactResponse, CrmDomainResponse, CrmPermissionRole, CrmStageInput, CrmStageResponse, CrmStagesResponse, CrmTeamSettingsResponse, CustomSpeakerAssignment, Database, DatabaseDetail, DatabaseId, DatabaseOp, DatabaseQueryRequest, DatabaseView, DatabaseWebhookDeliveryResponse, DatabaseWebhookPayloadProblem, DatabaseWebhookResponse, DataType, DateOperator, DeclineCallData, DeclineCallError, DeclineCallErrors, DeclineCallResponse, DeclineCallResponses, DeclineRingData, DeclineRingError, DeclineRingErrors, DeclineRingResponse, DeclineRingResponses, DeleteAnchorData, DeleteAnchorError, DeleteAnchorErrors, DeleteAnchorResponse, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordError, DeleteCallRecordErrors, DeleteCallRecordResponse, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelError, DeleteChannelErrors, DeleteChannelLabelData, DeleteChannelLabelError, DeleteChannelLabelErrors, DeleteChannelLabelResponse, DeleteChannelLabelResponses, DeleteChannelResponse, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceError, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponse, DeleteCollabSurfaceResponses, DeleteDatabaseWebhookData, DeleteDatabaseWebhookError, DeleteDatabaseWebhookErrors, DeleteDatabaseWebhookResponse, DeleteDatabaseWebhookResponses, DeleteDocumentData, DeleteDocumentError, DeleteDocumentErrors, DeleteDocumentResponse, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionError, DeleteEntityMentionErrors, DeleteEntityMentionResponse, DeleteEntityMentionResponse2, DeleteEntityMentionResponses, DeleteHarnessData, DeleteHarnessError, DeleteHarnessErrors, DeleteHarnessResponse, DeleteHarnessResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerError, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponse, DeleteHistoryHandlerResponses, DeleteInitiativeData, DeleteInitiativeError, DeleteInitiativeErrors, DeleteInitiativeResponse, DeleteInitiativeResponses, DeleteProjectHandlerData, DeleteProjectHandlerError, DeleteProjectHandlerErrors, DeleteProjectHandlerResponse, DeleteProjectHandlerResponses, DeleteSelfHarnessData, DeleteSelfHarnessError, DeleteSelfHarnessErrors, DeleteSelfHarnessResponse, DeleteSelfHarnessResponses, DeleteUnthreadedAnchorRequest, DeleteUnthreadedAnchorResponse, DeleteUnthreadedPdfAnchorRequest, DeleteUserApiKeyData, DeleteUserApiKeyError, DeleteUserApiKeyErrors, DeleteUserApiKeyResponse, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationError, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponse, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerError, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookError, DeleteWebhookErrors, DeleteWebhookResponse, DeleteWebhookResponses, DeliverDatabaseWebhookData, DeliverDatabaseWebhookError, DeliverDatabaseWebhookErrors, DeliverDatabaseWebhookResponse, DeliverDatabaseWebhookResponses, DirectAccess, DocumentBasic, DocumentContent, DocumentContentLocation, DocumentContentState, DocumentContentUploadedMetadata, DocumentCopiedMetadata, DocumentCreatedMetadata, DocumentDeletedMetadata, DocumentFilters, DocumentId, DocumentInteractionMetadata, DocumentMetadata, DocumentMetadataWithContent, DocumentPermissionsToken, DocumentPermissionsTokenRequest, DocumentPermissionsTokenResponse, DocumentPreview, DocumentPreviewData, DocumentPreviewDataSubType, DocumentPurgedMetadata, DocumentResponse, DocumentResponseMetadata, DocumentResponseMetadataWithContent, DocumentStorageServiceApiVersion, DocumentSubType, DocumentSyncContentUpdatedMetadata, DocumentSyncEditor, DocumentTeamShareResponse, DocumentTextContent, DocumentTopicEvent, DocumentUpdatedMetadata, EditAnchorData, EditAnchorError, EditAnchorErrors, EditAnchorRequest, EditAnchorResponse, EditAnchorResponse2, EditAnchorResponses, EditCallRecordData, EditCallRecordError, EditCallRecordErrors, EditCallRecordRequest, EditCallRecordResponse, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptError, EditCallTranscriptErrors, EditCallTranscriptRequest, EditCallTranscriptResponse, EditCallTranscriptResponses, EditDocumentData, EditDocumentError, EditDocumentErrors, EditDocumentResponse, EditDocumentResponse2, EditDocumentResponses, EditDocumentServiceArgs, EditMyFormResponseData, EditMyFormResponseError, EditMyFormResponseErrors, EditMyFormResponseResponse, EditMyFormResponseResponses, EditPdfAnchorRequest, EditPdfPlaceableCommentAnchorRequest, EditProjectV2Data, EditProjectV2Error, EditProjectV2Errors, EditProjectV2Response, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Error, EditThreadV2Errors, EditThreadV2Response, EditThreadV2Responses, EmailFilters, EmailFollowup, EmailFollowupCommand, EmailFollowupResponse, EmailReminderCondition, EmailReminderPage, EmailReminderSummary, EmptyResponse, EnsureCollabSurfaceData, EnsureCollabSurfaceError, EnsureCollabSurfaceErrors, EnsureCollabSurfaceRequest, EnsureCollabSurfaceResponse, EnsureCollabSurfaceResponses, EnsureStarterHandlerData, EnsureStarterHandlerErrors, EnsureStarterHandlerResponse, EnsureStarterHandlerResponses, EntityFilters, EntityKind, EntityMessageCreateData, EntityMessageCreateResponse, EntityMessageCreateResponses, EntityMessageDeleteMessageData, EntityMessageDeleteMessageResponse, EntityMessageDeleteMessageResponses, EntityMessageDeleteThreadData, EntityMessageDeleteThreadResponse, EntityMessageDeleteThreadResponses, EntityMessageEditData, EntityMessageEditResponse, EntityMessageEditResponses, EntityMessageGetMessageData, EntityMessageGetMessageResponse, EntityMessageGetMessageResponses, EntityMessageGetThreadData, EntityMessageGetThreadResponse, EntityMessageGetThreadResponses, EntityMessageLegacyData, EntityMessageLegacyResponse, EntityMessageLegacyResponses, EntityMessagePatchThreadData, EntityMessagePatchThreadResponse, EntityMessagePatchThreadResponses, EntityMessageReactData, EntityMessageReactResponse, EntityMessageReactResponses, EntityMessageTypingData, EntityMessageTypingResponse, EntityMessageTypingResponses, EntityPermission, EntityPermissionResponse, EntityRef, EntityReference, EntityType, ErrorResponse, EventIcsData, EventIcsErrors, EventIcsResponse, EventIcsResponses, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventType, EventVisibility, ExcludedDefaultView, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerError, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExcludeDefaultViewRequest, ExportDocumentData, ExportDocumentError, ExportDocumentErrors, ExportDocumentResponse, ExportDocumentResponse2, ExportDocumentResponses, Favorite, FavoriteEntityRef, FavoritesList, FileChangeKindDto, FileSystemNodeWithIds, FileType, FileTypeUpdate, FilterCondition, FilterGroup, FilterNode, FilterTest, FinalizeSlackImportData, FinalizeSlackImportErrors, FinalizeSlackImportResponse, FinalizeSlackImportResponses, FolderItem, FollowupState, ForeignEntity, ForeignEntityFilters, Form, FormAccess, FormCollaboration, FormDetail, FormErrorCode, FormErrorResponse, FormLayout, FormPublicationProblem, FormQuestionDetail, FormResponse, FormSection, FormSectionDetail, FormSource, FormStatus, FormTally, Formula, GenericErrorResponse, GenericResponse, GenericSuccessResponse, GetActiveCallsData, GetActiveCallsError, GetActiveCallsErrors, GetActiveCallsResponse, GetActiveCallsResponses, GetActivityData, GetActivityError, GetActivityErrors, GetActivityResponse, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesError, GetAttachmentReferencesErrors, GetAttachmentReferencesResponse, GetAttachmentReferencesResponse2, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewError, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewRequest, GetBatchCallRecordPreviewResponse, GetBatchCallRecordPreviewResponse2, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewError, GetBatchChannelPreviewErrors, GetBatchChannelPreviewRequest, GetBatchChannelPreviewResponse, GetBatchChannelPreviewResponse2, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerError, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponse, GetBatchPreviewHandlerResponses, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchProjectPreviewData, GetBatchProjectPreviewError, GetBatchProjectPreviewErrors, GetBatchProjectPreviewRequest, GetBatchProjectPreviewResponse, GetBatchProjectPreviewResponse2, GetBatchProjectPreviewResponses, GetBotOwnerProfilesData, GetBotOwnerProfilesError, GetBotOwnerProfilesErrors, GetBotOwnerProfilesResponse, GetBotOwnerProfilesResponses, GetCallRecordData, GetCallRecordError, GetCallRecordErrors, GetCallRecordResponse, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsError, GetChannelAttachmentsErrors, GetChannelAttachmentsResponse, GetChannelAttachmentsResponses, GetChannelData, GetChannelError, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkError, GetChannelJoinLinkErrors, GetChannelJoinLinkResponse, GetChannelJoinLinkResponses, GetChannelParticipantsData, GetChannelParticipantsError, GetChannelParticipantsErrors, GetChannelParticipantsResponse, GetChannelParticipantsResponses, GetChannelResponse, GetChannelResponses, GetChannelsData, GetChannelsError, GetChannelsErrors, GetChannelsResponse, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceError, GetCollabSurfaceErrors, GetCollabSurfaceResponse, GetCollabSurfaceResponses, GetCompanyData, GetCompanyError, GetCompanyErrors, GetCompanyResponse, GetCompanyResponses, GetContactByEmailData, GetContactByEmailError, GetContactByEmailErrors, GetContactByEmailResponse, GetContactByEmailResponse2, GetContactByEmailResponses, GetContactData, GetContactError, GetContactErrors, GetContactResponse, GetContactResponses, GetCrmPipelineData, GetCrmPipelinePermissionsData, GetCrmPipelinePermissionsResponse, GetCrmPipelinePermissionsResponses, GetCrmPipelineResponse, GetCrmPipelineResponses, GetCrmPipelineRowsData, GetCrmPipelineRowsResponse, GetCrmPipelineRowsResponses, GetCrmPipelineTableData, GetCrmPipelineTableResponse, GetCrmPipelineTableResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsError, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponse, GetCrmTeamSettingsResponses, GetDatabaseData, GetDatabaseError, GetDatabaseErrors, GetDatabasePermissionsData, GetDatabasePermissionsError, GetDatabasePermissionsErrors, GetDatabasePermissionsResponse, GetDatabasePermissionsResponses, GetDatabaseQueryData, GetDatabaseQueryError, GetDatabaseQueryErrors, GetDatabaseQueryResponse, GetDatabaseQueryResponses, GetDatabaseResponse, GetDatabaseResponses, GetDatabaseRowHistoryData, GetDatabaseRowHistoryError, GetDatabaseRowHistoryErrors, GetDatabaseRowHistoryResponse, GetDatabaseRowHistoryResponses, GetDatabaseTableChangesData, GetDatabaseTableChangesError, GetDatabaseTableChangesErrors, GetDatabaseTableChangesResponse, GetDatabaseTableChangesResponses, GetDatabaseViewPositionsData, GetDatabaseViewPositionsError, GetDatabaseViewPositionsErrors, GetDatabaseViewPositionsResponse, GetDatabaseViewPositionsResponses, GetDocumentAnchorsData, GetDocumentAnchorsError, GetDocumentAnchorsErrors, GetDocumentAnchorsResponse, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameError, GetDocumentBranchNameErrors, GetDocumentBranchNameResponse, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugError, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponse, GetDocumentByTeamSlugResponses, GetDocumentData, GetDocumentError, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsError, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponse, GetDocumentGithubPullRequestsResponses, GetDocumentKeyResponse, GetDocumentKeyResponseData, GetDocumentListHandlerData, GetDocumentListHandlerError, GetDocumentListHandlerErrors, GetDocumentListHandlerResponse, GetDocumentListHandlerResponses, GetDocumentListResult, GetDocumentLocationV3Data, GetDocumentLocationV3Error, GetDocumentLocationV3Errors, GetDocumentLocationV3Response, GetDocumentLocationV3Responses, GetDocumentPermissionsResponseDataV2, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenError, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponse, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Error, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Response, GetDocumentPermissionsV2Responses, GetDocumentProcessingResult, GetDocumentProcessingResultData, GetDocumentProcessingResultError, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponse, GetDocumentProcessingResultResponse2, GetDocumentProcessingResultResponses, GetDocumentResponse, GetDocumentResponse2, GetDocumentResponseData, GetDocumentResponses, GetDocumentSearchResponse, GetDocumentShortIdData, GetDocumentShortIdError, GetDocumentShortIdErrors, GetDocumentShortIdResponse, GetDocumentShortIdResponses, GetDocumentsResponse, GetDocumentTeamShareData, GetDocumentTeamShareError, GetDocumentTeamShareErrors, GetDocumentTeamShareResponse, GetDocumentTeamShareResponses, GetDocumentTextContentData, GetDocumentTextContentErrors, GetDocumentTextContentResponse, GetDocumentTextContentResponses, GetDocumentUserAccessLevelResponse, GetDocumentVersionData, GetDocumentVersionError, GetDocumentVersionErrors, GetDocumentVersionResponse, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerError, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponse, GetDocumentViewsHandlerResponses, GetEmailFollowupData, GetEmailFollowupError, GetEmailFollowupErrors, GetEmailFollowupResponse, GetEmailFollowupResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponse, GetEntityPermissionResponses, GetForeignEntityBySourceData, GetForeignEntityBySourceError, GetForeignEntityBySourceErrors, GetForeignEntityBySourceResponse, GetForeignEntityBySourceResponses, GetForeignEntityData, GetForeignEntityError, GetForeignEntityErrors, GetForeignEntityResponse, GetForeignEntityResponses, GetFormData, GetFormError, GetFormErrors, GetFormPermissionsData, GetFormPermissionsError, GetFormPermissionsErrors, GetFormPermissionsResponse, GetFormPermissionsResponses, GetFormResponse, GetFormResponses, GetFormResponseSummaryData, GetFormResponseSummaryError, GetFormResponseSummaryErrors, GetFormResponseSummaryResponse, GetFormResponseSummaryResponses, GetFormTallyData, GetFormTallyError, GetFormTallyErrors, GetFormTallyResponse, GetFormTallyResponses, GetGithubPullRequestChangesData, GetGithubPullRequestChangesError, GetGithubPullRequestChangesErrors, GetGithubPullRequestChangesPatchData, GetGithubPullRequestChangesPatchError, GetGithubPullRequestChangesPatchErrors, GetGithubPullRequestChangesPatchResponse, GetGithubPullRequestChangesPatchResponses, GetGithubPullRequestChangesResponse, GetGithubPullRequestChangesResponses, GetGithubPullRequestData, GetGithubPullRequestError, GetGithubPullRequestErrors, GetGithubPullRequestFacetsData, GetGithubPullRequestFacetsError, GetGithubPullRequestFacetsErrors, GetGithubPullRequestFacetsResponse, GetGithubPullRequestFacetsResponses, GetGithubPullRequestResponse, GetGithubPullRequestResponses, GetGithubPullRequestTasksData, GetGithubPullRequestTasksError, GetGithubPullRequestTasksErrors, GetGithubPullRequestTasksResponse, GetGithubPullRequestTasksResponses, GetHarnessPairingData, GetHarnessPairingError, GetHarnessPairingErrors, GetHarnessPairingResponse, GetHarnessPairingResponses, GetHistoryHandlerData, GetHistoryHandlerError, GetHistoryHandlerErrors, GetHistoryHandlerResponse, GetHistoryHandlerResponses, GetInitiativeData, GetInitiativeError, GetInitiativeErrors, GetInitiativeResponse, GetInitiativeResponses, GetInstructionsDocumentResponse, GetInstructionsHandlerData, GetInstructionsHandlerError, GetInstructionsHandlerErrors, GetInstructionsHandlerResponse, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupError, GetItemsSoupErrors, GetItemsSoupResponse, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerError, GetLocationHandlerErrors, GetLocationHandlerResponse, GetLocationHandlerResponses, GetMyFormResponseData, GetMyFormResponseError, GetMyFormResponseErrors, GetMyFormResponseResponse, GetMyFormResponseResponses, GetOrCreateAction, GetOrCreateCallData, GetOrCreateCallError, GetOrCreateCallErrors, GetOrCreateCallResponse, GetOrCreateCallResponses, GetOrCreateChannelResponse, GetOrCreateDmData, GetOrCreateDmError, GetOrCreateDmErrors, GetOrCreateDmRequest, GetOrCreateDmResponse, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateError, GetOrCreatePrivateErrors, GetOrCreatePrivateRequest, GetOrCreatePrivateResponse, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerError, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponse, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerError, GetPinsHandlerErrors, GetPinsHandlerResponse, GetPinsHandlerResponses, GetPinsResponse, GetProjectContentHandlerData, GetProjectContentHandlerError, GetProjectContentHandlerErrors, GetProjectContentHandlerResponse, GetProjectContentHandlerResponses, GetProjectContentResponse, GetProjectHandlerData, GetProjectHandlerError, GetProjectHandlerErrors, GetProjectHandlerResponse, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Error, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Response, GetProjectPermissionsV2Responses, GetProjectResponse, GetProjectResponseData, GetProjectsHandlerData, GetProjectsHandlerError, GetProjectsHandlerErrors, GetProjectsHandlerResponse, GetProjectsHandlerResponses, GetProjectsResponse, GetProjectUserAccessLevelData, GetProjectUserAccessLevelError, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponse, GetProjectUserAccessLevelResponses, GetRingStatusData, GetRingStatusError, GetRingStatusErrors, GetRingStatusResponse, GetRingStatusResponses, GetSelfBotData, GetSelfBotError, GetSelfBotErrors, GetSelfBotResponse, GetSelfBotResponses, GetSelfHarnessData, GetSelfHarnessError, GetSelfHarnessErrors, GetSelfHarnessResponse, GetSelfHarnessResponses, GetSlackImportData, GetSlackImportErrors, GetSlackImportResponse, GetSlackImportResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerError, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponse, GetSystemSkillsHandlerResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerError, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponse, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationError, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponse, GetUserDocumentViewLocationResponses, GetUserHistoryResponse, GetViewsHandlerData, GetViewsHandlerError, GetViewsHandlerErrors, GetViewsHandlerResponse, GetViewsHandlerResponses, GetWebhookData, GetWebhookError, GetWebhookErrors, GetWebhookResponse, GetWebhookResponses, GithubLabelFacet, GithubPullRequest, GithubPullRequestChangesPatchResponse, GithubPullRequestChangesResponse, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestFacets, GithubPullRequestLabel, GithubPullRequestReview, GithubPullRequestReviewDecision, GithubPullRequestReviewState, GithubPullRequestsResponse, GithubPullRequestTasks, GithubPullRequestTasksRequest, GithubPullRequestTasksResponse, GithubPullRequestUser, GithubRepositoryFacet, GithubUserFacet, GitRefDto, GroupedInitialParams, GroupedPageParams, GroupedSoupGroupPage, GroupedSoupInitialPage, GroupedSoupPage, GroupedSoupSort, GuestCallChatPostData, GuestCallChatPostErrors, GuestCallChatPostResponse, GuestCallChatPostResponses, GuestCallChatReadData, GuestCallChatReadErrors, GuestCallChatReadResponse, GuestCallChatReadResponses, GuestChatMessage, GuestChatPage, GuestChatPost, GuestId, GuestJoinRequest, GuestPolicy, HandlerData, HandlerError, HandlerErrors, HandlerResponse, HandlerResponses, Harness, HarnessAgent, HarnessId, HarnessOwner, HarnessSession, HashMap, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HighlightType, ImportCounters, ImportDatabaseTableData, ImportDatabaseTableError, ImportDatabaseTableErrors, ImportDatabaseTableResponse, ImportDatabaseTableResponses, ImportedAuthor, ImportError, ImportLimits, ImportPage, ImportProgress, ImportTable, ImportWarning, InferColumnTypeOutcome, InferColumnTypeRequest, InferDatabaseColumnTypeData, InferDatabaseColumnTypeError, InferDatabaseColumnTypeErrors, InferDatabaseColumnTypeResponse, InferDatabaseColumnTypeResponses, InFlightTurnSummary, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InitialPropertyValue, InitiativeDetail, InitiativeFilters, InitiativeId, InitiativeList, InitiativeSummary, InputReceivedMetadata, InstallSyncData, InstallSyncErrors, InteractionReason, InvalidDatabaseWebhookPayloadResponse, InviteMeetingRequest, InviteMeetingUsersRequest, Item, ItemWithUserAccessLevel, JobId, JobProcessingResultHandlerData, JobProcessingResultHandlerError, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponse, JobProcessingResultHandlerResponses, JobStatus, JoinChannelByCodeData, JoinChannelByCodeError, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelError, JoinChannelErrors, JoinChannelResponses, KeySegment, Lane, LaneKey, LatestMessage, LayoutProblem, LeaveCallResponse, LeaveChannelData, LeaveChannelError, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallError, LeaveOrEndCallErrors, LeaveOrEndCallResponse, LeaveOrEndCallResponses, LinkedAccount, LinkedAccountData, LinkedAccountResponse, LinkedAccountResponses, LinkedAccountState, LinkedAccountView, LinkedAdoptData, LinkedAdoptGroup, LinkedAdoptResponse, LinkedAdoptResponses, LinkedAttachment, LinkedAttachmentState, LinkedBackfill, LinkedBackfillState, LinkedCancelPairingData, LinkedCancelPairingResponse, LinkedCancelPairingResponses, LinkedCannotAdd, LinkedCapabilities, LinkedChat, LinkedChatKind, LinkedChats, LinkedChatsData, LinkedChatsResponse, LinkedChatsResponses, LinkedCommunityReference, LinkedConfigurationData, LinkedConfigurationResponse, LinkedConfigurationResponses, LinkedConnect, LinkedConnectData, LinkedConnectResponse, LinkedConnectResponses, LinkedDeliveryData, LinkedDeliveryResponse, LinkedDeliveryResponses, LinkedDeliveryState, LinkedDetachData, LinkedDetachResponse, LinkedDetachResponses, LinkedDisconnect, LinkedDisconnectData, LinkedDisconnectRequest, LinkedDisconnectResponse, LinkedDisconnectResponses, LinkedFeatures, LinkedGroupInfo, LinkedGroupReference, LinkedIdentity, LinkedMediaKind, LinkedMediaPresentation, LinkedMessageAttachments, LinkedMessageAttachmentsData, LinkedMessageAttachmentsResponse, LinkedMessageAttachmentsResponses, LinkedMutation, LinkedPairing, LinkedPairingData, LinkedPairingResponse, LinkedPairingResponses, LinkedPairingState, LinkedPairState, LinkedParticipant, LinkedPasskeyData, LinkedPasskeyResponse, LinkedPasskeyResponses, LinkedReplyBlock, LinkedReplyContent, LinkedReplyData, LinkedReplyErrors, LinkedReplyResponse, LinkedReplyResponses, LinkedSendProgress, LinkedSendReply, LinkedSharedGroupReference, LinkedUploadData, LinkedUploadedAttachment, LinkedUploadRequest, LinkedUploadResponse, LinkedUploadResponses, LinkShare, ListAccessibleFormsData, ListAccessibleFormsError, ListAccessibleFormsErrors, ListAccessibleFormsResponse, ListAccessibleFormsResponses, ListAgentsData, ListAgentsError, ListAgentsErrors, ListAgentsResponse, ListAgentsResponses, ListBotChannelsData, ListBotChannelsError, ListBotChannelsErrors, ListBotChannelsResponse, ListBotChannelsResponses, ListChannelLabelsData, ListChannelLabelsError, ListChannelLabelsErrors, ListChannelLabelsResponse, ListChannelLabelsResponses, ListCompanyContactsData, ListCompanyContactsError, ListCompanyContactsErrors, ListCompanyContactsResponse, ListCompanyContactsResponses, ListCrmPipelinesData, ListCrmPipelinesResponse, ListCrmPipelinesResponses, ListDatabaseColumnCastsData, ListDatabaseColumnCastsError, ListDatabaseColumnCastsErrors, ListDatabaseColumnCastsResponse, ListDatabaseColumnCastsResponses, ListDatabasesData, ListDatabasesError, ListDatabasesErrors, ListDatabasesResponse, ListDatabasesResponses, ListDatabaseWebhooksData, ListDatabaseWebhooksError, ListDatabaseWebhooksErrors, ListDatabaseWebhooksResponse, ListDatabaseWebhooksResponse2, ListDatabaseWebhooksResponses, ListedDatabase, ListedForm, ListEmailRemindersData, ListEmailRemindersError, ListEmailRemindersErrors, ListEmailRemindersResponse, ListEmailRemindersResponses, ListFavoritesData, ListFavoritesError, ListFavoritesErrors, ListFavoritesResponse, ListFavoritesResponses, ListFormsData, ListFormsError, ListFormsErrors, ListFormsResponse, ListFormsResponses, ListHarnessAgentsData, ListHarnessAgentsError, ListHarnessAgentsErrors, ListHarnessAgentsResponse, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesError, ListHarnessesErrors, ListHarnessesResponse, ListHarnessesResponses, ListHarnessSessionsData, ListHarnessSessionsError, ListHarnessSessionsErrors, ListHarnessSessionsResponse, ListHarnessSessionsResponses, ListInitiativesData, ListInitiativesError, ListInitiativesErrors, ListInitiativesResponse, ListInitiativesResponses, ListJoinRequestsData, ListJoinRequestsError, ListJoinRequestsErrors, ListJoinRequestsResponse, ListJoinRequestsResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponse, ListOccurrencesResponses, ListSlackImportsData, ListSlackImportsResponse, ListSlackImportsResponses, ListTeamCalendarData, ListTeamCalendarResponse, ListTeamCalendarResponses, ListTeamOutOfOfficeData, ListTeamOutOfOfficeErrors, ListTeamOutOfOfficeResponse, ListTeamOutOfOfficeResponses, ListUserApiKeysData, ListUserApiKeysError, ListUserApiKeysErrors, ListUserApiKeysResponse, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, MarkRead, Meeting, MeetingCancelData, MeetingCancelError, MeetingCancelErrors, MeetingCancelPreparationData, MeetingCancelPreparationError, MeetingCancelPreparationErrors, MeetingCancelPreparationResponse, MeetingCancelPreparationResponses, MeetingCancelResponse, MeetingCancelResponses, MeetingCreateData, MeetingCreateError, MeetingCreateErrors, MeetingCreateResponse, MeetingCreateResponses, MeetingGuestJoinData, MeetingGuestJoinError, MeetingGuestJoinErrors, MeetingGuestJoinResponse, MeetingGuestJoinResponses, MeetingGuestParticipantsData, MeetingGuestParticipantsError, MeetingGuestParticipantsErrors, MeetingGuestParticipantsResponse, MeetingGuestParticipantsResponses, MeetingInviteData, MeetingInviteError, MeetingInviteErrors, MeetingInvitePermissions, MeetingInvitePermissionsData, MeetingInvitePermissionsError, MeetingInvitePermissionsErrors, MeetingInvitePermissionsResponse, MeetingInvitePermissionsResponses, MeetingInviteResponse, MeetingInviteResponses, MeetingInviteUsersData, MeetingInviteUsersError, MeetingInviteUsersErrors, MeetingInviteUsersResponse, MeetingInviteUsersResponses, MeetingJoinData, MeetingJoinError, MeetingJoinErrors, MeetingJoinResponse, MeetingJoinResponses, MeetingLeaveData, MeetingLeaveError, MeetingLeaveErrors, MeetingLeaveResponse, MeetingLeaveResponses, MeetingListActiveData, MeetingListActiveError, MeetingListActiveErrors, MeetingListActiveResponse, MeetingListActiveResponses, MeetingListData, MeetingListError, MeetingListErrors, MeetingListResponse, MeetingListResponses, MeetingLookupData, MeetingLookupError, MeetingLookupErrors, MeetingLookupResponse, MeetingLookupResponses, MeetingParticipant, MeetingParticipants, MeetingParticipantsData, MeetingParticipantsError, MeetingParticipantsErrors, MeetingParticipantsResponse, MeetingParticipantsResponses, MeetingPreparation, MeetingPrepareData, MeetingPrepareError, MeetingPrepareErrors, MeetingPrepareResponse, MeetingPrepareResponses, MeetingShareData, MeetingShareError, MeetingShareErrors, MeetingShareResponse, MeetingShareResponses, MeetingsResponse, MeetingToken, MeetingUpdateData, MeetingUpdateError, MeetingUpdateErrors, MeetingUpdateResponse, MeetingUpdateResponses, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponse, MentionPreviewsResponses, Message, MessageAttachment, MessageAttachmentCreatedMetadata, MessageAttachmentRemovedMetadata, MessageChange, MessageCursor, MessageDeletedMetadata, MessageDirection, MessageEvent, MessageEventAttachment, MessageListItem, MessageMentionedMetadata, MessagePage, MessageParent, MessagePatch, MessagePatchedMetadata, MessagePostedMetadata, MessageThread, MessageThreadPreview, MessageTimelineData, MessageTimelineEntriesData, MessageTimelineEntriesResponse, MessageTimelineEntriesResponses, MessageTimelineEntry, MessageTimelinePage, MessageTimelineQuery, MessageTimelineResponse, MessageTimelineResponses, MessageTopicEvent, MyResponse, NewAttachment, NewColumn, NewOption, NewThreadAnchor, NewView, NotificationFilters, NotificationState, NumberOperator, OpBatch, Operator, OpRefusalResponse, OpResult, OptionId, OptionRef, PairingDetails, Params, ParticipantRole, PatchBotRequest, PatchChannelData, PatchChannelError, PatchChannelErrors, PatchChannelRequest, PatchChannelResponse, PatchChannelResponses, PatchMessageNotificationPolicy, PatchProjectRequestV2, PatchThreadRequestV2, PatchViewHandlerData, PatchViewHandlerError, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookError, PatchWebhookErrors, PatchWebhookRequest, PatchWebhookResponse, PatchWebhookResponses, PdfAnchor, PdfAnchorId, PdfHighlightAnchor, PdfHighlightAnchorRequest, PdfHighlightRect, PdfHighlightRectAnchorRequest, PdfPlaceableCommentAnchor, PendingClaimResponse, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentError, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponse, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectError, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponse, PermanentlyDeleteProjectResponses, PinnedItem, PinRequest, Pipeline, PipelineRecordType, PipelineSharing, PostActivityData, PostActivityError, PostActivityErrors, PostActivityRequest, PostActivityResponse, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookError, PostChannelBotWebhookErrors, PostChannelBotWebhookResponse, PostChannelBotWebhookResponses, PostGroupedSoupAstGroupPageRequest, PostGroupedSoupAstInitialRequest, PostGroupedSoupAstRequest, PostItemsSoupAstData, PostItemsSoupAstError, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedError, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponse, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponse, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupError, PostItemsSoupErrors, PostItemsSoupResponse, PostItemsSoupResponses, PostMessage, PostMessageNotificationPolicy, PostSoupAstRequest, PostSoupRequest, PresaveDocumentHandlerData, PresaveDocumentHandlerError, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponse, PresaveDocumentHandlerResponses, PreSaveDocumentRequest, PreSaveDocumentResponse, PreSaveDocumentResponseData, PresenceOperator, PresignedUrl, PreviewSmartTagData, PreviewSmartTagError, PreviewSmartTagErrors, PreviewSmartTagResponse, PreviewSmartTagResponses, Project, ProjectDeleteResponseData, ProjectDocumentStatus, ProjectFilters, ProjectPreview, ProjectPreviewData, PropertyDefinition, PropertyDefinitionWithOptions, PropertyFilter, PropertyInput, PropertyOption, PropertyOptionValue, PropertyOwner, PropertyValue, PutCrmTeamSettingsData, PutCrmTeamSettingsError, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponse, PutCrmTeamSettingsResponses, PutCrmTeamStagesData, PutCrmTeamStagesError, PutCrmTeamStagesErrors, PutCrmTeamStagesResponse, PutCrmTeamStagesResponses, PutFormLayoutData, PutFormLayoutError, PutFormLayoutErrors, PutFormLayoutResponse, PutFormLayoutResponses, QueryCrmPipelineRowsData, QueryCrmPipelineRowsResponse, QueryCrmPipelineRowsResponses, QueryDatabasesData, QueryDatabasesError, QueryDatabasesErrors, QueryDatabasesResponse, QueryDatabasesResponses, QueryDefinition, QuestionLayout, QuestionOption, QuestionTally, ReactionInput, RecentlyDeletedData, RecentlyDeletedError, RecentlyDeletedErrors, RecentlyDeletedResponse, RecentlyDeletedResponseData, RecentlyDeletedResponses, RegisterSlackImportUploadsData, RegisterSlackImportUploadsErrors, RegisterSlackImportUploadsResponse, RegisterSlackImportUploadsResponses, RegisterUploads, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotError, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponse, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityError, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsError, RemoveParticipantsErrors, RemoveParticipantsRequest, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerError, RemovePinHandlerErrors, RemovePinHandlerResponse, RemovePinHandlerResponses, RenameChannelLabelData, RenameChannelLabelError, RenameChannelLabelErrors, RenameChannelLabelRequest, RenameChannelLabelResponse, RenameChannelLabelResponses, RenameCrmPipelineData, RenameCrmPipelineResponse, RenameCrmPipelineResponses, RenamePipeline, ReorderFavoritesData, ReorderFavoritesError, ReorderFavoritesErrors, ReorderFavoritesRequest, ReorderFavoritesResponses, ReorderPinRequest, ReorderPinsHandlerData, ReorderPinsHandlerError, ReorderPinsHandlerErrors, ReorderPinsHandlerResponse, ReorderPinsHandlerResponses, ReplaceCrmStagesRequest, RequestAccess, RequestedHarnessScope, RequestedLayout, RequestStatus, RequestToJoinData, RequestToJoinError, RequestToJoinErrors, RequestToJoinResponse, RequestToJoinResponses, ResetCrmTeamStagesData, ResetCrmTeamStagesError, ResetCrmTeamStagesErrors, ResetCrmTeamStagesResponse, ResetCrmTeamStagesResponses, ResolveRequest, ResponseStatus, ResponseSummary, ResultColumn, ResultSet, RevertDeleteDocumentData, RevertDeleteDocumentError, RevertDeleteDocumentErrors, RevertDeleteDocumentResponse, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectError, RevertDeleteProjectErrors, RevertDeleteProjectResponse, RevertDeleteProjectResponses, RingStatus, RingStatusResponse, RowChange, RowChangeKind, RowChanges, RowHistoryEntry, RowHistoryResponse, RowId, RowsChange, RowsResult, S3ObjectInfo, SaveBomPart, SaveDatabaseQueryData, SaveDatabaseQueryError, SaveDatabaseQueryErrors, SaveDatabaseQueryResponse, SaveDatabaseQueryResponses, SaveDocumentHandlerData, SaveDocumentHandlerError, SaveDocumentHandlerErrors, SaveDocumentHandlerResponse, SaveDocumentHandlerResponses, SaveDocumentRequest, SaveDocumentResponse, SaveDocumentResponseData, SavedQuery, SaveQueryRequest, SearchContactsData, SearchContactsError, SearchContactsErrors, SearchContactsResponse, SearchContactsResponse2, SearchContactsResponses, SearchState, SectionCount, SessionDeletedMetadata, SessionIdentity, SessionMentionedMetadata, SessionOpenedMetadata, SessionRenamedMetadata, SessionSettledMetadata, SessionSource, SessionStoppedMetadata, SetChannelLabelData, SetChannelLabelError, SetChannelLabelErrors, SetChannelLabelRequest, SetChannelLabelResponse, SetChannelLabelResponses, SetChannelPictureData, SetChannelPictureError, SetChannelPictureErrors, SetChannelPictureRequest, SetChannelPictureResponse, SetChannelPictureResponses, SetCompanyHiddenData, SetCompanyHiddenError, SetCompanyHiddenErrors, SetCompanyHiddenRequest, SetCompanyHiddenResponse, SetCompanyHiddenResponses, SetCompanyNameRequest, SetContactHiddenData, SetContactHiddenError, SetContactHiddenErrors, SetContactHiddenRequest, SetContactHiddenResponse, SetContactHiddenResponses, SetContactNameRequest, SetCrmCompanyNameData, SetCrmCompanyNameError, SetCrmCompanyNameErrors, SetCrmCompanyNameResponse, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameError, SetCrmContactNameErrors, SetCrmContactNameResponse, SetCrmContactNameResponses, SetDirectAccess, SetDocumentTeamShareData, SetDocumentTeamShareError, SetDocumentTeamShareErrors, SetDocumentTeamShareRequest, SetDocumentTeamShareResponse, SetDocumentTeamShareResponses, SetEmailFollowupData, SetEmailFollowupError, SetEmailFollowupErrors, SetEmailFollowupResponse, SetEmailFollowupResponses, SetEmailSyncData, SetEmailSyncError, SetEmailSyncErrors, SetEmailSyncRequest, SetEmailSyncResponse, SetEmailSyncResponses, SetOperator, SetPropertyValue, Sha256Digest, ShareCrmPipelineData, ShareCrmPipelineResponse, ShareCrmPipelineResponses, ShareDatabaseAwarenessData, ShareDatabaseAwarenessError, ShareDatabaseAwarenessErrors, ShareDatabaseAwarenessResponse, ShareDatabaseAwarenessResponses, SharedEmailFilter, ShareEntity, ShareEntityType, SharePermissionV2, SharePipeline, ShortIdResponse, SimpleMention, SimpleSaveData, SimpleSaveError, SimpleSaveErrors, SimpleSaveResponse, SimpleSaveResponses, SkippedCell, SlackCompleteRequest, SlackCreateRequest, SlackRegisterRequest, SlackTimestamp, SlackUserId, SmartTagChannelMatch, SmartTagPreview, SortDirection, SortKey, SoupAgentSessionSoupPropertiesField, SoupApiItem, SoupApiSort, SoupApiSortDirection, SoupAttachment, SoupCalendarEventSoupPropertiesField, SoupCalendarEventTime, SoupCallRecordGuest, SoupCallRecordParticipant, SoupCallRecordSoupPropertiesField, SoupChannel, SoupChannelThread, SoupChatSoupPropertiesField, SoupContact, SoupCountedReaction, SoupCrmCompanySoupPropertiesField, SoupCrmContactSoupPropertiesField, SoupCrmDomain, SoupDatabaseRowSoupPropertiesField, SoupDocumentSoupPropertiesField, SoupDocumentSubType, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreviewSoupPropertiesField, SoupForeignEntity, SoupInitiativeSoupPropertiesField, SoupItem, SoupLabel, SoupLabelListVisibility, SoupLabelType, SoupMessageAttachment, SoupMessageListVisibility, SoupMessageSender, SoupMessageSenderType, SoupPage, SoupProjectSoupPropertiesField, SoupPropertiesField, SoupProperty, SoupThreadInfo, SoupThreadReply, SourceBinding, SourceId, SourceIdentity, SqlCell, SqlEntityKind, SqlOutcome, SqlOutcomeKind, SqlSelectOption, SqlStatement, StarterDatabase, StarterDocumentsResponse, StorageRow, StorageRows, StorageRowsQuery, StoredGithubPullRequest, StreamEventsData, StreamEventsError, StreamEventsErrors, StreamEventsResponse, StreamEventsResponses, String, Submission, SubmissionOutcome, SubmitFormResponseData, SubmitFormResponseError, SubmitFormResponseErrors, SubmitFormResponseResponse, SubmitFormResponseResponses, SuccessResponse, SurfaceState, SyncServiceVersionId, SystemSkillSummary, Table, TableChange, TableChanged, TableChanges, TableDetail, TableId, TableResult, TableVersion, TagFilterMode, TakenId, TallyBucket, TallyValue, TaskFilters, TeamCalendarContent, TeamCalendarCoverage, TeamCalendarDetails, TeamCalendarItem, TeamCalendarMember, TeamCalendarPage, TeamCalendarSharing, TeamOutOfOfficeItem, TeamOutOfOfficeResponse, TeamRole, TextOperator, ThreadAnchor, ThreadOrigin, ThreadPatch, ThreadState, TimelineActivity, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TouchedColumn, TouchedRow, TranscribeDictationData, TranscribeDictationError, TranscribeDictationErrors, TranscribeDictationResponse, TranscribeDictationResponses, TranscribeResponse, TranscriptSegmentRequest, TrashCrmPipelineData, TrashCrmPipelineResponse, TrashCrmPipelineResponses, TrashPipeline, TurnEndedMetadata, TurnStartedMetadata, TurnSummary, TypedSuccessResponse, TypedSuccessResponseGetDocumentResponseData, TypingInput, UndoChangeResponse, UndoDatabaseChangeData, UndoDatabaseChangeError, UndoDatabaseChangeErrors, UndoDatabaseChangeResponse, UndoDatabaseChangeResponses, UndoOutcome, UndoRefusal, UnlockedBooking, UpdateAgentData, UpdateAgentError, UpdateAgentErrors, UpdateAgentRequest, UpdateAgentResponse, UpdateAgentResponses, UpdateChannelSharePermission, UpdateCrmPipelinePermissionsData, UpdateCrmPipelinePermissionsResponse, UpdateCrmPipelinePermissionsResponses, UpdateCrmTeamSettingsRequest, UpdateDatabasePermissionsData, UpdateDatabasePermissionsError, UpdateDatabasePermissionsErrors, UpdateDatabasePermissionsResponse, UpdateDatabasePermissionsResponses, UpdateForm, UpdateFormData, UpdateFormError, UpdateFormErrors, UpdateFormPermissionsData, UpdateFormPermissionsError, UpdateFormPermissionsErrors, UpdateFormPermissionsResponse, UpdateFormPermissionsResponses, UpdateFormResponse, UpdateFormResponses, UpdateInitiativeData, UpdateInitiativeError, UpdateInitiativeErrors, UpdateInitiativeRequest, UpdateInitiativeResponse, UpdateInitiativeResponses, UpdateMeetingRequest, UpdateOperation, UpdateSharePermissionRequestV2, UploadDescriptor, UploadDocumentStatus, UploadExtractFolderHandlerData, UploadExtractFolderHandlerError, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponse, UploadExtractFolderHandlerResponses, UploadExtractFolderRequest, UploadFolderHandlerData, UploadFolderHandlerError, UploadFolderHandlerErrors, UploadFolderHandlerResponse, UploadFolderHandlerResponses, UploadFolderRequest, UploadGrant, UploadId, UpsertHistoryHandlerData, UpsertHistoryHandlerError, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponse, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationError, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationRequest, UpsertUserDocumentViewLocationResponse, UpsertUserDocumentViewLocationResponses, UserApiKeyId, UserApiKeyInfo, UserApiKeysList, UserDocumentsResponse, UserDocumentViewLocation, UserDocumentViewLocationResponse, UserPinsResponse, UserViewsResponse, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenError, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponse, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookError, ValidateWebhookErrors, ValidateWebhookResponse, ValidateWebhookResponse2, ValidateWebhookResponses, Vec, VersionedTable, View, ViewChange, ViewColumn, ViewerCapabilities, ViewLayout, ViewPatch, ViewPosition, ViewPositionsResponse, ViewQuery, ViewResult, ViewsResponse, WaitingForInputMetadata, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, WhatsAppCall, WhatsAppCallOutcome, WhatsAppContactCard, WhatsAppContacts, WhatsAppEvent, WhatsappGroupData, WhatsAppGroupDetail, WhatsAppGroupMessage, WhatsAppGroupMessages, WhatsappGroupMessagesData, WhatsappGroupMessagesResponse, WhatsappGroupMessagesResponses, WhatsappGroupPermissionsData, WhatsappGroupPermissionsResponse, WhatsappGroupPermissionsResponses, WhatsAppGroupReaction, WhatsappGroupReadData, WhatsappGroupReadResponse, WhatsappGroupReadResponses, WhatsappGroupResponse, WhatsappGroupResponses, WhatsappGroupsData, WhatsAppGroupSender, WhatsappGroupSendsData, WhatsappGroupSendsResponse, WhatsappGroupSendsResponses, WhatsappGroupsResponse, WhatsappGroupsResponses, WhatsAppGroupSummary, WhatsappGroupUpdatePermissionsData, WhatsappGroupUpdatePermissionsResponse, WhatsappGroupUpdatePermissionsResponses, WhatsAppLocation, WhatsAppMention, WhatsAppMessageKind, WhatsAppPersonRef, WhatsAppPoll, WhatsAppPollOption, WhatsAppRichContent, WhatsAppSystemAction, WhatsAppSystemLine, Widget, WithCallId, WithChannelId, WithDocumentId, WithProjectId } from './types.gen';
+export type { AccessiblePipeline, AccessLevel, AccessRequest, AccessRequestsCancelData, AccessRequestsCancelErrors, AccessRequestsCancelResponses, AccessRequestsDirectData, AccessRequestsDirectErrors, AccessRequestsDirectResponse, AccessRequestsDirectResponses, AccessRequestsRemoveDirectData, AccessRequestsRemoveDirectErrors, AccessRequestsRemoveDirectResponses, AccessRequestsResolveData, AccessRequestsResolveErrors, AccessRequestsResolveResponse, AccessRequestsResolveResponses, AccessRequestsSetDirectData, AccessRequestsSetDirectErrors, AccessRequestsSetDirectResponses, AccessRequestsStateData, AccessRequestsStateErrors, AccessRequestsStateResponse, AccessRequestsStateResponses, AccessRequestsSubmitData, AccessRequestsSubmitErrors, AccessRequestsSubmitResponse, AccessRequestsSubmitResponses, AccessRequestState, ActiveCallsResponse, ActiveCallSummary, ActiveMeeting, ActiveMeetingsResponse, ActivityType, AddFavoriteData, AddFavoriteError, AddFavoriteErrors, AddFavoriteRequest, AddFavoriteResponse, AddFavoriteResponses, AddParticipantsData, AddParticipantsError, AddParticipantsErrors, AddParticipantsRequest, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerError, AddPinHandlerErrors, AddPinHandlerResponse, AddPinHandlerResponses, AddPinRequest, AdoptedGroup, Agent, AgentActionId, AgentChannelScope, AgentDmProfile, AgentMcpServer, AgentMcpServers, AgentPullRequestState, AgentSessionFilters, AgentSessionLifecycleEvent, AgentSessionSource, AgentSessionVisibility, AgentTyping, AgentTypingPhase, Anchor, AnchorId, AnchorResponse, AnnotationIncrementalUpdate, Answer, ApiActivity, ApiAttachmentChannelReference, ApiAttachmentCommentReference, ApiAttachmentEntityReference, ApiAttachmentGenericReference, ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelDetail, ApiChannelListMessage, ApiChannelListPage, ApiChannelListParticipant, ApiChannelListType, ApiChannelParticipant, ApiChannelWithLatest, ApiEntityFilterAst, ApiGroupByField, ApiGroupMeta, ApiParticipantListRole, ApiParticipantRole, ApiPropertyEntityType, AppliedOps, ApplyCrmPipelineOpsData, ApplyCrmPipelineOpsResponse, ApplyCrmPipelineOpsResponses, ApplyDatabaseOpsData, ApplyDatabaseOpsError, ApplyDatabaseOpsErrors, ApplyDatabaseOpsResponse, ApplyDatabaseOpsResponses, ApplyOpsRequest, ApplyOpsResponse, ApproveHarnessPairingData, ApproveHarnessPairingError, ApproveHarnessPairingErrors, ApproveHarnessPairingResponse, ApproveHarnessPairingResponses, ApprovePairingRequest, AttachmentChange, AttendeeResponseStatus, Audience, Awareness, AwarenessRelay, BasicDocument, BasicDocumentSubType, BomPart, BookingTarget, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotOwnerProfile, BotSenderProfile, BotToken, BranchNameResponse, BTreeMap, BulkWakeupRequest, BulkWakeupResponse, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponse, BulkWakeupSyncServiceDocumentsResponses, CalendarAttendee, CalendarEvent, CalendarEventFilters, CalendarEventSourceContent, CalendarJoinRequest, CalendarJoinRequestApiError, CalendarJoinRequestErrorCode, CalendarJoinRequestsResponse, CalendarJoinRequestStatus, CalendarMentionEvent, CalendarMentionPreviewItem, CalendarMentionPreviewKind, CalendarMentionPreviewRequest, CalendarMentionPreviewRequestItem, CalendarMentionPreviewResponse, CalendarMentionViewerCopy, CalendarOccurrence, CalendarOccurrenceItem, CalendarOccurrenceResponse, CalendarSyncStatus, CallActiveResponse, CallFilters, CallProvider, CallRecord, CallRecordGuest, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordSource, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, CancelSlackImportData, CancelSlackImportErrors, CancelSlackImportResponse, CancelSlackImportResponses, CardPosition, CastVerdict, CellValue, CellWrite, ChangedFileDto, ChangesetDto, ChangesetSourceDto, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelFilters, ChannelJoinCodeResponse, ChannelLabel, ChannelLabelRule, ChannelLabelsList, ChannelMessage, ChannelParticipant, ChannelParticipantAddedMetadata, ChannelParticipantRemovedMetadata, ChannelPictureChangedMetadata, ChannelPreview, ChannelPreviewData, ChannelSender, ChannelSharePermission, ChannelThreadFilters, ChannelTopicEvent, ChannelType, ChannelUpdatedMetadata, ChannelWebhookRequest, ChannelWebhookResponse, ChannelWithParticipants, Chat, ChatFilters, CheckActiveCallData, CheckActiveCallError, CheckActiveCallErrors, CheckActiveCallResponse, CheckActiveCallResponses, ClaimedPairing, ClaimHarnessPairingData, ClaimHarnessPairingError, ClaimHarnessPairingErrors, ClaimHarnessPairingResponse, ClaimHarnessPairingResponses, ClaimPairingRequest, ClientOptions, CloudStorageItemType, CollaborateFormData, CollaborateFormError, CollaborateFormErrors, CollaborateFormResponse, CollaborateFormResponses, CollabSurfaceResponse, CollabSurfaceTokenResponse, Column, ColumnCast, ColumnChange, ColumnChangeKind, ColumnConfig, ColumnConversion, ColumnConversionRequest, ColumnDetail, ColumnId, ColumnKind, ColumnProtection, ColumnResult, CommandFailure, CommandRejectedMetadata, CommittedChange, CompleteSlackImportUploadsData, CompleteSlackImportUploadsErrors, CompleteSlackImportUploadsResponse, CompleteSlackImportUploadsResponses, CompleteUploads, ConferenceProvider, Conjunction, ConversationId, ConversationKind, ConversationMetadata, ConversationProgress, ConversationSeal, ConversationStatus, ConvertDatabaseColumnData, ConvertDatabaseColumnError, ConvertDatabaseColumnErrors, ConvertDatabaseColumnResponse, ConvertDatabaseColumnResponses, ConvertedCell, CopyDocumentData, CopyDocumentError, CopyDocumentErrors, CopyDocumentQueryParams, CopyDocumentRequest, CopyDocumentResponse, CopyDocumentResponse2, CopyDocumentResponses, CountedReaction, CreateAgentData, CreateAgentError, CreateAgentErrors, CreateAgentRequest, CreateAgentResponse, CreateAgentResponses, CreateAnchorData, CreateAnchorError, CreateAnchorErrors, CreateAnchorResponse, CreateAnchorResponses, CreateBotRequest, CreateBulkDocumentResponse, CreateBulkDocumentResponseData, CreateCanvasDocumentRequest, CreateCanvasDocumentResponse, CreateCanvasHandlerData, CreateCanvasHandlerError, CreateCanvasHandlerErrors, CreateCanvasHandlerResponse, CreateCanvasHandlerResponses, CreateChannelData, CreateChannelError, CreateChannelErrors, CreateChannelLabelData, CreateChannelLabelError, CreateChannelLabelErrors, CreateChannelLabelRequest, CreateChannelLabelResponse, CreateChannelLabelResponses, CreateChannelRequest, CreateChannelResponse, CreateChannelResponse2, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotError, CreateChannelScopedBotErrors, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, CreateChannelScopedBotResponse2, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenError, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponse, CreateCollabSurfaceTokenResponses, CreateCrmCompanyData, CreateCrmCompanyError, CreateCrmCompanyErrors, CreateCrmCompanyRequest, CreateCrmCompanyResponse, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactError, CreateCrmContactErrors, CreateCrmContactRequest, CreateCrmContactResponse, CreateCrmContactResponses, CreateCrmPipelineData, CreateCrmPipelineResponse, CreateCrmPipelineResponses, CreateDatabaseData, CreateDatabaseError, CreateDatabaseErrors, CreateDatabaseRequest, CreateDatabaseResponse, CreateDatabaseResponses, CreateDatabaseWebhookData, CreateDatabaseWebhookError, CreateDatabaseWebhookErrors, CreateDatabaseWebhookRequest, CreateDatabaseWebhookResponse, CreateDatabaseWebhookResponses, CreatedDatabaseWebhookResponse, CreateDocumentData, CreateDocumentError, CreateDocumentErrors, CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData, CreateDocumentResponses, CreatedPairing, CreatedUserApiKey, CreateEntityMentionData, CreateEntityMentionError, CreateEntityMentionErrors, CreateEntityMentionRequest, CreateEntityMentionResponse, CreateEntityMentionResponse2, CreateEntityMentionResponses, CreateForm, CreateFormData, CreateFormError, CreateFormErrors, CreateFormResponse, CreateFormResponses, CreateHarnessPairingData, CreateHarnessPairingError, CreateHarnessPairingErrors, CreateHarnessPairingResponse, CreateHarnessPairingResponses, CreateImport, CreateInitiativeData, CreateInitiativeError, CreateInitiativeErrors, CreateInitiativeRequest, CreateInitiativeResponse, CreateInitiativeResponses, CreateInstructionsDocumentResponse, CreateInstructionsHandlerData, CreateInstructionsHandlerError, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponse, CreateInstructionsHandlerResponses, CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, CreateMarkdownHandlerData, CreateMarkdownHandlerError, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponse, CreateMarkdownHandlerResponses, CreateMeetingRequest, CreatePairingRequest, CreatePipeline, CreateProjectHandlerData, CreateProjectHandlerError, CreateProjectHandlerErrors, CreateProjectHandlerResponse, CreateProjectHandlerResponses, CreateProjectRequest, CreateProjectResponse, CreateSkillHandlerData, CreateSkillHandlerError, CreateSkillHandlerErrors, CreateSkillHandlerResponse, CreateSkillHandlerResponses, CreateSkillRequest, CreateSkillResponse, CreateSlackImportData, CreateSlackImportErrors, CreateSlackImportResponse, CreateSlackImportResponses, CreateSnippetHandlerData, CreateSnippetHandlerError, CreateSnippetHandlerErrors, CreateSnippetHandlerResponse, CreateSnippetHandlerResponses, CreateSnippetRequest, CreateSnippetResponse, CreateTaskHandlerData, CreateTaskHandlerError, CreateTaskHandlerErrors, CreateTaskHandlerResponse, CreateTaskHandlerResponses, CreateTaskRequest, CreateTaskResponse, CreateToken, CreateUnthreadedAnchorRequest, CreateUnthreadedAnchorResponse, CreateUnthreadedPdfAnchorRequest, CreateUserApiKeyData, CreateUserApiKeyError, CreateUserApiKeyErrors, CreateUserApiKeyRequest, CreateUserApiKeyResponse, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerError, CreateViewHandlerErrors, CreateViewHandlerResponse, CreateViewHandlerResponses, CreateViewRequest, CreateWebhookData, CreateWebhookError, CreateWebhookErrors, CreateWebhookRequest, CreateWebhookResponse, CreateWebhookResponse2, CreateWebhookResponses, CrmAssociation, CrmCompanyFilters, CrmCompanyResponse, CrmContactResponse, CrmDomainResponse, CrmPermissionRole, CrmStageInput, CrmStageResponse, CrmStagesResponse, CrmTeamSettingsResponse, CustomSpeakerAssignment, Database, DatabaseDetail, DatabaseId, DatabaseOp, DatabaseQueryRequest, DatabaseView, DatabaseWebhookDeliveryResponse, DatabaseWebhookPayloadProblem, DatabaseWebhookResponse, DataType, DateOperator, DeclineCallData, DeclineCallError, DeclineCallErrors, DeclineCallResponse, DeclineCallResponses, DeclineRingData, DeclineRingError, DeclineRingErrors, DeclineRingResponse, DeclineRingResponses, DeleteAnchorData, DeleteAnchorError, DeleteAnchorErrors, DeleteAnchorResponse, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordError, DeleteCallRecordErrors, DeleteCallRecordResponse, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelError, DeleteChannelErrors, DeleteChannelLabelData, DeleteChannelLabelError, DeleteChannelLabelErrors, DeleteChannelLabelResponse, DeleteChannelLabelResponses, DeleteChannelResponse, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceError, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponse, DeleteCollabSurfaceResponses, DeleteDatabaseWebhookData, DeleteDatabaseWebhookError, DeleteDatabaseWebhookErrors, DeleteDatabaseWebhookResponse, DeleteDatabaseWebhookResponses, DeleteDocumentData, DeleteDocumentError, DeleteDocumentErrors, DeleteDocumentResponse, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionError, DeleteEntityMentionErrors, DeleteEntityMentionResponse, DeleteEntityMentionResponse2, DeleteEntityMentionResponses, DeleteHarnessData, DeleteHarnessError, DeleteHarnessErrors, DeleteHarnessResponse, DeleteHarnessResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerError, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponse, DeleteHistoryHandlerResponses, DeleteInitiativeData, DeleteInitiativeError, DeleteInitiativeErrors, DeleteInitiativeResponse, DeleteInitiativeResponses, DeleteProjectHandlerData, DeleteProjectHandlerError, DeleteProjectHandlerErrors, DeleteProjectHandlerResponse, DeleteProjectHandlerResponses, DeleteSelfHarnessData, DeleteSelfHarnessError, DeleteSelfHarnessErrors, DeleteSelfHarnessResponse, DeleteSelfHarnessResponses, DeleteUnthreadedAnchorRequest, DeleteUnthreadedAnchorResponse, DeleteUnthreadedPdfAnchorRequest, DeleteUserApiKeyData, DeleteUserApiKeyError, DeleteUserApiKeyErrors, DeleteUserApiKeyResponse, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationError, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponse, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerError, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookError, DeleteWebhookErrors, DeleteWebhookResponse, DeleteWebhookResponses, DeliverDatabaseWebhookData, DeliverDatabaseWebhookError, DeliverDatabaseWebhookErrors, DeliverDatabaseWebhookResponse, DeliverDatabaseWebhookResponses, DirectAccess, DocumentBasic, DocumentContent, DocumentContentLocation, DocumentContentState, DocumentContentUploadedMetadata, DocumentCopiedMetadata, DocumentCreatedMetadata, DocumentDeletedMetadata, DocumentFilters, DocumentId, DocumentInteractionMetadata, DocumentMetadata, DocumentMetadataWithContent, DocumentPermissionsToken, DocumentPermissionsTokenRequest, DocumentPermissionsTokenResponse, DocumentPreview, DocumentPreviewData, DocumentPreviewDataSubType, DocumentPurgedMetadata, DocumentResponse, DocumentResponseMetadata, DocumentResponseMetadataWithContent, DocumentStorageServiceApiVersion, DocumentSubType, DocumentSyncContentUpdatedMetadata, DocumentSyncEditor, DocumentTeamShareResponse, DocumentTextContent, DocumentTopicEvent, DocumentUpdatedMetadata, EditAnchorData, EditAnchorError, EditAnchorErrors, EditAnchorRequest, EditAnchorResponse, EditAnchorResponse2, EditAnchorResponses, EditCallRecordData, EditCallRecordError, EditCallRecordErrors, EditCallRecordRequest, EditCallRecordResponse, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptError, EditCallTranscriptErrors, EditCallTranscriptRequest, EditCallTranscriptResponse, EditCallTranscriptResponses, EditDocumentData, EditDocumentError, EditDocumentErrors, EditDocumentResponse, EditDocumentResponse2, EditDocumentResponses, EditDocumentServiceArgs, EditMyFormResponseData, EditMyFormResponseError, EditMyFormResponseErrors, EditMyFormResponseResponse, EditMyFormResponseResponses, EditPdfAnchorRequest, EditPdfPlaceableCommentAnchorRequest, EditProjectV2Data, EditProjectV2Error, EditProjectV2Errors, EditProjectV2Response, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Error, EditThreadV2Errors, EditThreadV2Response, EditThreadV2Responses, EmailFilters, EmailFollowup, EmailFollowupCommand, EmailFollowupResponse, EmailReminderCondition, EmailReminderPage, EmailReminderSummary, EmptyResponse, EnsureCollabSurfaceData, EnsureCollabSurfaceError, EnsureCollabSurfaceErrors, EnsureCollabSurfaceRequest, EnsureCollabSurfaceResponse, EnsureCollabSurfaceResponses, EnsureStarterHandlerData, EnsureStarterHandlerErrors, EnsureStarterHandlerResponse, EnsureStarterHandlerResponses, EntityFilters, EntityKind, EntityMessageCreateData, EntityMessageCreateResponse, EntityMessageCreateResponses, EntityMessageDeleteMessageData, EntityMessageDeleteMessageResponse, EntityMessageDeleteMessageResponses, EntityMessageDeleteThreadData, EntityMessageDeleteThreadResponse, EntityMessageDeleteThreadResponses, EntityMessageEditData, EntityMessageEditResponse, EntityMessageEditResponses, EntityMessageGetMessageData, EntityMessageGetMessageResponse, EntityMessageGetMessageResponses, EntityMessageGetThreadData, EntityMessageGetThreadResponse, EntityMessageGetThreadResponses, EntityMessageLegacyData, EntityMessageLegacyResponse, EntityMessageLegacyResponses, EntityMessagePatchThreadData, EntityMessagePatchThreadResponse, EntityMessagePatchThreadResponses, EntityMessageReactData, EntityMessageReactResponse, EntityMessageReactResponses, EntityMessageTypingData, EntityMessageTypingResponse, EntityMessageTypingResponses, EntityPermission, EntityPermissionResponse, EntityRef, EntityReference, EntityType, ErrorResponse, EventIcsData, EventIcsErrors, EventIcsResponse, EventIcsResponses, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventType, EventVisibility, ExcludedDefaultView, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerError, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExcludeDefaultViewRequest, ExportDocumentData, ExportDocumentError, ExportDocumentErrors, ExportDocumentResponse, ExportDocumentResponse2, ExportDocumentResponses, Favorite, FavoriteEntityRef, FavoritesList, FileChangeKindDto, FileSystemNodeWithIds, FileType, FileTypeUpdate, FilterCondition, FilterGroup, FilterNode, FilterTest, FinalizeSlackImportData, FinalizeSlackImportErrors, FinalizeSlackImportResponse, FinalizeSlackImportResponses, FolderItem, FollowupState, ForeignEntity, ForeignEntityFilters, Form, FormAccess, FormCollaboration, FormDetail, FormErrorCode, FormErrorResponse, FormLayout, FormPublicationProblem, FormQuestionDetail, FormResponse, FormSection, FormSectionDetail, FormSource, FormStatus, FormTally, Formula, GenericErrorResponse, GenericResponse, GenericSuccessResponse, GetActiveCallsData, GetActiveCallsError, GetActiveCallsErrors, GetActiveCallsResponse, GetActiveCallsResponses, GetActivityData, GetActivityError, GetActivityErrors, GetActivityResponse, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesError, GetAttachmentReferencesErrors, GetAttachmentReferencesResponse, GetAttachmentReferencesResponse2, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewError, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewRequest, GetBatchCallRecordPreviewResponse, GetBatchCallRecordPreviewResponse2, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewError, GetBatchChannelPreviewErrors, GetBatchChannelPreviewRequest, GetBatchChannelPreviewResponse, GetBatchChannelPreviewResponse2, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerError, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponse, GetBatchPreviewHandlerResponses, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchProjectPreviewData, GetBatchProjectPreviewError, GetBatchProjectPreviewErrors, GetBatchProjectPreviewRequest, GetBatchProjectPreviewResponse, GetBatchProjectPreviewResponse2, GetBatchProjectPreviewResponses, GetBotOwnerProfilesData, GetBotOwnerProfilesError, GetBotOwnerProfilesErrors, GetBotOwnerProfilesResponse, GetBotOwnerProfilesResponses, GetCallRecordData, GetCallRecordError, GetCallRecordErrors, GetCallRecordResponse, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsError, GetChannelAttachmentsErrors, GetChannelAttachmentsResponse, GetChannelAttachmentsResponses, GetChannelData, GetChannelError, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkError, GetChannelJoinLinkErrors, GetChannelJoinLinkResponse, GetChannelJoinLinkResponses, GetChannelParticipantsData, GetChannelParticipantsError, GetChannelParticipantsErrors, GetChannelParticipantsResponse, GetChannelParticipantsResponses, GetChannelResponse, GetChannelResponses, GetChannelsData, GetChannelsError, GetChannelsErrors, GetChannelsResponse, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceError, GetCollabSurfaceErrors, GetCollabSurfaceResponse, GetCollabSurfaceResponses, GetCompanyData, GetCompanyError, GetCompanyErrors, GetCompanyResponse, GetCompanyResponses, GetContactByEmailData, GetContactByEmailError, GetContactByEmailErrors, GetContactByEmailResponse, GetContactByEmailResponse2, GetContactByEmailResponses, GetContactData, GetContactError, GetContactErrors, GetContactResponse, GetContactResponses, GetCrmPipelineData, GetCrmPipelinePermissionsData, GetCrmPipelinePermissionsResponse, GetCrmPipelinePermissionsResponses, GetCrmPipelineResponse, GetCrmPipelineResponses, GetCrmPipelineRowsData, GetCrmPipelineRowsResponse, GetCrmPipelineRowsResponses, GetCrmPipelineTableData, GetCrmPipelineTableResponse, GetCrmPipelineTableResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsError, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponse, GetCrmTeamSettingsResponses, GetDatabaseData, GetDatabaseError, GetDatabaseErrors, GetDatabasePermissionsData, GetDatabasePermissionsError, GetDatabasePermissionsErrors, GetDatabasePermissionsResponse, GetDatabasePermissionsResponses, GetDatabaseQueryData, GetDatabaseQueryError, GetDatabaseQueryErrors, GetDatabaseQueryResponse, GetDatabaseQueryResponses, GetDatabaseResponse, GetDatabaseResponses, GetDatabaseRowHistoryData, GetDatabaseRowHistoryError, GetDatabaseRowHistoryErrors, GetDatabaseRowHistoryResponse, GetDatabaseRowHistoryResponses, GetDatabaseTableChangesData, GetDatabaseTableChangesError, GetDatabaseTableChangesErrors, GetDatabaseTableChangesResponse, GetDatabaseTableChangesResponses, GetDatabaseViewPositionsData, GetDatabaseViewPositionsError, GetDatabaseViewPositionsErrors, GetDatabaseViewPositionsResponse, GetDatabaseViewPositionsResponses, GetDocumentAnchorsData, GetDocumentAnchorsError, GetDocumentAnchorsErrors, GetDocumentAnchorsResponse, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameError, GetDocumentBranchNameErrors, GetDocumentBranchNameResponse, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugError, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponse, GetDocumentByTeamSlugResponses, GetDocumentData, GetDocumentError, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsError, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponse, GetDocumentGithubPullRequestsResponses, GetDocumentKeyResponse, GetDocumentKeyResponseData, GetDocumentListHandlerData, GetDocumentListHandlerError, GetDocumentListHandlerErrors, GetDocumentListHandlerResponse, GetDocumentListHandlerResponses, GetDocumentListResult, GetDocumentLocationV3Data, GetDocumentLocationV3Error, GetDocumentLocationV3Errors, GetDocumentLocationV3Response, GetDocumentLocationV3Responses, GetDocumentPermissionsResponseDataV2, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenError, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponse, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Error, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Response, GetDocumentPermissionsV2Responses, GetDocumentProcessingResult, GetDocumentProcessingResultData, GetDocumentProcessingResultError, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponse, GetDocumentProcessingResultResponse2, GetDocumentProcessingResultResponses, GetDocumentResponse, GetDocumentResponse2, GetDocumentResponseData, GetDocumentResponses, GetDocumentSearchResponse, GetDocumentShortIdData, GetDocumentShortIdError, GetDocumentShortIdErrors, GetDocumentShortIdResponse, GetDocumentShortIdResponses, GetDocumentsResponse, GetDocumentTeamShareData, GetDocumentTeamShareError, GetDocumentTeamShareErrors, GetDocumentTeamShareResponse, GetDocumentTeamShareResponses, GetDocumentTextContentData, GetDocumentTextContentErrors, GetDocumentTextContentResponse, GetDocumentTextContentResponses, GetDocumentUserAccessLevelResponse, GetDocumentVersionData, GetDocumentVersionError, GetDocumentVersionErrors, GetDocumentVersionResponse, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerError, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponse, GetDocumentViewsHandlerResponses, GetEmailFollowupData, GetEmailFollowupError, GetEmailFollowupErrors, GetEmailFollowupResponse, GetEmailFollowupResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponse, GetEntityPermissionResponses, GetForeignEntityBySourceData, GetForeignEntityBySourceError, GetForeignEntityBySourceErrors, GetForeignEntityBySourceResponse, GetForeignEntityBySourceResponses, GetForeignEntityData, GetForeignEntityError, GetForeignEntityErrors, GetForeignEntityResponse, GetForeignEntityResponses, GetFormData, GetFormError, GetFormErrors, GetFormPermissionsData, GetFormPermissionsError, GetFormPermissionsErrors, GetFormPermissionsResponse, GetFormPermissionsResponses, GetFormResponse, GetFormResponses, GetFormResponseSummaryData, GetFormResponseSummaryError, GetFormResponseSummaryErrors, GetFormResponseSummaryResponse, GetFormResponseSummaryResponses, GetFormTallyData, GetFormTallyError, GetFormTallyErrors, GetFormTallyResponse, GetFormTallyResponses, GetGithubPullRequestChangesData, GetGithubPullRequestChangesError, GetGithubPullRequestChangesErrors, GetGithubPullRequestChangesPatchData, GetGithubPullRequestChangesPatchError, GetGithubPullRequestChangesPatchErrors, GetGithubPullRequestChangesPatchResponse, GetGithubPullRequestChangesPatchResponses, GetGithubPullRequestChangesResponse, GetGithubPullRequestChangesResponses, GetGithubPullRequestData, GetGithubPullRequestError, GetGithubPullRequestErrors, GetGithubPullRequestFacetsData, GetGithubPullRequestFacetsError, GetGithubPullRequestFacetsErrors, GetGithubPullRequestFacetsResponse, GetGithubPullRequestFacetsResponses, GetGithubPullRequestResponse, GetGithubPullRequestResponses, GetGithubPullRequestTasksData, GetGithubPullRequestTasksError, GetGithubPullRequestTasksErrors, GetGithubPullRequestTasksResponse, GetGithubPullRequestTasksResponses, GetHarnessPairingData, GetHarnessPairingError, GetHarnessPairingErrors, GetHarnessPairingResponse, GetHarnessPairingResponses, GetHistoryHandlerData, GetHistoryHandlerError, GetHistoryHandlerErrors, GetHistoryHandlerResponse, GetHistoryHandlerResponses, GetInitiativeData, GetInitiativeError, GetInitiativeErrors, GetInitiativeResponse, GetInitiativeResponses, GetInstructionsDocumentResponse, GetInstructionsHandlerData, GetInstructionsHandlerError, GetInstructionsHandlerErrors, GetInstructionsHandlerResponse, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupError, GetItemsSoupErrors, GetItemsSoupResponse, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerError, GetLocationHandlerErrors, GetLocationHandlerResponse, GetLocationHandlerResponses, GetMyFormResponseData, GetMyFormResponseError, GetMyFormResponseErrors, GetMyFormResponseResponse, GetMyFormResponseResponses, GetOrCreateAction, GetOrCreateCallData, GetOrCreateCallError, GetOrCreateCallErrors, GetOrCreateCallResponse, GetOrCreateCallResponses, GetOrCreateChannelResponse, GetOrCreateDmData, GetOrCreateDmError, GetOrCreateDmErrors, GetOrCreateDmRequest, GetOrCreateDmResponse, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateError, GetOrCreatePrivateErrors, GetOrCreatePrivateRequest, GetOrCreatePrivateResponse, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerError, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponse, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerError, GetPinsHandlerErrors, GetPinsHandlerResponse, GetPinsHandlerResponses, GetPinsResponse, GetProjectContentHandlerData, GetProjectContentHandlerError, GetProjectContentHandlerErrors, GetProjectContentHandlerResponse, GetProjectContentHandlerResponses, GetProjectContentResponse, GetProjectHandlerData, GetProjectHandlerError, GetProjectHandlerErrors, GetProjectHandlerResponse, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Error, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Response, GetProjectPermissionsV2Responses, GetProjectResponse, GetProjectResponseData, GetProjectsHandlerData, GetProjectsHandlerError, GetProjectsHandlerErrors, GetProjectsHandlerResponse, GetProjectsHandlerResponses, GetProjectsResponse, GetProjectUserAccessLevelData, GetProjectUserAccessLevelError, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponse, GetProjectUserAccessLevelResponses, GetRingStatusData, GetRingStatusError, GetRingStatusErrors, GetRingStatusResponse, GetRingStatusResponses, GetSelfBotData, GetSelfBotError, GetSelfBotErrors, GetSelfBotResponse, GetSelfBotResponses, GetSelfHarnessData, GetSelfHarnessError, GetSelfHarnessErrors, GetSelfHarnessResponse, GetSelfHarnessResponses, GetSlackImportData, GetSlackImportErrors, GetSlackImportResponse, GetSlackImportResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerError, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponse, GetSystemSkillsHandlerResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerError, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponse, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationError, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponse, GetUserDocumentViewLocationResponses, GetUserHistoryResponse, GetViewsHandlerData, GetViewsHandlerError, GetViewsHandlerErrors, GetViewsHandlerResponse, GetViewsHandlerResponses, GetWebhookData, GetWebhookError, GetWebhookErrors, GetWebhookResponse, GetWebhookResponses, GithubLabelFacet, GithubPullRequest, GithubPullRequestChangesPatchResponse, GithubPullRequestChangesResponse, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestFacets, GithubPullRequestLabel, GithubPullRequestReview, GithubPullRequestReviewDecision, GithubPullRequestReviewState, GithubPullRequestsResponse, GithubPullRequestTasks, GithubPullRequestTasksRequest, GithubPullRequestTasksResponse, GithubPullRequestUser, GithubRepositoryFacet, GithubUserFacet, GitRefDto, GroupedInitialParams, GroupedPageParams, GroupedSoupGroupPage, GroupedSoupInitialPage, GroupedSoupPage, GroupedSoupSort, GuestCallChatPostData, GuestCallChatPostErrors, GuestCallChatPostResponse, GuestCallChatPostResponses, GuestCallChatReadData, GuestCallChatReadErrors, GuestCallChatReadResponse, GuestCallChatReadResponses, GuestChatMessage, GuestChatPage, GuestChatPost, GuestId, GuestJoinRequest, GuestPolicy, HandlerData, HandlerError, HandlerErrors, HandlerResponse, HandlerResponses, Harness, HarnessAgent, HarnessId, HarnessOwner, HarnessSession, HashMap, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HighlightType, ImportCounters, ImportDatabaseTableData, ImportDatabaseTableError, ImportDatabaseTableErrors, ImportDatabaseTableResponse, ImportDatabaseTableResponses, ImportedAuthor, ImportError, ImportLimits, ImportPage, ImportProgress, ImportTable, ImportWarning, InferColumnTypeOutcome, InferColumnTypeRequest, InferDatabaseColumnTypeData, InferDatabaseColumnTypeError, InferDatabaseColumnTypeErrors, InferDatabaseColumnTypeResponse, InferDatabaseColumnTypeResponses, InFlightTurnSummary, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InitialPropertyValue, InitiativeDetail, InitiativeFilters, InitiativeId, InitiativeList, InitiativeSummary, InputReceivedMetadata, InstallSyncData, InstallSyncErrors, InteractionReason, InvalidDatabaseWebhookPayloadResponse, InviteMeetingRequest, InviteMeetingUsersRequest, Item, ItemWithUserAccessLevel, JobId, JobProcessingResultHandlerData, JobProcessingResultHandlerError, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponse, JobProcessingResultHandlerResponses, JobStatus, JoinChannelByCodeData, JoinChannelByCodeError, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelError, JoinChannelErrors, JoinChannelResponses, KeySegment, Lane, LaneKey, LatestMessage, LayoutProblem, LeaveCallResponse, LeaveChannelData, LeaveChannelError, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallError, LeaveOrEndCallErrors, LeaveOrEndCallResponse, LeaveOrEndCallResponses, LinkedAccount, LinkedAccountData, LinkedAccountResponse, LinkedAccountResponses, LinkedAccountState, LinkedAccountView, LinkedAdoptData, LinkedAdoptGroup, LinkedAdoptResponse, LinkedAdoptResponses, LinkedAttachment, LinkedAttachmentState, LinkedBackfill, LinkedBackfillState, LinkedCancelPairingData, LinkedCancelPairingResponse, LinkedCancelPairingResponses, LinkedCannotAdd, LinkedCapabilities, LinkedChat, LinkedChatKind, LinkedChats, LinkedChatsData, LinkedChatsResponse, LinkedChatsResponses, LinkedCommunityReference, LinkedConfigurationData, LinkedConfigurationResponse, LinkedConfigurationResponses, LinkedConnect, LinkedConnectData, LinkedConnectResponse, LinkedConnectResponses, LinkedDeliveryData, LinkedDeliveryResponse, LinkedDeliveryResponses, LinkedDeliveryState, LinkedDetachData, LinkedDetachResponse, LinkedDetachResponses, LinkedDisconnect, LinkedDisconnectData, LinkedDisconnectRequest, LinkedDisconnectResponse, LinkedDisconnectResponses, LinkedFeatures, LinkedGroupReference, LinkedMediaKind, LinkedMediaPresentation, LinkedMessageAttachments, LinkedMessageAttachmentsData, LinkedMessageAttachmentsResponse, LinkedMessageAttachmentsResponses, LinkedMutation, LinkedPairing, LinkedPairingData, LinkedPairingResponse, LinkedPairingResponses, LinkedPairingState, LinkedPairState, LinkedPasskeyData, LinkedPasskeyResponse, LinkedPasskeyResponses, LinkedReplyBlock, LinkedReplyContent, LinkedReplyData, LinkedReplyErrors, LinkedReplyResponse, LinkedReplyResponses, LinkedSendProgress, LinkedSendReply, LinkedSharedGroupReference, LinkedUploadData, LinkedUploadedAttachment, LinkedUploadRequest, LinkedUploadResponse, LinkedUploadResponses, LinkShare, ListAccessibleFormsData, ListAccessibleFormsError, ListAccessibleFormsErrors, ListAccessibleFormsResponse, ListAccessibleFormsResponses, ListAgentsData, ListAgentsError, ListAgentsErrors, ListAgentsResponse, ListAgentsResponses, ListBotChannelsData, ListBotChannelsError, ListBotChannelsErrors, ListBotChannelsResponse, ListBotChannelsResponses, ListChannelLabelsData, ListChannelLabelsError, ListChannelLabelsErrors, ListChannelLabelsResponse, ListChannelLabelsResponses, ListCompanyContactsData, ListCompanyContactsError, ListCompanyContactsErrors, ListCompanyContactsResponse, ListCompanyContactsResponses, ListCrmPipelinesData, ListCrmPipelinesResponse, ListCrmPipelinesResponses, ListDatabaseColumnCastsData, ListDatabaseColumnCastsError, ListDatabaseColumnCastsErrors, ListDatabaseColumnCastsResponse, ListDatabaseColumnCastsResponses, ListDatabasesData, ListDatabasesError, ListDatabasesErrors, ListDatabasesResponse, ListDatabasesResponses, ListDatabaseWebhooksData, ListDatabaseWebhooksError, ListDatabaseWebhooksErrors, ListDatabaseWebhooksResponse, ListDatabaseWebhooksResponse2, ListDatabaseWebhooksResponses, ListedDatabase, ListedForm, ListEmailRemindersData, ListEmailRemindersError, ListEmailRemindersErrors, ListEmailRemindersResponse, ListEmailRemindersResponses, ListFavoritesData, ListFavoritesError, ListFavoritesErrors, ListFavoritesResponse, ListFavoritesResponses, ListFormsData, ListFormsError, ListFormsErrors, ListFormsResponse, ListFormsResponses, ListHarnessAgentsData, ListHarnessAgentsError, ListHarnessAgentsErrors, ListHarnessAgentsResponse, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesError, ListHarnessesErrors, ListHarnessesResponse, ListHarnessesResponses, ListHarnessSessionsData, ListHarnessSessionsError, ListHarnessSessionsErrors, ListHarnessSessionsResponse, ListHarnessSessionsResponses, ListInitiativesData, ListInitiativesError, ListInitiativesErrors, ListInitiativesResponse, ListInitiativesResponses, ListJoinRequestsData, ListJoinRequestsError, ListJoinRequestsErrors, ListJoinRequestsResponse, ListJoinRequestsResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponse, ListOccurrencesResponses, ListSlackImportsData, ListSlackImportsResponse, ListSlackImportsResponses, ListTeamCalendarData, ListTeamCalendarResponse, ListTeamCalendarResponses, ListTeamOutOfOfficeData, ListTeamOutOfOfficeErrors, ListTeamOutOfOfficeResponse, ListTeamOutOfOfficeResponses, ListUserApiKeysData, ListUserApiKeysError, ListUserApiKeysErrors, ListUserApiKeysResponse, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, MarkRead, Meeting, MeetingCancelData, MeetingCancelError, MeetingCancelErrors, MeetingCancelPreparationData, MeetingCancelPreparationError, MeetingCancelPreparationErrors, MeetingCancelPreparationResponse, MeetingCancelPreparationResponses, MeetingCancelResponse, MeetingCancelResponses, MeetingCreateData, MeetingCreateError, MeetingCreateErrors, MeetingCreateResponse, MeetingCreateResponses, MeetingGuestJoinData, MeetingGuestJoinError, MeetingGuestJoinErrors, MeetingGuestJoinResponse, MeetingGuestJoinResponses, MeetingGuestParticipantsData, MeetingGuestParticipantsError, MeetingGuestParticipantsErrors, MeetingGuestParticipantsResponse, MeetingGuestParticipantsResponses, MeetingInviteData, MeetingInviteError, MeetingInviteErrors, MeetingInvitePermissions, MeetingInvitePermissionsData, MeetingInvitePermissionsError, MeetingInvitePermissionsErrors, MeetingInvitePermissionsResponse, MeetingInvitePermissionsResponses, MeetingInviteResponse, MeetingInviteResponses, MeetingInviteUsersData, MeetingInviteUsersError, MeetingInviteUsersErrors, MeetingInviteUsersResponse, MeetingInviteUsersResponses, MeetingJoinData, MeetingJoinError, MeetingJoinErrors, MeetingJoinResponse, MeetingJoinResponses, MeetingLeaveData, MeetingLeaveError, MeetingLeaveErrors, MeetingLeaveResponse, MeetingLeaveResponses, MeetingListActiveData, MeetingListActiveError, MeetingListActiveErrors, MeetingListActiveResponse, MeetingListActiveResponses, MeetingListData, MeetingListError, MeetingListErrors, MeetingListResponse, MeetingListResponses, MeetingLookupData, MeetingLookupError, MeetingLookupErrors, MeetingLookupResponse, MeetingLookupResponses, MeetingParticipant, MeetingParticipants, MeetingParticipantsData, MeetingParticipantsError, MeetingParticipantsErrors, MeetingParticipantsResponse, MeetingParticipantsResponses, MeetingPreparation, MeetingPrepareData, MeetingPrepareError, MeetingPrepareErrors, MeetingPrepareResponse, MeetingPrepareResponses, MeetingShareData, MeetingShareError, MeetingShareErrors, MeetingShareResponse, MeetingShareResponses, MeetingsResponse, MeetingToken, MeetingUpdateData, MeetingUpdateError, MeetingUpdateErrors, MeetingUpdateResponse, MeetingUpdateResponses, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponse, MentionPreviewsResponses, Message, MessageAttachment, MessageAttachmentCreatedMetadata, MessageAttachmentRemovedMetadata, MessageChange, MessageCursor, MessageDeletedMetadata, MessageDirection, MessageEvent, MessageEventAttachment, MessageListItem, MessageMentionedMetadata, MessagePage, MessageParent, MessagePatch, MessagePatchedMetadata, MessagePostedMetadata, MessageThread, MessageThreadPreview, MessageTimelineData, MessageTimelineEntriesData, MessageTimelineEntriesResponse, MessageTimelineEntriesResponses, MessageTimelineEntry, MessageTimelinePage, MessageTimelineQuery, MessageTimelineResponse, MessageTimelineResponses, MessageTopicEvent, MyResponse, NewAttachment, NewColumn, NewOption, NewThreadAnchor, NewView, NotificationFilters, NotificationState, NumberOperator, OpBatch, Operator, OpRefusalResponse, OpResult, OptionId, OptionRef, PairingDetails, Params, ParticipantRole, PatchBotRequest, PatchChannelData, PatchChannelError, PatchChannelErrors, PatchChannelRequest, PatchChannelResponse, PatchChannelResponses, PatchMessageNotificationPolicy, PatchProjectRequestV2, PatchThreadRequestV2, PatchViewHandlerData, PatchViewHandlerError, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookError, PatchWebhookErrors, PatchWebhookRequest, PatchWebhookResponse, PatchWebhookResponses, PdfAnchor, PdfAnchorId, PdfHighlightAnchor, PdfHighlightAnchorRequest, PdfHighlightRect, PdfHighlightRectAnchorRequest, PdfPlaceableCommentAnchor, PendingClaimResponse, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentError, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponse, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectError, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponse, PermanentlyDeleteProjectResponses, PinnedItem, PinRequest, Pipeline, PipelineRecordType, PipelineSharing, PostActivityData, PostActivityError, PostActivityErrors, PostActivityRequest, PostActivityResponse, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookError, PostChannelBotWebhookErrors, PostChannelBotWebhookResponse, PostChannelBotWebhookResponses, PostGroupedSoupAstGroupPageRequest, PostGroupedSoupAstInitialRequest, PostGroupedSoupAstRequest, PostItemsSoupAstData, PostItemsSoupAstError, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedError, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponse, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponse, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupError, PostItemsSoupErrors, PostItemsSoupResponse, PostItemsSoupResponses, PostMessage, PostMessageNotificationPolicy, PostSoupAstRequest, PostSoupRequest, PresaveDocumentHandlerData, PresaveDocumentHandlerError, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponse, PresaveDocumentHandlerResponses, PreSaveDocumentRequest, PreSaveDocumentResponse, PreSaveDocumentResponseData, PresenceOperator, PresignedUrl, PreviewSmartTagData, PreviewSmartTagError, PreviewSmartTagErrors, PreviewSmartTagResponse, PreviewSmartTagResponses, Project, ProjectDeleteResponseData, ProjectDocumentStatus, ProjectFilters, ProjectPreview, ProjectPreviewData, PropertyDefinition, PropertyDefinitionWithOptions, PropertyFilter, PropertyInput, PropertyOption, PropertyOptionValue, PropertyOwner, PropertyValue, PutCrmTeamSettingsData, PutCrmTeamSettingsError, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponse, PutCrmTeamSettingsResponses, PutCrmTeamStagesData, PutCrmTeamStagesError, PutCrmTeamStagesErrors, PutCrmTeamStagesResponse, PutCrmTeamStagesResponses, PutFormLayoutData, PutFormLayoutError, PutFormLayoutErrors, PutFormLayoutResponse, PutFormLayoutResponses, QueryCrmPipelineRowsData, QueryCrmPipelineRowsResponse, QueryCrmPipelineRowsResponses, QueryDatabasesData, QueryDatabasesError, QueryDatabasesErrors, QueryDatabasesResponse, QueryDatabasesResponses, QueryDefinition, QuestionLayout, QuestionOption, QuestionTally, ReactionInput, RecentlyDeletedData, RecentlyDeletedError, RecentlyDeletedErrors, RecentlyDeletedResponse, RecentlyDeletedResponseData, RecentlyDeletedResponses, RegisterSlackImportUploadsData, RegisterSlackImportUploadsErrors, RegisterSlackImportUploadsResponse, RegisterSlackImportUploadsResponses, RegisterUploads, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotError, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponse, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityError, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsError, RemoveParticipantsErrors, RemoveParticipantsRequest, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerError, RemovePinHandlerErrors, RemovePinHandlerResponse, RemovePinHandlerResponses, RenameChannelLabelData, RenameChannelLabelError, RenameChannelLabelErrors, RenameChannelLabelRequest, RenameChannelLabelResponse, RenameChannelLabelResponses, RenameCrmPipelineData, RenameCrmPipelineResponse, RenameCrmPipelineResponses, RenamePipeline, ReorderFavoritesData, ReorderFavoritesError, ReorderFavoritesErrors, ReorderFavoritesRequest, ReorderFavoritesResponses, ReorderPinRequest, ReorderPinsHandlerData, ReorderPinsHandlerError, ReorderPinsHandlerErrors, ReorderPinsHandlerResponse, ReorderPinsHandlerResponses, ReplaceCrmStagesRequest, RequestAccess, RequestedHarnessScope, RequestedLayout, RequestStatus, RequestToJoinData, RequestToJoinError, RequestToJoinErrors, RequestToJoinResponse, RequestToJoinResponses, ResetCrmTeamStagesData, ResetCrmTeamStagesError, ResetCrmTeamStagesErrors, ResetCrmTeamStagesResponse, ResetCrmTeamStagesResponses, ResolveRequest, ResponseStatus, ResponseSummary, ResultColumn, ResultSet, RevertDeleteDocumentData, RevertDeleteDocumentError, RevertDeleteDocumentErrors, RevertDeleteDocumentResponse, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectError, RevertDeleteProjectErrors, RevertDeleteProjectResponse, RevertDeleteProjectResponses, RingStatus, RingStatusResponse, RowChange, RowChangeKind, RowChanges, RowHistoryEntry, RowHistoryResponse, RowId, RowsChange, RowsResult, S3ObjectInfo, SaveBomPart, SaveDatabaseQueryData, SaveDatabaseQueryError, SaveDatabaseQueryErrors, SaveDatabaseQueryResponse, SaveDatabaseQueryResponses, SaveDocumentHandlerData, SaveDocumentHandlerError, SaveDocumentHandlerErrors, SaveDocumentHandlerResponse, SaveDocumentHandlerResponses, SaveDocumentRequest, SaveDocumentResponse, SaveDocumentResponseData, SavedQuery, SaveQueryRequest, SearchContactsData, SearchContactsError, SearchContactsErrors, SearchContactsResponse, SearchContactsResponse2, SearchContactsResponses, SearchState, SectionCount, SessionDeletedMetadata, SessionIdentity, SessionMentionedMetadata, SessionOpenedMetadata, SessionRenamedMetadata, SessionSettledMetadata, SessionSource, SessionStoppedMetadata, SetChannelLabelData, SetChannelLabelError, SetChannelLabelErrors, SetChannelLabelRequest, SetChannelLabelResponse, SetChannelLabelResponses, SetChannelPictureData, SetChannelPictureError, SetChannelPictureErrors, SetChannelPictureRequest, SetChannelPictureResponse, SetChannelPictureResponses, SetCompanyHiddenData, SetCompanyHiddenError, SetCompanyHiddenErrors, SetCompanyHiddenRequest, SetCompanyHiddenResponse, SetCompanyHiddenResponses, SetCompanyNameRequest, SetContactHiddenData, SetContactHiddenError, SetContactHiddenErrors, SetContactHiddenRequest, SetContactHiddenResponse, SetContactHiddenResponses, SetContactNameRequest, SetCrmCompanyNameData, SetCrmCompanyNameError, SetCrmCompanyNameErrors, SetCrmCompanyNameResponse, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameError, SetCrmContactNameErrors, SetCrmContactNameResponse, SetCrmContactNameResponses, SetDirectAccess, SetDocumentTeamShareData, SetDocumentTeamShareError, SetDocumentTeamShareErrors, SetDocumentTeamShareRequest, SetDocumentTeamShareResponse, SetDocumentTeamShareResponses, SetEmailFollowupData, SetEmailFollowupError, SetEmailFollowupErrors, SetEmailFollowupResponse, SetEmailFollowupResponses, SetEmailSyncData, SetEmailSyncError, SetEmailSyncErrors, SetEmailSyncRequest, SetEmailSyncResponse, SetEmailSyncResponses, SetOperator, SetPropertyValue, Sha256Digest, ShareCrmPipelineData, ShareCrmPipelineResponse, ShareCrmPipelineResponses, ShareDatabaseAwarenessData, ShareDatabaseAwarenessError, ShareDatabaseAwarenessErrors, ShareDatabaseAwarenessResponse, ShareDatabaseAwarenessResponses, SharedEmailFilter, ShareEntity, ShareEntityType, SharePermissionV2, SharePipeline, ShortIdResponse, SimpleMention, SimpleSaveData, SimpleSaveError, SimpleSaveErrors, SimpleSaveResponse, SimpleSaveResponses, SkippedCell, SlackCompleteRequest, SlackCreateRequest, SlackRegisterRequest, SlackTimestamp, SlackUserId, SmartTagChannelMatch, SmartTagPreview, SortDirection, SortKey, SoupAgentSessionSoupPropertiesField, SoupApiItem, SoupApiSort, SoupApiSortDirection, SoupAttachment, SoupCalendarEventSoupPropertiesField, SoupCalendarEventTime, SoupCallRecordGuest, SoupCallRecordParticipant, SoupCallRecordSoupPropertiesField, SoupChannel, SoupChannelThread, SoupChatSoupPropertiesField, SoupContact, SoupCountedReaction, SoupCrmCompanySoupPropertiesField, SoupCrmContactSoupPropertiesField, SoupCrmDomain, SoupDatabaseRowSoupPropertiesField, SoupDocumentSoupPropertiesField, SoupDocumentSubType, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreviewSoupPropertiesField, SoupForeignEntity, SoupInitiativeSoupPropertiesField, SoupItem, SoupLabel, SoupLabelListVisibility, SoupLabelType, SoupMessageAttachment, SoupMessageListVisibility, SoupMessageSender, SoupMessageSenderType, SoupPage, SoupProjectSoupPropertiesField, SoupPropertiesField, SoupProperty, SoupThreadInfo, SoupThreadReply, SourceBinding, SourceId, SourceIdentity, SqlCell, SqlEntityKind, SqlOutcome, SqlOutcomeKind, SqlSelectOption, SqlStatement, StarterDatabase, StarterDocumentsResponse, StorageRow, StorageRows, StorageRowsQuery, StoredGithubPullRequest, StreamEventsData, StreamEventsError, StreamEventsErrors, StreamEventsResponse, StreamEventsResponses, String, Submission, SubmissionOutcome, SubmitFormResponseData, SubmitFormResponseError, SubmitFormResponseErrors, SubmitFormResponseResponse, SubmitFormResponseResponses, SuccessResponse, SurfaceState, SyncServiceVersionId, SystemSkillSummary, Table, TableChange, TableChanged, TableChanges, TableDetail, TableId, TableResult, TableVersion, TagFilterMode, TakenId, TallyBucket, TallyValue, TaskFilters, TeamCalendarContent, TeamCalendarCoverage, TeamCalendarDetails, TeamCalendarItem, TeamCalendarMember, TeamCalendarPage, TeamCalendarSharing, TeamOutOfOfficeItem, TeamOutOfOfficeResponse, TeamRole, TextOperator, ThreadAnchor, ThreadOrigin, ThreadPatch, ThreadState, TimelineActivity, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TouchedColumn, TouchedRow, TranscribeDictationData, TranscribeDictationError, TranscribeDictationErrors, TranscribeDictationResponse, TranscribeDictationResponses, TranscribeResponse, TranscriptSegmentRequest, TrashCrmPipelineData, TrashCrmPipelineResponse, TrashCrmPipelineResponses, TrashPipeline, TurnEndedMetadata, TurnStartedMetadata, TurnSummary, TypedSuccessResponse, TypedSuccessResponseGetDocumentResponseData, TypingInput, UndoChangeResponse, UndoDatabaseChangeData, UndoDatabaseChangeError, UndoDatabaseChangeErrors, UndoDatabaseChangeResponse, UndoDatabaseChangeResponses, UndoOutcome, UndoRefusal, UnlockedBooking, UpdateAgentData, UpdateAgentError, UpdateAgentErrors, UpdateAgentRequest, UpdateAgentResponse, UpdateAgentResponses, UpdateChannelSharePermission, UpdateCrmPipelinePermissionsData, UpdateCrmPipelinePermissionsResponse, UpdateCrmPipelinePermissionsResponses, UpdateCrmTeamSettingsRequest, UpdateDatabasePermissionsData, UpdateDatabasePermissionsError, UpdateDatabasePermissionsErrors, UpdateDatabasePermissionsResponse, UpdateDatabasePermissionsResponses, UpdateForm, UpdateFormData, UpdateFormError, UpdateFormErrors, UpdateFormPermissionsData, UpdateFormPermissionsError, UpdateFormPermissionsErrors, UpdateFormPermissionsResponse, UpdateFormPermissionsResponses, UpdateFormResponse, UpdateFormResponses, UpdateInitiativeData, UpdateInitiativeError, UpdateInitiativeErrors, UpdateInitiativeRequest, UpdateInitiativeResponse, UpdateInitiativeResponses, UpdateMeetingRequest, UpdateOperation, UpdateSharePermissionRequestV2, UploadDescriptor, UploadDocumentStatus, UploadExtractFolderHandlerData, UploadExtractFolderHandlerError, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponse, UploadExtractFolderHandlerResponses, UploadExtractFolderRequest, UploadFolderHandlerData, UploadFolderHandlerError, UploadFolderHandlerErrors, UploadFolderHandlerResponse, UploadFolderHandlerResponses, UploadFolderRequest, UploadGrant, UploadId, UpsertHistoryHandlerData, UpsertHistoryHandlerError, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponse, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationError, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationRequest, UpsertUserDocumentViewLocationResponse, UpsertUserDocumentViewLocationResponses, UserApiKeyId, UserApiKeyInfo, UserApiKeysList, UserDocumentsResponse, UserDocumentViewLocation, UserDocumentViewLocationResponse, UserPinsResponse, UserViewsResponse, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenError, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponse, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookError, ValidateWebhookErrors, ValidateWebhookResponse, ValidateWebhookResponse2, ValidateWebhookResponses, Vec, VersionedTable, View, ViewChange, ViewColumn, ViewerCapabilities, ViewLayout, ViewPatch, ViewPosition, ViewPositionsResponse, ViewQuery, ViewResult, ViewsResponse, WaitingForInputMetadata, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, WhatsAppCall, WhatsAppCallOutcome, WhatsAppContactCard, WhatsAppContacts, WhatsAppEvent, WhatsappGroupData, WhatsAppGroupDetail, WhatsAppGroupMessage, WhatsappGroupMessageData, WhatsappGroupMessageResponse, WhatsappGroupMessageResponses, WhatsAppGroupMessages, WhatsappGroupMessagesData, WhatsappGroupMessagesResponse, WhatsappGroupMessagesResponses, WhatsappGroupPermissionsData, WhatsappGroupPermissionsResponse, WhatsappGroupPermissionsResponses, WhatsAppGroupReaction, WhatsappGroupReadData, WhatsappGroupReadResponse, WhatsappGroupReadResponses, WhatsappGroupResponse, WhatsappGroupResponses, WhatsappGroupsData, WhatsAppGroupSender, WhatsappGroupSendsData, WhatsappGroupSendsResponse, WhatsappGroupSendsResponses, WhatsappGroupsResponse, WhatsappGroupsResponses, WhatsAppGroupSummary, WhatsappGroupUpdatePermissionsData, WhatsappGroupUpdatePermissionsResponse, WhatsappGroupUpdatePermissionsResponses, WhatsAppLocation, WhatsAppMention, WhatsAppMessageKind, WhatsAppParticipant, WhatsAppPersonRef, WhatsAppPoll, WhatsAppPollOption, WhatsAppRichContent, WhatsAppRoster, WhatsAppSystemAction, WhatsAppSystemLine, Widget, WithCallId, WithChannelId, WithDocumentId, WithProjectId } from './types.gen';
diff --git a/packages/sdk/generated/storage/sdk.gen.ts b/packages/sdk/generated/storage/sdk.gen.ts
index 9c7e0e4976..5ed323540b 100644
--- a/packages/sdk/generated/storage/sdk.gen.ts
+++ b/packages/sdk/generated/storage/sdk.gen.ts
@@ -2,7 +2,7 @@
import { type Client, type ClientMeta, formDataBodySerializer, type Options as Options2, type RequestResult, type ServerSentEventsResult, type TDataShape } from './client';
import { client } from './client.gen';
-import type { AccessRequestsCancelData, AccessRequestsCancelErrors, AccessRequestsCancelResponses, AccessRequestsDirectData, AccessRequestsDirectErrors, AccessRequestsDirectResponses, AccessRequestsRemoveDirectData, AccessRequestsRemoveDirectErrors, AccessRequestsRemoveDirectResponses, AccessRequestsResolveData, AccessRequestsResolveErrors, AccessRequestsResolveResponses, AccessRequestsSetDirectData, AccessRequestsSetDirectErrors, AccessRequestsSetDirectResponses, AccessRequestsStateData, AccessRequestsStateErrors, AccessRequestsStateResponses, AccessRequestsSubmitData, AccessRequestsSubmitErrors, AccessRequestsSubmitResponses, AddFavoriteData, AddFavoriteErrors, AddFavoriteResponses, AddParticipantsData, AddParticipantsErrors, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerErrors, AddPinHandlerResponses, ApplyCrmPipelineOpsData, ApplyCrmPipelineOpsResponses, ApplyDatabaseOpsData, ApplyDatabaseOpsErrors, ApplyDatabaseOpsResponses, ApproveHarnessPairingData, ApproveHarnessPairingErrors, ApproveHarnessPairingResponses, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponses, CallWebhookData, CallWebhookErrors, CallWebhookResponses, CancelSlackImportData, CancelSlackImportErrors, CancelSlackImportResponses, CheckActiveCallData, CheckActiveCallErrors, CheckActiveCallResponses, ClaimHarnessPairingData, ClaimHarnessPairingErrors, ClaimHarnessPairingResponses, CollaborateFormData, CollaborateFormErrors, CollaborateFormResponses, CompleteSlackImportUploadsData, CompleteSlackImportUploadsErrors, CompleteSlackImportUploadsResponses, ConvertDatabaseColumnData, ConvertDatabaseColumnErrors, ConvertDatabaseColumnResponses, CopyDocumentData, CopyDocumentErrors, CopyDocumentResponses, CreateAgentData, CreateAgentErrors, CreateAgentResponses, CreateAnchorData, CreateAnchorErrors, CreateAnchorResponses, CreateCanvasHandlerData, CreateCanvasHandlerErrors, CreateCanvasHandlerResponses, CreateChannelData, CreateChannelErrors, CreateChannelLabelData, CreateChannelLabelErrors, CreateChannelLabelResponses, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotErrors, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponses, CreateCrmCompanyData, CreateCrmCompanyErrors, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactErrors, CreateCrmContactResponses, CreateCrmPipelineData, CreateCrmPipelineResponses, CreateDatabaseData, CreateDatabaseErrors, CreateDatabaseResponses, CreateDatabaseWebhookData, CreateDatabaseWebhookErrors, CreateDatabaseWebhookResponses, CreateDocumentData, CreateDocumentErrors, CreateDocumentResponses, CreateEntityMentionData, CreateEntityMentionErrors, CreateEntityMentionResponses, CreateFormData, CreateFormErrors, CreateFormResponses, CreateHarnessPairingData, CreateHarnessPairingErrors, CreateHarnessPairingResponses, CreateInitiativeData, CreateInitiativeErrors, CreateInitiativeResponses, CreateInstructionsHandlerData, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponses, CreateMarkdownHandlerData, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponses, CreateProjectHandlerData, CreateProjectHandlerErrors, CreateProjectHandlerResponses, CreateSkillHandlerData, CreateSkillHandlerErrors, CreateSkillHandlerResponses, CreateSlackImportData, CreateSlackImportErrors, CreateSlackImportResponses, CreateSnippetHandlerData, CreateSnippetHandlerErrors, CreateSnippetHandlerResponses, CreateTaskHandlerData, CreateTaskHandlerErrors, CreateTaskHandlerResponses, CreateUserApiKeyData, CreateUserApiKeyErrors, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerErrors, CreateViewHandlerResponses, CreateWebhookData, CreateWebhookErrors, CreateWebhookResponses, DeclineCallData, DeclineCallErrors, DeclineCallResponses, DeclineRingData, DeclineRingErrors, DeclineRingResponses, DeleteAnchorData, DeleteAnchorErrors, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordErrors, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelErrors, DeleteChannelLabelData, DeleteChannelLabelErrors, DeleteChannelLabelResponses, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponses, DeleteDatabaseWebhookData, DeleteDatabaseWebhookErrors, DeleteDatabaseWebhookResponses, DeleteDocumentData, DeleteDocumentErrors, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionErrors, DeleteEntityMentionResponses, DeleteHarnessData, DeleteHarnessErrors, DeleteHarnessResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponses, DeleteInitiativeData, DeleteInitiativeErrors, DeleteInitiativeResponses, DeleteProjectHandlerData, DeleteProjectHandlerErrors, DeleteProjectHandlerResponses, DeleteSelfHarnessData, DeleteSelfHarnessErrors, DeleteSelfHarnessResponses, DeleteUserApiKeyData, DeleteUserApiKeyErrors, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookErrors, DeleteWebhookResponses, DeliverDatabaseWebhookData, DeliverDatabaseWebhookErrors, DeliverDatabaseWebhookResponses, EditAnchorData, EditAnchorErrors, EditAnchorResponses, EditCallRecordData, EditCallRecordErrors, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptErrors, EditCallTranscriptResponses, EditDocumentData, EditDocumentErrors, EditDocumentResponses, EditMyFormResponseData, EditMyFormResponseErrors, EditMyFormResponseResponses, EditProjectV2Data, EditProjectV2Errors, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Errors, EditThreadV2Responses, EnsureCollabSurfaceData, EnsureCollabSurfaceErrors, EnsureCollabSurfaceResponses, EnsureStarterHandlerData, EnsureStarterHandlerErrors, EnsureStarterHandlerResponses, EntityMessageCreateData, EntityMessageCreateResponses, EntityMessageDeleteMessageData, EntityMessageDeleteMessageResponses, EntityMessageDeleteThreadData, EntityMessageDeleteThreadResponses, EntityMessageEditData, EntityMessageEditResponses, EntityMessageGetMessageData, EntityMessageGetMessageResponses, EntityMessageGetThreadData, EntityMessageGetThreadResponses, EntityMessageLegacyData, EntityMessageLegacyResponses, EntityMessagePatchThreadData, EntityMessagePatchThreadResponses, EntityMessageReactData, EntityMessageReactResponses, EntityMessageTypingData, EntityMessageTypingResponses, EventIcsData, EventIcsErrors, EventIcsResponses, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExportDocumentData, ExportDocumentErrors, ExportDocumentResponses, FinalizeSlackImportData, FinalizeSlackImportErrors, FinalizeSlackImportResponses, GetActiveCallsData, GetActiveCallsErrors, GetActiveCallsResponses, GetActivityData, GetActivityErrors, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesErrors, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewErrors, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponses, GetBatchProjectPreviewData, GetBatchProjectPreviewErrors, GetBatchProjectPreviewResponses, GetBotOwnerProfilesData, GetBotOwnerProfilesErrors, GetBotOwnerProfilesResponses, GetCallRecordData, GetCallRecordErrors, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsErrors, GetChannelAttachmentsResponses, GetChannelData, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkErrors, GetChannelJoinLinkResponses, GetChannelParticipantsData, GetChannelParticipantsErrors, GetChannelParticipantsResponses, GetChannelResponses, GetChannelsData, GetChannelsErrors, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceErrors, GetCollabSurfaceResponses, GetCompanyData, GetCompanyErrors, GetCompanyResponses, GetContactByEmailData, GetContactByEmailErrors, GetContactByEmailResponses, GetContactData, GetContactErrors, GetContactResponses, GetCrmPipelineData, GetCrmPipelinePermissionsData, GetCrmPipelinePermissionsResponses, GetCrmPipelineResponses, GetCrmPipelineRowsData, GetCrmPipelineRowsResponses, GetCrmPipelineTableData, GetCrmPipelineTableResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponses, GetDatabaseData, GetDatabaseErrors, GetDatabasePermissionsData, GetDatabasePermissionsErrors, GetDatabasePermissionsResponses, GetDatabaseQueryData, GetDatabaseQueryErrors, GetDatabaseQueryResponses, GetDatabaseResponses, GetDatabaseRowHistoryData, GetDatabaseRowHistoryErrors, GetDatabaseRowHistoryResponses, GetDatabaseTableChangesData, GetDatabaseTableChangesErrors, GetDatabaseTableChangesResponses, GetDatabaseViewPositionsData, GetDatabaseViewPositionsErrors, GetDatabaseViewPositionsResponses, GetDocumentAnchorsData, GetDocumentAnchorsErrors, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameErrors, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponses, GetDocumentData, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponses, GetDocumentListHandlerData, GetDocumentListHandlerErrors, GetDocumentListHandlerResponses, GetDocumentLocationV3Data, GetDocumentLocationV3Errors, GetDocumentLocationV3Responses, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Responses, GetDocumentProcessingResultData, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponses, GetDocumentResponses, GetDocumentShortIdData, GetDocumentShortIdErrors, GetDocumentShortIdResponses, GetDocumentTeamShareData, GetDocumentTeamShareErrors, GetDocumentTeamShareResponses, GetDocumentTextContentData, GetDocumentTextContentErrors, GetDocumentTextContentResponses, GetDocumentVersionData, GetDocumentVersionErrors, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponses, GetEmailFollowupData, GetEmailFollowupErrors, GetEmailFollowupResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponses, GetForeignEntityBySourceData, GetForeignEntityBySourceErrors, GetForeignEntityBySourceResponses, GetForeignEntityData, GetForeignEntityErrors, GetForeignEntityResponses, GetFormData, GetFormErrors, GetFormPermissionsData, GetFormPermissionsErrors, GetFormPermissionsResponses, GetFormResponses, GetFormResponseSummaryData, GetFormResponseSummaryErrors, GetFormResponseSummaryResponses, GetFormTallyData, GetFormTallyErrors, GetFormTallyResponses, GetGithubPullRequestChangesData, GetGithubPullRequestChangesErrors, GetGithubPullRequestChangesPatchData, GetGithubPullRequestChangesPatchErrors, GetGithubPullRequestChangesPatchResponses, GetGithubPullRequestChangesResponses, GetGithubPullRequestData, GetGithubPullRequestErrors, GetGithubPullRequestFacetsData, GetGithubPullRequestFacetsErrors, GetGithubPullRequestFacetsResponses, GetGithubPullRequestResponses, GetGithubPullRequestTasksData, GetGithubPullRequestTasksErrors, GetGithubPullRequestTasksResponses, GetHarnessPairingData, GetHarnessPairingErrors, GetHarnessPairingResponses, GetHistoryHandlerData, GetHistoryHandlerErrors, GetHistoryHandlerResponses, GetInitiativeData, GetInitiativeErrors, GetInitiativeResponses, GetInstructionsHandlerData, GetInstructionsHandlerErrors, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupErrors, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerErrors, GetLocationHandlerResponses, GetMyFormResponseData, GetMyFormResponseErrors, GetMyFormResponseResponses, GetOrCreateCallData, GetOrCreateCallErrors, GetOrCreateCallResponses, GetOrCreateDmData, GetOrCreateDmErrors, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateErrors, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerErrors, GetPinsHandlerResponses, GetProjectContentHandlerData, GetProjectContentHandlerErrors, GetProjectContentHandlerResponses, GetProjectHandlerData, GetProjectHandlerErrors, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Responses, GetProjectsHandlerData, GetProjectsHandlerErrors, GetProjectsHandlerResponses, GetProjectUserAccessLevelData, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponses, GetRingStatusData, GetRingStatusErrors, GetRingStatusResponses, GetSelfBotData, GetSelfBotErrors, GetSelfBotResponses, GetSelfHarnessData, GetSelfHarnessErrors, GetSelfHarnessResponses, GetSlackImportData, GetSlackImportErrors, GetSlackImportResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponses, GetViewsHandlerData, GetViewsHandlerErrors, GetViewsHandlerResponses, GetWebhookData, GetWebhookErrors, GetWebhookResponses, GuestCallChatPostData, GuestCallChatPostErrors, GuestCallChatPostResponses, GuestCallChatReadData, GuestCallChatReadErrors, GuestCallChatReadResponses, HandlerData, HandlerErrors, HandlerResponses, HealthHandlerData, HealthHandlerResponses, ImportDatabaseTableData, ImportDatabaseTableErrors, ImportDatabaseTableResponses, InferDatabaseColumnTypeData, InferDatabaseColumnTypeErrors, InferDatabaseColumnTypeResponses, IngestTranscriptData, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsErrors, InitializeUserDocumentsResponses, InstallSyncData, InstallSyncErrors, JobProcessingResultHandlerData, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelErrors, JoinChannelResponses, LeaveChannelData, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallErrors, LeaveOrEndCallResponses, LinkedAccountData, LinkedAccountResponses, LinkedAdoptData, LinkedAdoptResponses, LinkedCancelPairingData, LinkedCancelPairingResponses, LinkedChatsData, LinkedChatsResponses, LinkedConfigurationData, LinkedConfigurationResponses, LinkedConnectData, LinkedConnectResponses, LinkedDeliveryData, LinkedDeliveryResponses, LinkedDetachData, LinkedDetachResponses, LinkedDisconnectData, LinkedDisconnectResponses, LinkedMessageAttachmentsData, LinkedMessageAttachmentsResponses, LinkedPairingData, LinkedPairingResponses, LinkedPasskeyData, LinkedPasskeyResponses, LinkedReplyData, LinkedReplyErrors, LinkedReplyResponses, LinkedUploadData, LinkedUploadResponses, ListAccessibleFormsData, ListAccessibleFormsErrors, ListAccessibleFormsResponses, ListAgentsData, ListAgentsErrors, ListAgentsResponses, ListBotChannelsData, ListBotChannelsErrors, ListBotChannelsResponses, ListChannelLabelsData, ListChannelLabelsErrors, ListChannelLabelsResponses, ListCompanyContactsData, ListCompanyContactsErrors, ListCompanyContactsResponses, ListCrmPipelinesData, ListCrmPipelinesResponses, ListDatabaseColumnCastsData, ListDatabaseColumnCastsErrors, ListDatabaseColumnCastsResponses, ListDatabasesData, ListDatabasesErrors, ListDatabasesResponses, ListDatabaseWebhooksData, ListDatabaseWebhooksErrors, ListDatabaseWebhooksResponses, ListEmailRemindersData, ListEmailRemindersErrors, ListEmailRemindersResponses, ListFavoritesData, ListFavoritesErrors, ListFavoritesResponses, ListFormsData, ListFormsErrors, ListFormsResponses, ListHarnessAgentsData, ListHarnessAgentsErrors, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesErrors, ListHarnessesResponses, ListHarnessSessionsData, ListHarnessSessionsErrors, ListHarnessSessionsResponses, ListInitiativesData, ListInitiativesErrors, ListInitiativesResponses, ListJoinRequestsData, ListJoinRequestsErrors, ListJoinRequestsResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponses, ListSlackImportsData, ListSlackImportsResponses, ListTeamCalendarData, ListTeamCalendarResponses, ListTeamOutOfOfficeData, ListTeamOutOfOfficeErrors, ListTeamOutOfOfficeResponses, ListUserApiKeysData, ListUserApiKeysErrors, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksErrors, ListWebhooksResponses, MeetingCancelData, MeetingCancelErrors, MeetingCancelPreparationData, MeetingCancelPreparationErrors, MeetingCancelPreparationResponses, MeetingCancelResponses, MeetingCreateData, MeetingCreateErrors, MeetingCreateResponses, MeetingGuestJoinData, MeetingGuestJoinErrors, MeetingGuestJoinResponses, MeetingGuestParticipantsData, MeetingGuestParticipantsErrors, MeetingGuestParticipantsResponses, MeetingInviteData, MeetingInviteErrors, MeetingInvitePermissionsData, MeetingInvitePermissionsErrors, MeetingInvitePermissionsResponses, MeetingInviteResponses, MeetingInviteUsersData, MeetingInviteUsersErrors, MeetingInviteUsersResponses, MeetingJoinData, MeetingJoinErrors, MeetingJoinResponses, MeetingLeaveData, MeetingLeaveErrors, MeetingLeaveResponses, MeetingListActiveData, MeetingListActiveErrors, MeetingListActiveResponses, MeetingListData, MeetingListErrors, MeetingListResponses, MeetingLookupData, MeetingLookupErrors, MeetingLookupResponses, MeetingParticipantsData, MeetingParticipantsErrors, MeetingParticipantsResponses, MeetingPrepareData, MeetingPrepareErrors, MeetingPrepareResponses, MeetingShareData, MeetingShareErrors, MeetingShareResponses, MeetingUpdateData, MeetingUpdateErrors, MeetingUpdateResponses, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponses, MessageTimelineData, MessageTimelineEntriesData, MessageTimelineEntriesResponses, MessageTimelineResponses, PatchChannelData, PatchChannelErrors, PatchChannelResponses, PatchViewHandlerData, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookErrors, PatchWebhookResponses, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponses, PostActivityData, PostActivityErrors, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookErrors, PostChannelBotWebhookResponses, PostItemsSoupAstData, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupErrors, PostItemsSoupResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponses, PreviewSmartTagData, PreviewSmartTagErrors, PreviewSmartTagResponses, PutCrmTeamSettingsData, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponses, PutCrmTeamStagesData, PutCrmTeamStagesErrors, PutCrmTeamStagesResponses, PutFormLayoutData, PutFormLayoutErrors, PutFormLayoutResponses, QueryCrmPipelineRowsData, QueryCrmPipelineRowsResponses, QueryDatabasesData, QueryDatabasesErrors, QueryDatabasesResponses, RecentlyDeletedData, RecentlyDeletedErrors, RecentlyDeletedResponses, RegisterSlackImportUploadsData, RegisterSlackImportUploadsErrors, RegisterSlackImportUploadsResponses, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsErrors, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerErrors, RemovePinHandlerResponses, RenameChannelLabelData, RenameChannelLabelErrors, RenameChannelLabelResponses, RenameCrmPipelineData, RenameCrmPipelineResponses, ReorderFavoritesData, ReorderFavoritesErrors, ReorderFavoritesResponses, ReorderPinsHandlerData, ReorderPinsHandlerErrors, ReorderPinsHandlerResponses, RequestToJoinData, RequestToJoinErrors, RequestToJoinResponses, ResetCrmTeamStagesData, ResetCrmTeamStagesErrors, ResetCrmTeamStagesResponses, RevertDeleteDocumentData, RevertDeleteDocumentErrors, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectErrors, RevertDeleteProjectResponses, SaveDatabaseQueryData, SaveDatabaseQueryErrors, SaveDatabaseQueryResponses, SaveDocumentHandlerData, SaveDocumentHandlerErrors, SaveDocumentHandlerResponses, SearchContactsData, SearchContactsErrors, SearchContactsResponses, SetChannelLabelData, SetChannelLabelErrors, SetChannelLabelResponses, SetChannelPictureData, SetChannelPictureErrors, SetChannelPictureResponses, SetCompanyHiddenData, SetCompanyHiddenErrors, SetCompanyHiddenResponses, SetContactHiddenData, SetContactHiddenErrors, SetContactHiddenResponses, SetCrmCompanyNameData, SetCrmCompanyNameErrors, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameErrors, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareErrors, SetDocumentTeamShareResponses, SetEmailFollowupData, SetEmailFollowupErrors, SetEmailFollowupResponses, SetEmailSyncData, SetEmailSyncErrors, SetEmailSyncResponses, ShareCrmPipelineData, ShareCrmPipelineResponses, ShareDatabaseAwarenessData, ShareDatabaseAwarenessErrors, ShareDatabaseAwarenessResponses, SimpleSaveData, SimpleSaveErrors, SimpleSaveResponses, StreamEventsData, StreamEventsErrors, StreamEventsResponse, StreamEventsResponses, SubmitFormResponseData, SubmitFormResponseErrors, SubmitFormResponseResponses, ToggleShareWithTeamData, ToggleShareWithTeamErrors, ToggleShareWithTeamResponses, TranscribeDictationData, TranscribeDictationErrors, TranscribeDictationResponses, TrashCrmPipelineData, TrashCrmPipelineResponses, UndoDatabaseChangeData, UndoDatabaseChangeErrors, UndoDatabaseChangeResponses, UpdateAgentData, UpdateAgentErrors, UpdateAgentResponses, UpdateCrmPipelinePermissionsData, UpdateCrmPipelinePermissionsResponses, UpdateDatabasePermissionsData, UpdateDatabasePermissionsErrors, UpdateDatabasePermissionsResponses, UpdateFormData, UpdateFormErrors, UpdateFormPermissionsData, UpdateFormPermissionsErrors, UpdateFormPermissionsResponses, UpdateFormResponses, UpdateInitiativeData, UpdateInitiativeErrors, UpdateInitiativeResponses, UploadExtractFolderHandlerData, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponses, UploadFolderHandlerData, UploadFolderHandlerErrors, UploadFolderHandlerResponses, UpsertHistoryHandlerData, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationResponses, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookErrors, ValidateWebhookResponses, WhatsappGroupData, WhatsappGroupMessagesData, WhatsappGroupMessagesResponses, WhatsappGroupPermissionsData, WhatsappGroupPermissionsResponses, WhatsappGroupReadData, WhatsappGroupReadResponses, WhatsappGroupResponses, WhatsappGroupsData, WhatsappGroupSendsData, WhatsappGroupSendsResponses, WhatsappGroupsResponses, WhatsappGroupUpdatePermissionsData, WhatsappGroupUpdatePermissionsResponses } from './types.gen';
+import type { AccessRequestsCancelData, AccessRequestsCancelErrors, AccessRequestsCancelResponses, AccessRequestsDirectData, AccessRequestsDirectErrors, AccessRequestsDirectResponses, AccessRequestsRemoveDirectData, AccessRequestsRemoveDirectErrors, AccessRequestsRemoveDirectResponses, AccessRequestsResolveData, AccessRequestsResolveErrors, AccessRequestsResolveResponses, AccessRequestsSetDirectData, AccessRequestsSetDirectErrors, AccessRequestsSetDirectResponses, AccessRequestsStateData, AccessRequestsStateErrors, AccessRequestsStateResponses, AccessRequestsSubmitData, AccessRequestsSubmitErrors, AccessRequestsSubmitResponses, AddFavoriteData, AddFavoriteErrors, AddFavoriteResponses, AddParticipantsData, AddParticipantsErrors, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerErrors, AddPinHandlerResponses, ApplyCrmPipelineOpsData, ApplyCrmPipelineOpsResponses, ApplyDatabaseOpsData, ApplyDatabaseOpsErrors, ApplyDatabaseOpsResponses, ApproveHarnessPairingData, ApproveHarnessPairingErrors, ApproveHarnessPairingResponses, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponses, CallWebhookData, CallWebhookErrors, CallWebhookResponses, CancelSlackImportData, CancelSlackImportErrors, CancelSlackImportResponses, CheckActiveCallData, CheckActiveCallErrors, CheckActiveCallResponses, ClaimHarnessPairingData, ClaimHarnessPairingErrors, ClaimHarnessPairingResponses, CollaborateFormData, CollaborateFormErrors, CollaborateFormResponses, CompleteSlackImportUploadsData, CompleteSlackImportUploadsErrors, CompleteSlackImportUploadsResponses, ConvertDatabaseColumnData, ConvertDatabaseColumnErrors, ConvertDatabaseColumnResponses, CopyDocumentData, CopyDocumentErrors, CopyDocumentResponses, CreateAgentData, CreateAgentErrors, CreateAgentResponses, CreateAnchorData, CreateAnchorErrors, CreateAnchorResponses, CreateCanvasHandlerData, CreateCanvasHandlerErrors, CreateCanvasHandlerResponses, CreateChannelData, CreateChannelErrors, CreateChannelLabelData, CreateChannelLabelErrors, CreateChannelLabelResponses, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotErrors, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponses, CreateCrmCompanyData, CreateCrmCompanyErrors, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactErrors, CreateCrmContactResponses, CreateCrmPipelineData, CreateCrmPipelineResponses, CreateDatabaseData, CreateDatabaseErrors, CreateDatabaseResponses, CreateDatabaseWebhookData, CreateDatabaseWebhookErrors, CreateDatabaseWebhookResponses, CreateDocumentData, CreateDocumentErrors, CreateDocumentResponses, CreateEntityMentionData, CreateEntityMentionErrors, CreateEntityMentionResponses, CreateFormData, CreateFormErrors, CreateFormResponses, CreateHarnessPairingData, CreateHarnessPairingErrors, CreateHarnessPairingResponses, CreateInitiativeData, CreateInitiativeErrors, CreateInitiativeResponses, CreateInstructionsHandlerData, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponses, CreateMarkdownHandlerData, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponses, CreateProjectHandlerData, CreateProjectHandlerErrors, CreateProjectHandlerResponses, CreateSkillHandlerData, CreateSkillHandlerErrors, CreateSkillHandlerResponses, CreateSlackImportData, CreateSlackImportErrors, CreateSlackImportResponses, CreateSnippetHandlerData, CreateSnippetHandlerErrors, CreateSnippetHandlerResponses, CreateTaskHandlerData, CreateTaskHandlerErrors, CreateTaskHandlerResponses, CreateUserApiKeyData, CreateUserApiKeyErrors, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerErrors, CreateViewHandlerResponses, CreateWebhookData, CreateWebhookErrors, CreateWebhookResponses, DeclineCallData, DeclineCallErrors, DeclineCallResponses, DeclineRingData, DeclineRingErrors, DeclineRingResponses, DeleteAnchorData, DeleteAnchorErrors, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordErrors, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelErrors, DeleteChannelLabelData, DeleteChannelLabelErrors, DeleteChannelLabelResponses, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponses, DeleteDatabaseWebhookData, DeleteDatabaseWebhookErrors, DeleteDatabaseWebhookResponses, DeleteDocumentData, DeleteDocumentErrors, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionErrors, DeleteEntityMentionResponses, DeleteHarnessData, DeleteHarnessErrors, DeleteHarnessResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponses, DeleteInitiativeData, DeleteInitiativeErrors, DeleteInitiativeResponses, DeleteProjectHandlerData, DeleteProjectHandlerErrors, DeleteProjectHandlerResponses, DeleteSelfHarnessData, DeleteSelfHarnessErrors, DeleteSelfHarnessResponses, DeleteUserApiKeyData, DeleteUserApiKeyErrors, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookErrors, DeleteWebhookResponses, DeliverDatabaseWebhookData, DeliverDatabaseWebhookErrors, DeliverDatabaseWebhookResponses, EditAnchorData, EditAnchorErrors, EditAnchorResponses, EditCallRecordData, EditCallRecordErrors, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptErrors, EditCallTranscriptResponses, EditDocumentData, EditDocumentErrors, EditDocumentResponses, EditMyFormResponseData, EditMyFormResponseErrors, EditMyFormResponseResponses, EditProjectV2Data, EditProjectV2Errors, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Errors, EditThreadV2Responses, EnsureCollabSurfaceData, EnsureCollabSurfaceErrors, EnsureCollabSurfaceResponses, EnsureStarterHandlerData, EnsureStarterHandlerErrors, EnsureStarterHandlerResponses, EntityMessageCreateData, EntityMessageCreateResponses, EntityMessageDeleteMessageData, EntityMessageDeleteMessageResponses, EntityMessageDeleteThreadData, EntityMessageDeleteThreadResponses, EntityMessageEditData, EntityMessageEditResponses, EntityMessageGetMessageData, EntityMessageGetMessageResponses, EntityMessageGetThreadData, EntityMessageGetThreadResponses, EntityMessageLegacyData, EntityMessageLegacyResponses, EntityMessagePatchThreadData, EntityMessagePatchThreadResponses, EntityMessageReactData, EntityMessageReactResponses, EntityMessageTypingData, EntityMessageTypingResponses, EventIcsData, EventIcsErrors, EventIcsResponses, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExportDocumentData, ExportDocumentErrors, ExportDocumentResponses, FinalizeSlackImportData, FinalizeSlackImportErrors, FinalizeSlackImportResponses, GetActiveCallsData, GetActiveCallsErrors, GetActiveCallsResponses, GetActivityData, GetActivityErrors, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesErrors, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewErrors, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponses, GetBatchProjectPreviewData, GetBatchProjectPreviewErrors, GetBatchProjectPreviewResponses, GetBotOwnerProfilesData, GetBotOwnerProfilesErrors, GetBotOwnerProfilesResponses, GetCallRecordData, GetCallRecordErrors, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsErrors, GetChannelAttachmentsResponses, GetChannelData, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkErrors, GetChannelJoinLinkResponses, GetChannelParticipantsData, GetChannelParticipantsErrors, GetChannelParticipantsResponses, GetChannelResponses, GetChannelsData, GetChannelsErrors, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceErrors, GetCollabSurfaceResponses, GetCompanyData, GetCompanyErrors, GetCompanyResponses, GetContactByEmailData, GetContactByEmailErrors, GetContactByEmailResponses, GetContactData, GetContactErrors, GetContactResponses, GetCrmPipelineData, GetCrmPipelinePermissionsData, GetCrmPipelinePermissionsResponses, GetCrmPipelineResponses, GetCrmPipelineRowsData, GetCrmPipelineRowsResponses, GetCrmPipelineTableData, GetCrmPipelineTableResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponses, GetDatabaseData, GetDatabaseErrors, GetDatabasePermissionsData, GetDatabasePermissionsErrors, GetDatabasePermissionsResponses, GetDatabaseQueryData, GetDatabaseQueryErrors, GetDatabaseQueryResponses, GetDatabaseResponses, GetDatabaseRowHistoryData, GetDatabaseRowHistoryErrors, GetDatabaseRowHistoryResponses, GetDatabaseTableChangesData, GetDatabaseTableChangesErrors, GetDatabaseTableChangesResponses, GetDatabaseViewPositionsData, GetDatabaseViewPositionsErrors, GetDatabaseViewPositionsResponses, GetDocumentAnchorsData, GetDocumentAnchorsErrors, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameErrors, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponses, GetDocumentData, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponses, GetDocumentListHandlerData, GetDocumentListHandlerErrors, GetDocumentListHandlerResponses, GetDocumentLocationV3Data, GetDocumentLocationV3Errors, GetDocumentLocationV3Responses, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Responses, GetDocumentProcessingResultData, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponses, GetDocumentResponses, GetDocumentShortIdData, GetDocumentShortIdErrors, GetDocumentShortIdResponses, GetDocumentTeamShareData, GetDocumentTeamShareErrors, GetDocumentTeamShareResponses, GetDocumentTextContentData, GetDocumentTextContentErrors, GetDocumentTextContentResponses, GetDocumentVersionData, GetDocumentVersionErrors, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponses, GetEmailFollowupData, GetEmailFollowupErrors, GetEmailFollowupResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponses, GetForeignEntityBySourceData, GetForeignEntityBySourceErrors, GetForeignEntityBySourceResponses, GetForeignEntityData, GetForeignEntityErrors, GetForeignEntityResponses, GetFormData, GetFormErrors, GetFormPermissionsData, GetFormPermissionsErrors, GetFormPermissionsResponses, GetFormResponses, GetFormResponseSummaryData, GetFormResponseSummaryErrors, GetFormResponseSummaryResponses, GetFormTallyData, GetFormTallyErrors, GetFormTallyResponses, GetGithubPullRequestChangesData, GetGithubPullRequestChangesErrors, GetGithubPullRequestChangesPatchData, GetGithubPullRequestChangesPatchErrors, GetGithubPullRequestChangesPatchResponses, GetGithubPullRequestChangesResponses, GetGithubPullRequestData, GetGithubPullRequestErrors, GetGithubPullRequestFacetsData, GetGithubPullRequestFacetsErrors, GetGithubPullRequestFacetsResponses, GetGithubPullRequestResponses, GetGithubPullRequestTasksData, GetGithubPullRequestTasksErrors, GetGithubPullRequestTasksResponses, GetHarnessPairingData, GetHarnessPairingErrors, GetHarnessPairingResponses, GetHistoryHandlerData, GetHistoryHandlerErrors, GetHistoryHandlerResponses, GetInitiativeData, GetInitiativeErrors, GetInitiativeResponses, GetInstructionsHandlerData, GetInstructionsHandlerErrors, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupErrors, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerErrors, GetLocationHandlerResponses, GetMyFormResponseData, GetMyFormResponseErrors, GetMyFormResponseResponses, GetOrCreateCallData, GetOrCreateCallErrors, GetOrCreateCallResponses, GetOrCreateDmData, GetOrCreateDmErrors, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateErrors, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerErrors, GetPinsHandlerResponses, GetProjectContentHandlerData, GetProjectContentHandlerErrors, GetProjectContentHandlerResponses, GetProjectHandlerData, GetProjectHandlerErrors, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Responses, GetProjectsHandlerData, GetProjectsHandlerErrors, GetProjectsHandlerResponses, GetProjectUserAccessLevelData, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponses, GetRingStatusData, GetRingStatusErrors, GetRingStatusResponses, GetSelfBotData, GetSelfBotErrors, GetSelfBotResponses, GetSelfHarnessData, GetSelfHarnessErrors, GetSelfHarnessResponses, GetSlackImportData, GetSlackImportErrors, GetSlackImportResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponses, GetViewsHandlerData, GetViewsHandlerErrors, GetViewsHandlerResponses, GetWebhookData, GetWebhookErrors, GetWebhookResponses, GuestCallChatPostData, GuestCallChatPostErrors, GuestCallChatPostResponses, GuestCallChatReadData, GuestCallChatReadErrors, GuestCallChatReadResponses, HandlerData, HandlerErrors, HandlerResponses, HealthHandlerData, HealthHandlerResponses, ImportDatabaseTableData, ImportDatabaseTableErrors, ImportDatabaseTableResponses, InferDatabaseColumnTypeData, InferDatabaseColumnTypeErrors, InferDatabaseColumnTypeResponses, IngestTranscriptData, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsErrors, InitializeUserDocumentsResponses, InstallSyncData, InstallSyncErrors, JobProcessingResultHandlerData, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelErrors, JoinChannelResponses, LeaveChannelData, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallErrors, LeaveOrEndCallResponses, LinkedAccountData, LinkedAccountResponses, LinkedAdoptData, LinkedAdoptResponses, LinkedCancelPairingData, LinkedCancelPairingResponses, LinkedChatsData, LinkedChatsResponses, LinkedConfigurationData, LinkedConfigurationResponses, LinkedConnectData, LinkedConnectResponses, LinkedDeliveryData, LinkedDeliveryResponses, LinkedDetachData, LinkedDetachResponses, LinkedDisconnectData, LinkedDisconnectResponses, LinkedMessageAttachmentsData, LinkedMessageAttachmentsResponses, LinkedPairingData, LinkedPairingResponses, LinkedPasskeyData, LinkedPasskeyResponses, LinkedReplyData, LinkedReplyErrors, LinkedReplyResponses, LinkedUploadData, LinkedUploadResponses, ListAccessibleFormsData, ListAccessibleFormsErrors, ListAccessibleFormsResponses, ListAgentsData, ListAgentsErrors, ListAgentsResponses, ListBotChannelsData, ListBotChannelsErrors, ListBotChannelsResponses, ListChannelLabelsData, ListChannelLabelsErrors, ListChannelLabelsResponses, ListCompanyContactsData, ListCompanyContactsErrors, ListCompanyContactsResponses, ListCrmPipelinesData, ListCrmPipelinesResponses, ListDatabaseColumnCastsData, ListDatabaseColumnCastsErrors, ListDatabaseColumnCastsResponses, ListDatabasesData, ListDatabasesErrors, ListDatabasesResponses, ListDatabaseWebhooksData, ListDatabaseWebhooksErrors, ListDatabaseWebhooksResponses, ListEmailRemindersData, ListEmailRemindersErrors, ListEmailRemindersResponses, ListFavoritesData, ListFavoritesErrors, ListFavoritesResponses, ListFormsData, ListFormsErrors, ListFormsResponses, ListHarnessAgentsData, ListHarnessAgentsErrors, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesErrors, ListHarnessesResponses, ListHarnessSessionsData, ListHarnessSessionsErrors, ListHarnessSessionsResponses, ListInitiativesData, ListInitiativesErrors, ListInitiativesResponses, ListJoinRequestsData, ListJoinRequestsErrors, ListJoinRequestsResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponses, ListSlackImportsData, ListSlackImportsResponses, ListTeamCalendarData, ListTeamCalendarResponses, ListTeamOutOfOfficeData, ListTeamOutOfOfficeErrors, ListTeamOutOfOfficeResponses, ListUserApiKeysData, ListUserApiKeysErrors, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksErrors, ListWebhooksResponses, MeetingCancelData, MeetingCancelErrors, MeetingCancelPreparationData, MeetingCancelPreparationErrors, MeetingCancelPreparationResponses, MeetingCancelResponses, MeetingCreateData, MeetingCreateErrors, MeetingCreateResponses, MeetingGuestJoinData, MeetingGuestJoinErrors, MeetingGuestJoinResponses, MeetingGuestParticipantsData, MeetingGuestParticipantsErrors, MeetingGuestParticipantsResponses, MeetingInviteData, MeetingInviteErrors, MeetingInvitePermissionsData, MeetingInvitePermissionsErrors, MeetingInvitePermissionsResponses, MeetingInviteResponses, MeetingInviteUsersData, MeetingInviteUsersErrors, MeetingInviteUsersResponses, MeetingJoinData, MeetingJoinErrors, MeetingJoinResponses, MeetingLeaveData, MeetingLeaveErrors, MeetingLeaveResponses, MeetingListActiveData, MeetingListActiveErrors, MeetingListActiveResponses, MeetingListData, MeetingListErrors, MeetingListResponses, MeetingLookupData, MeetingLookupErrors, MeetingLookupResponses, MeetingParticipantsData, MeetingParticipantsErrors, MeetingParticipantsResponses, MeetingPrepareData, MeetingPrepareErrors, MeetingPrepareResponses, MeetingShareData, MeetingShareErrors, MeetingShareResponses, MeetingUpdateData, MeetingUpdateErrors, MeetingUpdateResponses, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponses, MessageTimelineData, MessageTimelineEntriesData, MessageTimelineEntriesResponses, MessageTimelineResponses, PatchChannelData, PatchChannelErrors, PatchChannelResponses, PatchViewHandlerData, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookErrors, PatchWebhookResponses, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponses, PostActivityData, PostActivityErrors, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookErrors, PostChannelBotWebhookResponses, PostItemsSoupAstData, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupErrors, PostItemsSoupResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponses, PreviewSmartTagData, PreviewSmartTagErrors, PreviewSmartTagResponses, PutCrmTeamSettingsData, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponses, PutCrmTeamStagesData, PutCrmTeamStagesErrors, PutCrmTeamStagesResponses, PutFormLayoutData, PutFormLayoutErrors, PutFormLayoutResponses, QueryCrmPipelineRowsData, QueryCrmPipelineRowsResponses, QueryDatabasesData, QueryDatabasesErrors, QueryDatabasesResponses, RecentlyDeletedData, RecentlyDeletedErrors, RecentlyDeletedResponses, RegisterSlackImportUploadsData, RegisterSlackImportUploadsErrors, RegisterSlackImportUploadsResponses, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsErrors, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerErrors, RemovePinHandlerResponses, RenameChannelLabelData, RenameChannelLabelErrors, RenameChannelLabelResponses, RenameCrmPipelineData, RenameCrmPipelineResponses, ReorderFavoritesData, ReorderFavoritesErrors, ReorderFavoritesResponses, ReorderPinsHandlerData, ReorderPinsHandlerErrors, ReorderPinsHandlerResponses, RequestToJoinData, RequestToJoinErrors, RequestToJoinResponses, ResetCrmTeamStagesData, ResetCrmTeamStagesErrors, ResetCrmTeamStagesResponses, RevertDeleteDocumentData, RevertDeleteDocumentErrors, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectErrors, RevertDeleteProjectResponses, SaveDatabaseQueryData, SaveDatabaseQueryErrors, SaveDatabaseQueryResponses, SaveDocumentHandlerData, SaveDocumentHandlerErrors, SaveDocumentHandlerResponses, SearchContactsData, SearchContactsErrors, SearchContactsResponses, SetChannelLabelData, SetChannelLabelErrors, SetChannelLabelResponses, SetChannelPictureData, SetChannelPictureErrors, SetChannelPictureResponses, SetCompanyHiddenData, SetCompanyHiddenErrors, SetCompanyHiddenResponses, SetContactHiddenData, SetContactHiddenErrors, SetContactHiddenResponses, SetCrmCompanyNameData, SetCrmCompanyNameErrors, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameErrors, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareErrors, SetDocumentTeamShareResponses, SetEmailFollowupData, SetEmailFollowupErrors, SetEmailFollowupResponses, SetEmailSyncData, SetEmailSyncErrors, SetEmailSyncResponses, ShareCrmPipelineData, ShareCrmPipelineResponses, ShareDatabaseAwarenessData, ShareDatabaseAwarenessErrors, ShareDatabaseAwarenessResponses, SimpleSaveData, SimpleSaveErrors, SimpleSaveResponses, StreamEventsData, StreamEventsErrors, StreamEventsResponse, StreamEventsResponses, SubmitFormResponseData, SubmitFormResponseErrors, SubmitFormResponseResponses, ToggleShareWithTeamData, ToggleShareWithTeamErrors, ToggleShareWithTeamResponses, TranscribeDictationData, TranscribeDictationErrors, TranscribeDictationResponses, TrashCrmPipelineData, TrashCrmPipelineResponses, UndoDatabaseChangeData, UndoDatabaseChangeErrors, UndoDatabaseChangeResponses, UpdateAgentData, UpdateAgentErrors, UpdateAgentResponses, UpdateCrmPipelinePermissionsData, UpdateCrmPipelinePermissionsResponses, UpdateDatabasePermissionsData, UpdateDatabasePermissionsErrors, UpdateDatabasePermissionsResponses, UpdateFormData, UpdateFormErrors, UpdateFormPermissionsData, UpdateFormPermissionsErrors, UpdateFormPermissionsResponses, UpdateFormResponses, UpdateInitiativeData, UpdateInitiativeErrors, UpdateInitiativeResponses, UploadExtractFolderHandlerData, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponses, UploadFolderHandlerData, UploadFolderHandlerErrors, UploadFolderHandlerResponses, UpsertHistoryHandlerData, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationResponses, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookErrors, ValidateWebhookResponses, WhatsappGroupData, WhatsappGroupMessageData, WhatsappGroupMessageResponses, WhatsappGroupMessagesData, WhatsappGroupMessagesResponses, WhatsappGroupPermissionsData, WhatsappGroupPermissionsResponses, WhatsappGroupReadData, WhatsappGroupReadResponses, WhatsappGroupResponses, WhatsappGroupsData, WhatsappGroupSendsData, WhatsappGroupSendsResponses, WhatsappGroupsResponses, WhatsappGroupUpdatePermissionsData, WhatsappGroupUpdatePermissionsResponses } from './types.gen';
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {
/**
@@ -2821,7 +2821,7 @@ export class Sdk extends HeyApiClient {
}
/**
- * Stop syncing the group, locally.
+ * Stop syncing the group, locally. Owner only, in their own session.
*/
public linkedDetach<ThrowOnError extends boolean = false>(options: Options<LinkedDetachData, ThrowOnError>): RequestResult<LinkedDetachResponses, unknown, ThrowOnError> {
return (options.client ?? this.client).delete<LinkedDetachResponses, unknown, ThrowOnError>({ url: '/meta/linked/whatsapp-groups/{group_id}', ...options });
@@ -2884,6 +2884,13 @@ export class Sdk extends HeyApiClient {
});
}
+ /**
+ * One message of the timeline, as the timeline shows it.
+ */
+ public whatsappGroupMessage<ThrowOnError extends boolean = false>(options: Options<WhatsappGroupMessageData, ThrowOnError>): RequestResult<WhatsappGroupMessageResponses, unknown, ThrowOnError> {
+ return (options.client ?? this.client).get<WhatsappGroupMessageResponses, unknown, ThrowOnError>({ url: '/meta/linked/whatsapp-groups/{group_id}/messages/{message_id}', ...options });
+ }
+
/**
* Generic Share dialog policy.
*/
diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.ts
index 52443bdb34..d3ccaf6b60 100644
--- a/packages/sdk/generated/storage/types.gen.ts
+++ b/packages/sdk/generated/storage/types.gen.ts
@@ -199,7 +199,7 @@ export type AdoptedGroup = {
/**
* Shareable entity identifier.
*/
- group_id: string;
+ groupId: string;
};
/**
@@ -8949,7 +8949,7 @@ export type LinkedAccount = {
/**
* Explicit consent generation; reconnecting a socket never changes it.
*/
- authorization_generation: number;
+ authorizationGeneration: number;
/**
* Stable account identity.
*/
@@ -8957,7 +8957,7 @@ export type LinkedAccount = {
/**
* WhatsApp-verified identity, absent until the first pairing succeeds.
*/
- identity_jid?: string | null;
+ identityJid?: string | null;
/**
* Lifecycle.
*/
@@ -8965,7 +8965,7 @@ export type LinkedAccount = {
/**
* Authenticated owner.
*/
- user_id: string;
+ userId: string;
};
/**
@@ -8990,7 +8990,7 @@ export type LinkedAdoptGroup = {
* A group the requester's account has joined, or a direct chat from
* their chat list (the other person's JID, as the list names it).
*/
- group_jid: string;
+ groupJid: string;
};
/**
@@ -9000,15 +9000,15 @@ export type LinkedAttachment = {
/**
* The private document, once ready.
*/
- document_id?: string | null;
+ documentId?: string | null;
/**
* Length of audio or video in whole seconds, when declared.
*/
- duration_seconds?: number | null;
+ durationSeconds?: number | null;
/**
* Display filename.
*/
- file_name: string;
+ fileName: string;
/**
* Pixel height, when declared.
*/
@@ -9058,7 +9058,7 @@ export type LinkedBackfill = {
/**
* Where importing a group's earlier messages stands.
*/
-export type LinkedBackfillState = 'pending' | 'running' | 'waiting_for_phone' | 'done' | 'partial';
+export type LinkedBackfillState = 'waiting_for_message' | 'pending' | 'running' | 'waiting_for_phone' | 'done' | 'partial';
/**
* Why a chat can't be added to Macro; the app words it from the code.
@@ -9072,19 +9072,19 @@ export type LinkedCapabilities = {
/**
* Largest attachment in bytes.
*/
- attachment_limit_bytes: number;
+ attachmentLimitBytes: number;
/**
* Supported attachment MIME types.
*/
- attachment_types: Array<string>;
+ attachmentTypes: Array<string>;
/**
* Attachments per send.
*/
- max_attachments: number;
+ maxAttachments: number;
/**
* Edits and deletes are offered this long after sending.
*/
- mutation_window_seconds: number;
+ mutationWindowSeconds: number;
/**
* Supported message operations.
*/
@@ -9092,7 +9092,7 @@ export type LinkedCapabilities = {
/**
* Maximum UTF-8 bytes per text send.
*/
- text_limit_bytes: number;
+ textLimitBytes: number;
};
/**
@@ -9183,7 +9183,7 @@ export type LinkedConnect = {
* Observed send state. `unknown` means the request may have reached WhatsApp;
* it is never sent again automatically.
*/
-export type LinkedDeliveryState = 'pending' | 'sending' | 'unknown' | 'accepted' | 'sent' | 'delivered' | 'read' | 'failed';
+export type LinkedDeliveryState = 'pending' | 'sending' | 'unknown' | 'accepted' | 'failed';
/**
* Result of disconnecting an account.
@@ -9193,7 +9193,7 @@ export type LinkedDisconnect = {
* The session service was asked to log the device out of WhatsApp. It
* unlinks asynchronously; WhatsApp's Linked devices list is authoritative.
*/
- remote_unlink_requested: boolean;
+ remoteUnlinkRequested: boolean;
};
/**
@@ -9203,7 +9203,7 @@ export type LinkedDisconnectRequest = {
/**
* Fences retries against a later reconnect or replacement.
*/
- authorization_generation: number;
+ authorizationGeneration: number;
};
/**
@@ -9224,49 +9224,6 @@ export type LinkedFeatures = {
sending: boolean;
};
-/**
- * One full metadata read of a group, never an incomplete membership delta.
- */
-export type LinkedGroupInfo = {
- /**
- * Only admins may post.
- */
- announce: boolean;
- /**
- * The community's announcement group (everyone reads, admins post).
- */
- communityAnnouncements?: boolean;
- /**
- * The community a linked subgroup or announcement group belongs to.
- */
- communityJid?: string | null;
- /**
- * The community itself: it has no messages of its own and can't be added.
- */
- communityParent?: boolean;
- /**
- * Disappearing-messages timer in seconds while it is on. Macro keeps the
- * messages; its sends carry the timer so phones treat them like their own.
- */
- disappearingSeconds?: number | null;
- /**
- * Remote group JID.
- */
- jid: string;
- /**
- * Current subject.
- */
- name: string;
- /**
- * When the session service read this metadata.
- */
- observedAt: string;
- /**
- * Full roster.
- */
- participants: Array<LinkedParticipant>;
-};
-
/**
* A group entity bound to a remote group.
*/
@@ -9281,24 +9238,6 @@ export type LinkedGroupReference = {
name: string;
};
-/**
- * Verified sender aliases, supplied only by protocol metadata.
- */
-export type LinkedIdentity = {
- /**
- * Verified alternate identity, never inferred from a name or phone typed by a user.
- */
- alternateJid?: string | null;
- /**
- * Untrusted display name.
- */
- displayName?: string | null;
- /**
- * Phone-number or LID account JID.
- */
- jid: string;
-};
-
/**
* Attachment categories WhatsApp distinguishes.
*/
@@ -9316,11 +9255,11 @@ export type LinkedMessageAttachments = {
/**
* Its attachments in order; deleted ones are omitted.
*/
- linked_attachments: Array<LinkedAttachment>;
+ linkedAttachments: Array<LinkedAttachment>;
/**
* Group message.
*/
- message_id: string;
+ messageId: string;
};
/**
@@ -9369,11 +9308,11 @@ export type LinkedPairing = {
/**
* Account being connected.
*/
- account_id: string;
+ accountId: string;
/**
* Database-assigned deadline.
*/
- expires_at: string;
+ expiresAt: string;
/**
* One-use transaction id.
*/
@@ -9389,16 +9328,6 @@ export type LinkedPairing = {
*/
export type LinkedPairingState = 'waiting' | 'qr' | 'passkey' | 'success' | 'expired' | 'cancelled' | 'failed';
-/**
- * Current remote participant; Macro access is a separate grant.
- */
-export type LinkedParticipant = LinkedIdentity & {
- /**
- * Group admin; only admins post in announcement groups.
- */
- admin: boolean;
-};
-
/**
* Why the viewer cannot send now.
*/
@@ -9428,12 +9357,12 @@ export type LinkedReplyContent = {
/**
* The staged upload, which becomes the message's private document.
*/
- upload_id: string;
+ uploadId: string;
} | {
/**
* Existing group message, resolved to its WhatsApp source by the server.
*/
- message_id: string;
+ messageId: string;
/**
* Explicit operation.
*/
@@ -9452,15 +9381,15 @@ export type LinkedSendProgress = {
/**
* Intent creation time.
*/
- created_at: string;
+ createdAt: string;
/**
* Sanitized failure code.
*/
- error_code?: string | null;
+ errorCode?: string | null;
/**
* Group entity.
*/
- group_id: string;
+ groupId: string;
/**
* Stable intent id.
*/
@@ -9468,7 +9397,7 @@ export type LinkedSendProgress = {
/**
* Group message, once WhatsApp accepted it.
*/
- message_id?: string | null;
+ messageId?: string | null;
/**
* The original request, so a failed draft can be recovered.
*/
@@ -9480,7 +9409,7 @@ export type LinkedSendProgress = {
/**
* Person who submitted it.
*/
- user_id: string;
+ userId: string;
};
/**
@@ -9490,7 +9419,7 @@ export type LinkedSendReply = {
/**
* Stable client intent key. A changed payload with this key is a conflict.
*/
- idempotency_key: string;
+ idempotencyKey: string;
/**
* Content.
*/
@@ -9498,7 +9427,7 @@ export type LinkedSendReply = {
/**
* Group message being quoted, within this group.
*/
- reply_to?: string | null;
+ replyTo?: string | null;
};
/**
@@ -9544,7 +9473,7 @@ export type LinkedUploadedAttachment = {
/**
* Use as `upload_id` in a media send; also the future document id.
*/
- upload_id: string;
+ uploadId: string;
};
/**
@@ -9667,7 +9596,7 @@ export type MarkRead = {
/**
* Message in the addressed group.
*/
- message_id: string;
+ messageId: string;
};
/**
@@ -16202,26 +16131,25 @@ export type WhatsAppGroupDetail = WhatsAppGroupSummary & {
/**
* Caller's effective permission.
*/
- access_level: AccessLevel;
- community?: null | LinkedCommunityReference;
+ accessLevel: AccessLevel;
/**
* WhatsApp's disappearing-messages timer in seconds while it is on;
* Macro keeps the messages anyway. `null` when off or unknown.
*/
- disappearing_seconds?: number | null;
+ disappearingSeconds?: number | null;
/**
* Size and mutation limits.
*/
limits: LinkedCapabilities;
- roster?: null | LinkedGroupInfo;
+ roster?: null | WhatsAppRoster;
/**
* Caller's own phone identity, never another account's identity.
*/
- sending_identity?: string | null;
+ sendingIdentity?: string | null;
/**
* Owner-controlled standard sharing configuration.
*/
- share_permission: SharePermissionV2;
+ sharePermission: SharePermissionV2;
};
/**
@@ -16240,11 +16168,11 @@ export type WhatsAppGroupMessage = {
* Deleted for everyone.
*/
deleted: boolean;
- delivery_state?: null | LinkedDeliveryState;
+ deliveryState?: null | LinkedDeliveryState;
/**
* Last edit timestamp.
*/
- edited_at?: string | null;
+ editedAt?: string | null;
/**
* Forwarded from another chat.
*/
@@ -16268,11 +16196,11 @@ export type WhatsAppGroupMessage = {
/**
* Timestamp first received by Macro.
*/
- received_at: string;
+ receivedAt: string;
/**
* Message quoted by this one.
*/
- reply_to?: string | null;
+ replyTo?: string | null;
rich?: null | WhatsAppRichContent;
/**
* Sender.
@@ -16281,11 +16209,11 @@ export type WhatsAppGroupMessage = {
/**
* Timestamp assigned by WhatsApp.
*/
- sent_at: string;
+ sentAt: string;
/**
* Sent as view-once in WhatsApp; Macro shows it like any media.
*/
- view_once: boolean;
+ viewOnce: boolean;
};
/**
@@ -16299,7 +16227,7 @@ export type WhatsAppGroupMessages = {
/**
* Cursor for older messages.
*/
- next_cursor?: string | null;
+ nextCursor?: string | null;
};
/**
@@ -16331,11 +16259,11 @@ export type WhatsAppGroupSender = {
/**
* External person identity.
*/
- person_id: string;
+ personId: string;
/**
* Verified Macro user association, if present.
*/
- user_id?: string | null;
+ userId?: string | null;
};
/**
@@ -16346,7 +16274,8 @@ export type WhatsAppGroupSummary = {
/**
* Caller may currently send from their own account.
*/
- can_send: boolean;
+ canSend: boolean;
+ community?: null | LinkedCommunityReference;
/**
* Entity identifier.
*/
@@ -16358,20 +16287,21 @@ export type WhatsAppGroupSummary = {
/**
* Latest message timestamp.
*/
- last_message_at?: string | null;
+ lastMessageAt?: string | null;
/**
* Display name: the group's, or a direct chat's other person.
*/
name: string;
- send_reason?: null | LinkedReplyBlock;
+ sendReason?: null | LinkedReplyBlock;
/**
- * Unread live messages for this viewer.
+ * Unread live messages for this viewer, counted up to
+ * [`UNREAD_COUNT_CAP`].
*/
- unread_count: number;
+ unreadCount: number;
/**
* Actual entity owner.
*/
- user_id: string;
+ userId: string;
};
/**
@@ -16424,6 +16354,28 @@ export type WhatsAppMention = WhatsAppPersonRef & {
*/
export type WhatsAppMessageKind = 'message' | 'system';
+/**
+ * Someone in a WhatsApp chat; Macro access is a separate grant.
+ */
+export type WhatsAppParticipant = {
+ /**
+ * Group admin.
+ */
+ admin: boolean;
+ /**
+ * The other address WhatsApp verified for them.
+ */
+ alternateJid?: string | null;
+ /**
+ * Their WhatsApp name, untrusted.
+ */
+ displayName?: string | null;
+ /**
+ * Phone-number or LID JID.
+ */
+ jid: string;
+};
+
/**
* A person named in a message: a Macro user when verified, else their
* WhatsApp name, else their phone number.
@@ -16498,6 +16450,28 @@ export type WhatsAppRichContent = (WhatsAppPoll & {
type: 'system';
});
+/**
+ * A chat's WhatsApp metadata as the caller's account last read it.
+ */
+export type WhatsAppRoster = {
+ /**
+ * Only admins may post.
+ */
+ announce: boolean;
+ /**
+ * WhatsApp subject.
+ */
+ name: string;
+ /**
+ * When this was read from WhatsApp.
+ */
+ observedAt: string;
+ /**
+ * Everyone in the chat.
+ */
+ participants: Array<WhatsAppParticipant>;
+};
+
/**
* Kinds of system lines.
*/
@@ -23370,7 +23344,7 @@ export type WhatsappGroupMessagesData = {
*/
before?: string | null;
/**
- * Page size, 1 through 100.
+ * Page size, up to [`PAGE_LIMIT`]; [`DEFAULT_PAGE`] when absent.
*/
limit?: number | null;
};
@@ -23398,6 +23372,22 @@ export type LinkedMessageAttachmentsResponses = {
export type LinkedMessageAttachmentsResponse = LinkedMessageAttachmentsResponses[keyof LinkedMessageAttachmentsResponses];
+export type WhatsappGroupMessageData = {
+ body?: never;
+ path: {
+ group_id: string;
+ message_id: string;
+ };
+ query?: never;
+ url: '/meta/linked/whatsapp-groups/{group_id}/messages/{message_id}';
+};
+
+export type WhatsappGroupMessageResponses = {
+ 200: WhatsAppGroupMessage;
+};
+
+export type WhatsappGroupMessageResponse = WhatsappGroupMessageResponses[keyof WhatsappGroupMessageResponses];
+
export type WhatsappGroupPermissionsData = {
body?: never;
path: {
diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.json
index 5228f51a53..fe0eda5791 100644
--- a/packages/sdk/specs/storage.json
+++ b/packages/sdk/specs/storage.json
@@ -16309,7 +16309,7 @@
},
"delete": {
"tags": ["whatsapp_linked::inbound::router"],
- "summary": "Stop syncing the group, locally.",
+ "summary": "Stop syncing the group, locally. Owner only, in their own session.",
"operationId": "linked_detach",
"parameters": [
{
@@ -16444,7 +16444,7 @@
{
"name": "limit",
"in": "query",
- "description": "Page size, 1 through 100.",
+ "description": "Page size, up to [`PAGE_LIMIT`]; [`DEFAULT_PAGE`] when absent.",
"required": false,
"schema": {
"type": ["integer", "null"],
@@ -16513,6 +16513,45 @@
}
}
},
+ "/meta/linked/whatsapp-groups/{group_id}/messages/{message_id}": {
+ "get": {
+ "tags": ["whatsapp_linked::inbound::router"],
+ "summary": "One message of the timeline, as the timeline shows it.",
+ "operationId": "whatsapp_group_message",
+ "parameters": [
+ {
+ "name": "group_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ },
+ {
+ "name": "message_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/WhatsAppGroupMessage"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/meta/linked/whatsapp-groups/{group_id}/permissions": {
"get": {
"tags": ["whatsapp_linked::inbound::router"],
@@ -19799,9 +19838,9 @@
"AdoptedGroup": {
"type": "object",
"description": "Adoption response.",
- "required": ["group_id"],
+ "required": ["groupId"],
"properties": {
- "group_id": {
+ "groupId": {
"type": "string",
"format": "uuid",
"description": "Shareable entity identifier."
@@ -33288,9 +33327,9 @@
"LinkedAccount": {
"type": "object",
"description": "One person's account, never owned by a workspace.",
- "required": ["id", "user_id", "state", "authorization_generation"],
+ "required": ["id", "userId", "state", "authorizationGeneration"],
"properties": {
- "authorization_generation": {
+ "authorizationGeneration": {
"type": "integer",
"format": "int64",
"description": "Explicit consent generation; reconnecting a socket never changes it."
@@ -33300,7 +33339,7 @@
"format": "uuid",
"description": "Stable account identity."
},
- "identity_jid": {
+ "identityJid": {
"type": ["string", "null"],
"description": "WhatsApp-verified identity, absent until the first pairing succeeds."
},
@@ -33308,7 +33347,7 @@
"$ref": "#/components/schemas/LinkedAccountState",
"description": "Lifecycle."
},
- "user_id": {
+ "userId": {
"type": "string",
"description": "Authenticated owner."
}
@@ -33339,9 +33378,9 @@
"LinkedAdoptGroup": {
"type": "object",
"description": "Explicit adoption request; the account is selected server-side. The\ngroup's name always follows WhatsApp.",
- "required": ["group_jid"],
+ "required": ["groupJid"],
"properties": {
- "group_jid": {
+ "groupJid": {
"type": "string",
"description": "A group the requester's account has joined, or a direct chat from\ntheir chat list (the other person's JID, as the list names it)."
}
@@ -33350,20 +33389,20 @@
"LinkedAttachment": {
"type": "object",
"description": "One attachment of a linked message.",
- "required": ["ordinal", "state", "file_name", "mime", "size"],
+ "required": ["ordinal", "state", "fileName", "mime", "size"],
"properties": {
- "document_id": {
+ "documentId": {
"type": ["string", "null"],
"format": "uuid",
"description": "The private document, once ready."
},
- "duration_seconds": {
+ "durationSeconds": {
"type": ["integer", "null"],
"format": "int32",
"description": "Length of audio or video in whole seconds, when declared.",
"minimum": 0
},
- "file_name": {
+ "fileName": {
"type": "string",
"description": "Display filename."
},
@@ -33436,7 +33475,14 @@
"LinkedBackfillState": {
"type": "string",
"description": "Where importing a group's earlier messages stands.",
- "enum": ["pending", "running", "waiting_for_phone", "done", "partial"]
+ "enum": [
+ "waiting_for_message",
+ "pending",
+ "running",
+ "waiting_for_phone",
+ "done",
+ "partial"
+ ]
},
"LinkedCannotAdd": {
"type": "string",
@@ -33447,34 +33493,34 @@
"type": "object",
"description": "Operations implemented for linked groups, independent of current permission.",
"required": [
- "text_limit_bytes",
+ "textLimitBytes",
"mutations",
- "mutation_window_seconds",
- "max_attachments",
- "attachment_limit_bytes",
- "attachment_types"
+ "mutationWindowSeconds",
+ "maxAttachments",
+ "attachmentLimitBytes",
+ "attachmentTypes"
],
"properties": {
- "attachment_limit_bytes": {
+ "attachmentLimitBytes": {
"type": "integer",
"format": "int32",
"description": "Largest attachment in bytes.",
"minimum": 0
},
- "attachment_types": {
+ "attachmentTypes": {
"type": "array",
"items": {
"type": "string"
},
"description": "Supported attachment MIME types."
},
- "max_attachments": {
+ "maxAttachments": {
"type": "integer",
"format": "int32",
"description": "Attachments per send.",
"minimum": 0
},
- "mutation_window_seconds": {
+ "mutationWindowSeconds": {
"type": "integer",
"format": "int32",
"description": "Edits and deletes are offered this long after sending.",
@@ -33487,7 +33533,7 @@
},
"description": "Supported message operations."
},
- "text_limit_bytes": {
+ "textLimitBytes": {
"type": "integer",
"format": "int32",
"description": "Maximum UTF-8 bytes per text send.",
@@ -33626,23 +33672,14 @@
"LinkedDeliveryState": {
"type": "string",
"description": "Observed send state. `unknown` means the request may have reached WhatsApp;\nit is never sent again automatically.",
- "enum": [
- "pending",
- "sending",
- "unknown",
- "accepted",
- "sent",
- "delivered",
- "read",
- "failed"
- ]
+ "enum": ["pending", "sending", "unknown", "accepted", "failed"]
},
"LinkedDisconnect": {
"type": "object",
"description": "Result of disconnecting an account.",
- "required": ["remote_unlink_requested"],
+ "required": ["remoteUnlinkRequested"],
"properties": {
- "remote_unlink_requested": {
+ "remoteUnlinkRequested": {
"type": "boolean",
"description": "The session service was asked to log the device out of WhatsApp. It\nunlinks asynchronously; WhatsApp's Linked devices list is authoritative."
}
@@ -33651,9 +33688,9 @@
"LinkedDisconnectRequest": {
"type": "object",
"description": "The consent generation the owner deliberately disconnects.",
- "required": ["authorization_generation"],
+ "required": ["authorizationGeneration"],
"properties": {
- "authorization_generation": {
+ "authorizationGeneration": {
"type": "integer",
"format": "int64",
"description": "Fences retries against a later reconnect or replacement."
@@ -33679,55 +33716,6 @@
}
}
},
- "LinkedGroupInfo": {
- "type": "object",
- "description": "One full metadata read of a group, never an incomplete membership delta.",
- "required": ["jid", "name", "participants", "announce", "observedAt"],
- "properties": {
- "announce": {
- "type": "boolean",
- "description": "Only admins may post."
- },
- "communityAnnouncements": {
- "type": "boolean",
- "description": "The community's announcement group (everyone reads, admins post)."
- },
- "communityJid": {
- "type": ["string", "null"],
- "description": "The community a linked subgroup or announcement group belongs to."
- },
- "communityParent": {
- "type": "boolean",
- "description": "The community itself: it has no messages of its own and can't be added."
- },
- "disappearingSeconds": {
- "type": ["integer", "null"],
- "format": "int32",
- "description": "Disappearing-messages timer in seconds while it is on. Macro keeps the\nmessages; its sends carry the timer so phones treat them like their own.",
- "minimum": 0
- },
- "jid": {
- "type": "string",
- "description": "Remote group JID."
- },
- "name": {
- "type": "string",
- "description": "Current subject."
- },
- "observedAt": {
- "type": "string",
- "format": "date-time",
- "description": "When the session service read this metadata."
- },
- "participants": {
- "type": "array",
- "items": {
- "$ref": "#/components/schemas/LinkedParticipant"
- },
- "description": "Full roster."
- }
- }
- },
"LinkedGroupReference": {
"type": "object",
"description": "A group entity bound to a remote group.",
@@ -33744,25 +33732,6 @@
}
}
},
- "LinkedIdentity": {
- "type": "object",
- "description": "Verified sender aliases, supplied only by protocol metadata.",
- "required": ["jid"],
- "properties": {
- "alternateJid": {
- "type": ["string", "null"],
- "description": "Verified alternate identity, never inferred from a name or phone typed by a user."
- },
- "displayName": {
- "type": ["string", "null"],
- "description": "Untrusted display name."
- },
- "jid": {
- "type": "string",
- "description": "Phone-number or LID account JID."
- }
- }
- },
"LinkedMediaKind": {
"type": "string",
"description": "Attachment categories WhatsApp distinguishes.",
@@ -33776,16 +33745,16 @@
"LinkedMessageAttachments": {
"type": "object",
"description": "The attachments of one linked group message.",
- "required": ["message_id", "linked_attachments"],
+ "required": ["messageId", "linkedAttachments"],
"properties": {
- "linked_attachments": {
+ "linkedAttachments": {
"type": "array",
"items": {
"$ref": "#/components/schemas/LinkedAttachment"
},
"description": "Its attachments in order; deleted ones are omitted."
},
- "message_id": {
+ "messageId": {
"type": "string",
"format": "uuid",
"description": "Group message."
@@ -33832,14 +33801,14 @@
"LinkedPairing": {
"type": "object",
"description": "Owner-bound pairing transaction, without its QR or pairing code.",
- "required": ["id", "account_id", "state", "expires_at"],
+ "required": ["id", "accountId", "state", "expiresAt"],
"properties": {
- "account_id": {
+ "accountId": {
"type": "string",
"format": "uuid",
"description": "Account being connected."
},
- "expires_at": {
+ "expiresAt": {
"type": "string",
"format": "date-time",
"description": "Database-assigned deadline."
@@ -33868,25 +33837,6 @@
"failed"
]
},
- "LinkedParticipant": {
- "allOf": [
- {
- "$ref": "#/components/schemas/LinkedIdentity",
- "description": "Identity evidence."
- },
- {
- "type": "object",
- "required": ["admin"],
- "properties": {
- "admin": {
- "type": "boolean",
- "description": "Group admin; only admins post in announcement groups."
- }
- }
- }
- ],
- "description": "Current remote participant; Macro access is a separate grant."
- },
"LinkedReplyBlock": {
"type": "string",
"description": "Why the viewer cannot send now.",
@@ -33926,7 +33876,7 @@
{
"type": "object",
"description": "One attachment staged through the attachments route.",
- "required": ["upload_id", "type"],
+ "required": ["uploadId", "type"],
"properties": {
"caption": {
"type": ["string", "null"],
@@ -33936,7 +33886,7 @@
"type": "string",
"enum": ["media"]
},
- "upload_id": {
+ "uploadId": {
"type": "string",
"format": "uuid",
"description": "The staged upload, which becomes the message's private document."
@@ -33946,9 +33896,9 @@
{
"type": "object",
"description": "An operation on an existing message in this group.",
- "required": ["message_id", "operation", "type"],
+ "required": ["messageId", "operation", "type"],
"properties": {
- "message_id": {
+ "messageId": {
"type": "string",
"format": "uuid",
"description": "Existing group message, resolved to its WhatsApp source by the server."
@@ -33975,23 +33925,23 @@
"description": "Durable result of a deliberate send.",
"required": [
"id",
- "user_id",
- "group_id",
+ "userId",
+ "groupId",
"payload",
"state",
- "created_at"
+ "createdAt"
],
"properties": {
- "created_at": {
+ "createdAt": {
"type": "string",
"format": "date-time",
"description": "Intent creation time."
},
- "error_code": {
+ "errorCode": {
"type": ["string", "null"],
"description": "Sanitized failure code."
},
- "group_id": {
+ "groupId": {
"type": "string",
"format": "uuid",
"description": "Group entity."
@@ -34001,7 +33951,7 @@
"format": "uuid",
"description": "Stable intent id."
},
- "message_id": {
+ "messageId": {
"type": ["string", "null"],
"format": "uuid",
"description": "Group message, once WhatsApp accepted it."
@@ -34014,7 +33964,7 @@
"$ref": "#/components/schemas/LinkedDeliveryState",
"description": "Current state."
},
- "user_id": {
+ "userId": {
"type": "string",
"description": "Person who submitted it."
}
@@ -34023,9 +33973,9 @@
"LinkedSendReply": {
"type": "object",
"description": "Explicit send action from a person. Only deliberate sends reach WhatsApp.",
- "required": ["idempotency_key", "message"],
+ "required": ["idempotencyKey", "message"],
"properties": {
- "idempotency_key": {
+ "idempotencyKey": {
"type": "string",
"format": "uuid",
"description": "Stable client intent key. A changed payload with this key is a conflict."
@@ -34034,7 +33984,7 @@
"$ref": "#/components/schemas/LinkedReplyContent",
"description": "Content."
},
- "reply_to": {
+ "replyTo": {
"type": ["string", "null"],
"format": "uuid",
"description": "Group message being quoted, within this group."
@@ -34076,7 +34026,7 @@
"LinkedUploadedAttachment": {
"type": "object",
"description": "A staged attachment, sent only by a later deliberate send.",
- "required": ["upload_id", "filename", "kind"],
+ "required": ["uploadId", "filename", "kind"],
"properties": {
"filename": {
"type": "string",
@@ -34086,7 +34036,7 @@
"$ref": "#/components/schemas/LinkedMediaKind",
"description": "Category."
},
- "upload_id": {
+ "uploadId": {
"type": "string",
"format": "uuid",
"description": "Use as `upload_id` in a media send; also the future document id."
@@ -34266,9 +34216,9 @@
"MarkRead": {
"type": "object",
"description": "Mark messages through this message read.",
- "required": ["message_id"],
+ "required": ["messageId"],
"properties": {
- "message_id": {
+ "messageId": {
"type": "string",
"format": "uuid",
"description": "Message in the addressed group."
@@ -44684,24 +44634,13 @@
},
{
"type": "object",
- "required": ["share_permission", "access_level", "limits"],
+ "required": ["sharePermission", "accessLevel", "limits"],
"properties": {
- "access_level": {
+ "accessLevel": {
"$ref": "#/components/schemas/AccessLevel",
"description": "Caller's effective permission."
},
- "community": {
- "oneOf": [
- {
- "type": "null"
- },
- {
- "$ref": "#/components/schemas/LinkedCommunityReference",
- "description": "The WhatsApp community this group belongs to, if any."
- }
- ]
- },
- "disappearing_seconds": {
+ "disappearingSeconds": {
"type": ["integer", "null"],
"format": "int32",
"description": "WhatsApp's disappearing-messages timer in seconds while it is on;\nMacro keeps the messages anyway. `null` when off or unknown.",
@@ -44717,16 +44656,16 @@
"type": "null"
},
{
- "$ref": "#/components/schemas/LinkedGroupInfo",
+ "$ref": "#/components/schemas/WhatsAppRoster",
"description": "Latest remote metadata, absent when no observer is connected."
}
]
},
- "sending_identity": {
+ "sendingIdentity": {
"type": ["string", "null"],
"description": "Caller's own phone identity, never another account's identity."
},
- "share_permission": {
+ "sharePermission": {
"$ref": "#/components/schemas/SharePermissionV2",
"description": "Owner-controlled standard sharing configuration."
}
@@ -44742,14 +44681,14 @@
"id",
"sender",
"body",
- "sent_at",
- "received_at",
+ "sentAt",
+ "receivedAt",
"deleted",
"reactions",
"attachments",
"kind",
"forwarded",
- "view_once",
+ "viewOnce",
"mentions"
],
"properties": {
@@ -44768,7 +44707,7 @@
"type": "boolean",
"description": "Deleted for everyone."
},
- "delivery_state": {
+ "deliveryState": {
"oneOf": [
{
"type": "null"
@@ -44779,7 +44718,7 @@
}
]
},
- "edited_at": {
+ "editedAt": {
"type": ["string", "null"],
"format": "date-time",
"description": "Last edit timestamp."
@@ -44811,12 +44750,12 @@
},
"description": "Reactions grouped by emoji."
},
- "received_at": {
+ "receivedAt": {
"type": "string",
"format": "date-time",
"description": "Timestamp first received by Macro."
},
- "reply_to": {
+ "replyTo": {
"type": ["string", "null"],
"format": "uuid",
"description": "Message quoted by this one."
@@ -44836,12 +44775,12 @@
"$ref": "#/components/schemas/WhatsAppGroupSender",
"description": "Sender."
},
- "sent_at": {
+ "sentAt": {
"type": "string",
"format": "date-time",
"description": "Timestamp assigned by WhatsApp."
},
- "view_once": {
+ "viewOnce": {
"type": "boolean",
"description": "Sent as view-once in WhatsApp; Macro shows it like any media."
}
@@ -44859,7 +44798,7 @@
},
"description": "Messages in descending sent_at, id order."
},
- "next_cursor": {
+ "nextCursor": {
"type": ["string", "null"],
"format": "uuid",
"description": "Cursor for older messages."
@@ -44889,18 +44828,18 @@
"WhatsAppGroupSender": {
"type": "object",
"description": "Message sender from protocol-verified identity evidence.",
- "required": ["person_id", "name"],
+ "required": ["personId", "name"],
"properties": {
"name": {
"type": "string",
"description": "Display name, never authentication evidence."
},
- "person_id": {
+ "personId": {
"type": "string",
"format": "uuid",
"description": "External person identity."
},
- "user_id": {
+ "userId": {
"type": ["string", "null"],
"description": "Verified Macro user association, if present."
}
@@ -44909,14 +44848,7 @@
"WhatsAppGroupSummary": {
"type": "object",
"description": "Adopted group visible through ordinary entity sharing.",
- "required": [
- "id",
- "name",
- "kind",
- "user_id",
- "unread_count",
- "can_send"
- ],
+ "required": ["id", "name", "kind", "userId", "unreadCount", "canSend"],
"properties": {
"backfill": {
"oneOf": [
@@ -44925,14 +44857,25 @@
},
{
"$ref": "#/components/schemas/LinkedBackfill",
- "description": "Importing earlier messages after the group was added; `null` for\ngroups added before this existed."
+ "description": "Importing earlier messages after the chat was added; `null` when\nthere is nothing to import."
}
]
},
- "can_send": {
+ "canSend": {
"type": "boolean",
"description": "Caller may currently send from their own account."
},
+ "community": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/LinkedCommunityReference",
+ "description": "The WhatsApp community this group belongs to, if any."
+ }
+ ]
+ },
"id": {
"type": "string",
"format": "uuid",
@@ -44942,7 +44885,7 @@
"$ref": "#/components/schemas/LinkedChatKind",
"description": "A group, or a direct chat with one person (only its owner sends)."
},
- "last_message_at": {
+ "lastMessageAt": {
"type": ["string", "null"],
"format": "date-time",
"description": "Latest message timestamp."
@@ -44951,7 +44894,7 @@
"type": "string",
"description": "Display name: the group's, or a direct chat's other person."
},
- "send_reason": {
+ "sendReason": {
"oneOf": [
{
"type": "null"
@@ -44962,12 +44905,12 @@
}
]
},
- "unread_count": {
+ "unreadCount": {
"type": "integer",
"format": "int64",
- "description": "Unread live messages for this viewer."
+ "description": "Unread live messages for this viewer, counted up to\n[`UNREAD_COUNT_CAP`]."
},
- "user_id": {
+ "userId": {
"type": "string",
"description": "Actual entity owner."
}
@@ -45034,6 +44977,29 @@
"description": "What a timeline entry is.",
"enum": ["message", "system"]
},
+ "WhatsAppParticipant": {
+ "type": "object",
+ "description": "Someone in a WhatsApp chat; Macro access is a separate grant.",
+ "required": ["jid", "admin"],
+ "properties": {
+ "admin": {
+ "type": "boolean",
+ "description": "Group admin."
+ },
+ "alternateJid": {
+ "type": ["string", "null"],
+ "description": "The other address WhatsApp verified for them."
+ },
+ "displayName": {
+ "type": ["string", "null"],
+ "description": "Their WhatsApp name, untrusted."
+ },
+ "jid": {
+ "type": "string",
+ "description": "Phone-number or LID JID."
+ }
+ }
+ },
"WhatsAppPersonRef": {
"type": "object",
"description": "A person named in a message: a Macro user when verified, else their\nWhatsApp name, else their phone number.",
@@ -45205,6 +45171,33 @@
],
"description": "Structured content of a message besides its body."
},
+ "WhatsAppRoster": {
+ "type": "object",
+ "description": "A chat's WhatsApp metadata as the caller's account last read it.",
+ "required": ["name", "participants", "announce", "observedAt"],
+ "properties": {
+ "announce": {
+ "type": "boolean",
+ "description": "Only admins may post."
+ },
+ "name": {
+ "type": "string",
+ "description": "WhatsApp subject."
+ },
+ "observedAt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "When this was read from WhatsApp."
+ },
+ "participants": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/WhatsAppParticipant"
+ },
+ "description": "Everyone in the chat."
+ }
+ }
+ },
"WhatsAppSystemAction": {
"type": "string",
"description": "Kinds of system lines.",
diff --git a/packages/sdk/src/entities/whatsapp/account.ts b/packages/sdk/src/entities/whatsapp/account.ts
index 787c3e8927..fab98164a1 100644
--- a/packages/sdk/src/entities/whatsapp/account.ts
+++ b/packages/sdk/src/entities/whatsapp/account.ts
@@ -28,10 +28,10 @@ export class WhatsAppAccount extends MacroEntity<LinkedAccount> {
readonly state = this.field('state');
/** Verified remote identity, absent until pairing succeeds. */
- readonly identity = this.field('identity_jid');
+ readonly identity = this.field('identityJid');
/** The Macro user who owns this account. */
- readonly owner = this.mappedField('user_id', (id) =>
+ readonly owner = this.mappedField('userId', (id) =>
User.byId(this.client, id),
);
diff --git a/packages/sdk/src/entities/whatsapp/chat.ts b/packages/sdk/src/entities/whatsapp/chat.ts
index 65bb200316..b8260ef3d8 100644
--- a/packages/sdk/src/entities/whatsapp/chat.ts
+++ b/packages/sdk/src/entities/whatsapp/chat.ts
@@ -91,9 +91,9 @@ export class WhatsAppChat extends MacroEntity<LinkedChat> {
*/
async adopt(): Promise<WhatsAppGroup> {
const result = await this.mutate((client) =>
- client.storage.linkedAdopt({ body: { group_jid: this.id } }),
+ client.storage.linkedAdopt({ body: { groupJid: this.id } }),
);
- return WhatsAppGroup.byId(this.client, result.group_id);
+ return WhatsAppGroup.byId(this.client, result.groupId);
}
/** Reload the chat's list entry. */
diff --git a/packages/sdk/src/entities/whatsapp/group.ts b/packages/sdk/src/entities/whatsapp/group.ts
index 70f9e6907d..0243d48a92 100644
--- a/packages/sdk/src/entities/whatsapp/group.ts
+++ b/packages/sdk/src/entities/whatsapp/group.ts
@@ -52,13 +52,13 @@ export class WhatsAppGroup extends FavoritableEntity<WhatsAppGroupDetail> {
/** `group`, or `direct` for a one-to-one chat (only its owner sends). */
readonly kind = this.field('kind');
/** Whether the caller can send from their own connected account. */
- readonly canSend = this.field('can_send');
+ readonly canSend = this.field('canSend');
/** Reason sending is blocked. */
- readonly sendReason = this.field('send_reason');
+ readonly sendReason = this.field('sendReason');
/** Caller's own verified sending identity. */
- readonly sendingIdentity = this.field('sending_identity');
+ readonly sendingIdentity = this.field('sendingIdentity');
/** Per-user unread count. */
- readonly unreadCount = this.field('unread_count');
+ readonly unreadCount = this.field('unreadCount');
/** Importing earlier messages from the owner's phone after adding, if any. */
readonly backfill = this.field('backfill');
/** Supported sizes and mutation window. */
@@ -72,13 +72,13 @@ export class WhatsAppGroup extends FavoritableEntity<WhatsAppGroupDetail> {
),
);
/** WhatsApp's disappearing-messages timer in seconds while on; Macro keeps the messages. */
- readonly disappearingSeconds = this.field('disappearing_seconds');
+ readonly disappearingSeconds = this.field('disappearingSeconds');
/** The WhatsApp community this group belongs to, if any: the community's own chat, its name, and whether this is its announcement group. */
readonly community = this.mappedField('community', (record) =>
record ? communityOf(this.client, record) : undefined,
);
/** Actual owner, independent of WhatsApp membership. */
- readonly owner = this.mappedField('user_id', (id) =>
+ readonly owner = this.mappedField('userId', (id) =>
User.byId(this.client, id),
);
@@ -97,7 +97,7 @@ export class WhatsAppGroup extends FavoritableEntity<WhatsAppGroupDetail> {
items: page.messages.map((message) =>
WhatsAppMessage.from(this.client, this, message),
),
- nextCursor: page.next_cursor,
+ nextCursor: page.nextCursor,
};
});
}
@@ -108,7 +108,7 @@ export class WhatsAppGroup extends FavoritableEntity<WhatsAppGroupDetail> {
await this.mutate((client) =>
client.storage.whatsappGroupRead({
path: { group_id: this.id },
- body: { message_id: message.id },
+ body: { messageId: message.id },
}),
);
}
@@ -176,7 +176,7 @@ export class WhatsAppGroup extends FavoritableEntity<WhatsAppGroupDetail> {
this.assertGroup(value.upload.group);
return {
type: 'media',
- upload_id: value.upload.id,
+ uploadId: value.upload.id,
caption: value.caption,
};
})
@@ -184,7 +184,7 @@ export class WhatsAppGroup extends FavoritableEntity<WhatsAppGroupDetail> {
this.assertGroup(value.message.group);
return {
type: 'mutation',
- message_id: value.message.id,
+ messageId: value.message.id,
operation: value.operation,
text: value.text,
};
@@ -194,9 +194,9 @@ export class WhatsAppGroup extends FavoritableEntity<WhatsAppGroupDetail> {
client.storage.linkedReply({
path: { group_id: this.id },
body: {
- idempotency_key: options.idempotencyKey,
+ idempotencyKey: options.idempotencyKey,
message,
- reply_to: options.replyTo?.id,
+ replyTo: options.replyTo?.id,
},
}),
);
@@ -234,15 +234,15 @@ export class WhatsAppGroup extends FavoritableEntity<WhatsAppGroupDetail> {
body: messages.map((message) => message.id),
}),
).map((record) => ({
- message: WhatsAppMessage.byId(this.client, this, record.message_id),
- attachments: record.linked_attachments.map((attachment) => ({
+ message: WhatsAppMessage.byId(this.client, this, record.messageId),
+ attachments: record.linkedAttachments.map((attachment) => ({
ordinal: attachment.ordinal,
state: attachment.state,
- fileName: attachment.file_name,
+ fileName: attachment.fileName,
mime: attachment.mime,
size: attachment.size,
- document: attachment.document_id
- ? Document.byId(this.client, attachment.document_id)
+ document: attachment.documentId
+ ? Document.byId(this.client, attachment.documentId)
: undefined,
})),
}));
diff --git a/packages/sdk/src/entities/whatsapp/message.ts b/packages/sdk/src/entities/whatsapp/message.ts
index eb66ca6207..f213f11b98 100644
--- a/packages/sdk/src/entities/whatsapp/message.ts
+++ b/packages/sdk/src/entities/whatsapp/message.ts
@@ -1,5 +1,5 @@
import type { WhatsAppGroupMessage } from '../../../generated/storage/types.gen';
-import { MacroNotFoundError } from '../../utils';
+import { unwrap } from '../../utils';
import type { MacroClient } from '../../utils/client';
import { Document } from '../documents/document';
import { MacroEntity } from '../entity';
@@ -36,10 +36,11 @@ export class WhatsAppMessage extends MacroEntity<WhatsAppGroupMessage> {
}
protected async fetch(): Promise<WhatsAppGroupMessage> {
- for await (const message of this.group.messages({ limit: 100 })) {
- if (message.id === this.id) return message.detail.get();
- }
- throw new MacroNotFoundError('WhatsApp message is not available');
+ return unwrap(
+ await this.client.storage.whatsappGroupMessage({
+ path: { group_id: this.group.id, message_id: this.id },
+ }),
+ );
}
/** Plain WhatsApp text. */
@@ -47,28 +48,28 @@ export class WhatsAppMessage extends MacroEntity<WhatsAppGroupMessage> {
/** Protocol-verified sender association and display name. */
readonly sender = this.field('sender');
/** WhatsApp timestamp. */
- readonly sentAt = this.field('sent_at');
+ readonly sentAt = this.field('sentAt');
/** Last edit time. */
- readonly editedAt = this.field('edited_at');
+ readonly editedAt = this.field('editedAt');
/** Deleted for everyone. */
readonly deleted = this.field('deleted');
/** Grouped emoji counts and caller's own reaction. */
readonly reactions = this.field('reactions');
/** Caller-owned send's delivery state, when present. */
- readonly deliveryState = this.field('delivery_state');
+ readonly deliveryState = this.field('deliveryState');
/** `message`, or `system` for something that happened in the group (see `rich`). */
readonly kind = this.field('kind');
/** Forwarded from another chat. */
readonly forwarded = this.field('forwarded');
/** Sent as view-once in WhatsApp; Macro keeps and shows it like any media. */
- readonly viewOnce = this.field('view_once');
+ readonly viewOnce = this.field('viewOnce');
/** People the body @-mentions: `@<token>` in the body is this person. */
readonly mentions = this.field('mentions');
/** Poll (with tallies), location, contact cards, event or system line. */
readonly rich = this.field('rich');
/** Quoted message in this group. */
readonly replyTo: () => Promise<WhatsAppMessage | undefined> =
- this.mappedField('reply_to', (id) =>
+ this.mappedField('replyTo', (id) =>
id ? WhatsAppMessage.byId(this.client, this.group, id) : undefined,
);
/** Attachment state and imported document handles. */
@@ -76,15 +77,15 @@ export class WhatsAppMessage extends MacroEntity<WhatsAppGroupMessage> {
records.map((record) => ({
ordinal: record.ordinal,
state: record.state,
- fileName: record.file_name,
+ fileName: record.fileName,
mime: record.mime,
size: record.size,
width: record.width ?? undefined,
height: record.height ?? undefined,
- durationSeconds: record.duration_seconds ?? undefined,
+ durationSeconds: record.durationSeconds ?? undefined,
presentation: record.presentation ?? undefined,
- document: record.document_id
- ? Document.byId(this.client, record.document_id)
+ document: record.documentId
+ ? Document.byId(this.client, record.documentId)
: undefined,
})),
);
diff --git a/packages/sdk/src/entities/whatsapp/participant.ts b/packages/sdk/src/entities/whatsapp/participant.ts
index d8c1eb533b..83649f2307 100644
--- a/packages/sdk/src/entities/whatsapp/participant.ts
+++ b/packages/sdk/src/entities/whatsapp/participant.ts
@@ -1,4 +1,4 @@
-import type { LinkedParticipant as WhatsAppParticipantRecord } from '../../../generated/storage/types.gen';
+import type { WhatsAppParticipant as WhatsAppParticipantRecord } from '../../../generated/storage/types.gen';
import type { WhatsAppGroup } from './group';
/** Someone in an added WhatsApp chat, from its roster; mention them in a text reply. */
diff --git a/packages/sdk/src/entities/whatsapp/send.ts b/packages/sdk/src/entities/whatsapp/send.ts
index e3dcf81c73..97266f6dca 100644
--- a/packages/sdk/src/entities/whatsapp/send.ts
+++ b/packages/sdk/src/entities/whatsapp/send.ts
@@ -54,13 +54,13 @@ export class WhatsAppSend extends MacroEntity<LinkedSendProgress> {
readonly state = this.field('state');
/** Sanitized failure code, when present. */
- readonly errorCode = this.field('error_code');
+ readonly errorCode = this.field('errorCode');
/** When the send intent was created. */
- readonly createdAt = this.field('created_at');
+ readonly createdAt = this.field('createdAt');
/** Group message once WhatsApp accepted the send. */
- readonly message = this.mappedField('message_id', (id) =>
+ readonly message = this.mappedField('messageId', (id) =>
id ? WhatsAppMessage.byId(this.client, this.group, id) : undefined,
);
@@ -76,12 +76,12 @@ export class WhatsAppSend extends MacroEntity<LinkedSendProgress> {
.returnType<WhatsAppReply>()
.with({ type: 'media' }, (wire) => ({
type: 'media',
- upload: WhatsAppUpload.byId(this.group, wire.upload_id),
+ upload: WhatsAppUpload.byId(this.group, wire.uploadId),
caption: wire.caption ?? undefined,
}))
.with({ type: 'mutation' }, (wire) => ({
type: 'mutation',
- message: WhatsAppMessage.byId(this.client, this.group, wire.message_id),
+ message: WhatsAppMessage.byId(this.client, this.group, wire.messageId),
operation: wire.operation,
text: wire.text ?? undefined,
}))
@@ -94,10 +94,10 @@ export class WhatsAppSend extends MacroEntity<LinkedSendProgress> {
}))
.exhaustive();
return {
- idempotencyKey: payload.idempotency_key,
+ idempotencyKey: payload.idempotencyKey,
message,
- replyTo: payload.reply_to
- ? WhatsAppMessage.byId(this.client, this.group, payload.reply_to)
+ replyTo: payload.replyTo
+ ? WhatsAppMessage.byId(this.client, this.group, payload.replyTo)
: undefined,
};
}
diff --git a/packages/sdk/src/entities/whatsapp/upload.ts b/packages/sdk/src/entities/whatsapp/upload.ts
index fcbb33a7d3..b0accef18b 100644
--- a/packages/sdk/src/entities/whatsapp/upload.ts
+++ b/packages/sdk/src/entities/whatsapp/upload.ts
@@ -25,7 +25,7 @@ export class WhatsAppUpload {
record: LinkedUploadedAttachment,
): WhatsAppUpload {
return new WhatsAppUpload(
- record.upload_id,
+ record.uploadId,
group,
record.filename,
record.kind,
diff --git a/packages/sdk/src/macro.ts b/packages/sdk/src/macro.ts
index b65d543eb8..72339a3e99 100644
--- a/packages/sdk/src/macro.ts
+++ b/packages/sdk/src/macro.ts
@@ -303,7 +303,10 @@ export {
export { AccessRequest, EntityAccess } from './entities/sharing/access';
export type { SharePermissionOptions } from './entities/sharing/permissions';
export { WhatsAppAccount } from './entities/whatsapp/account';
-export { WhatsAppChat } from './entities/whatsapp/chat';
+export {
+ WhatsAppChat,
+ type WhatsAppCommunity,
+} from './entities/whatsapp/chat';
export {
WhatsAppGroup,
type WhatsAppReply,
diff --git a/packages/sdk/tests/whatsapp.test.ts b/packages/sdk/tests/whatsapp.test.ts
index 174a5346d0..2f050226fd 100644
--- a/packages/sdk/tests/whatsapp.test.ts
+++ b/packages/sdk/tests/whatsapp.test.ts
@@ -15,25 +15,25 @@ afterEach(() => {
const account = {
id: 'account',
- user_id: 'owner',
+ userId: 'owner',
state: 'connected',
- identity_jid: '[email protected]',
- authorization_generation: 1,
+ identityJid: '[email protected]',
+ authorizationGeneration: 1,
};
const summary = {
id: 'group',
name: 'Support',
kind: 'group',
- user_id: 'owner',
- unread_count: 1,
- last_message_at: '2026-10-21',
- can_send: true,
- send_reason: null,
+ userId: 'owner',
+ unreadCount: 1,
+ lastMessageAt: '2026-10-21',
+ canSend: true,
+ sendReason: null,
};
const remote = { jid: '[email protected]' };
const roster = {
name: 'Remote support',
- observed_at: '2026-10-21',
+ observedAt: '2026-10-21',
announce: false,
participants: [
{
@@ -47,50 +47,50 @@ const roster = {
const detail = {
...summary,
roster,
- disappearing_seconds: 604800,
+ disappearingSeconds: 604800,
community: { id: '[email protected]', name: 'Neighbours', announcements: false },
- sending_identity: account.identity_jid,
- access_level: 'owner',
- share_permission: {
+ sendingIdentity: account.identityJid,
+ accessLevel: 'owner',
+ sharePermission: {
id: 'permission',
owner: 'owner',
linkShare: null,
teamShareAccessLevel: null,
},
limits: {
- text_limit_bytes: 16384,
- mutation_window_seconds: 600,
- max_attachments: 1,
- attachment_limit_bytes: 33554432,
- attachment_types: ['text/plain'],
+ textLimitBytes: 16384,
+ mutationWindowSeconds: 600,
+ maxAttachments: 1,
+ attachmentLimitBytes: 33554432,
+ attachmentTypes: ['text/plain'],
mutations: ['reaction', 'edit', 'delete'],
},
};
const progress = {
id: 'intent',
- group_id: 'group',
- user_id: 'owner',
+ groupId: 'group',
+ userId: 'owner',
state: 'unknown',
- message_id: null,
- error_code: null,
- created_at: '2026-10-21',
+ messageId: null,
+ errorCode: null,
+ createdAt: '2026-10-21',
payload: {
- idempotency_key: 'stable',
+ idempotencyKey: 'stable',
message: { type: 'text', text: 'hello' },
},
};
const message = {
id: 'message',
- sender: { person_id: 'person', user_id: null, name: 'Customer' },
+ sender: { personId: 'person', userId: null, name: 'Customer' },
body: 'hello',
- reply_to: null,
- sent_at: '2026-10-21',
- received_at: '2026-10-21',
- edited_at: null,
+ replyTo: null,
+ sentAt: '2026-10-21',
+ receivedAt: '2026-10-21',
+ editedAt: null,
deleted: false,
reactions: [],
attachments: [],
- delivery_state: null,
+ deliveryState: null,
};
function fixture(handler: (request: Request) => Response | Promise<Response>) {
@@ -145,7 +145,7 @@ test('the chat list shows a group someone else shared instead of adding it again
shared: {
id: 'theirs',
name: 'Remote support',
- owner_id: 'macro|[email protected]',
+ ownerId: 'macro|[email protected]',
},
canAdd: false,
cannotAddReason: null,
@@ -177,7 +177,7 @@ test('the chat list lists groups and direct chats and adds a group by its handle
const { macro, requests } = fixture((request) =>
Response.json(
request.method === 'POST'
- ? { group_id: 'group' }
+ ? { groupId: 'group' }
: {
chats: [
{
@@ -227,7 +227,7 @@ test('the chat list lists groups and direct chats and adds a group by its handle
'/meta/linked/chats',
'/meta/linked/groups/adopt',
]);
- expect(await requests[1].json()).toEqual({ group_jid: remote.jid });
+ expect(await requests[1].json()).toEqual({ groupJid: remote.jid });
});
test('account access stays owner-scoped and no account normalizes to undefined', async () => {
@@ -242,8 +242,8 @@ test('timeline pagination is lazy and messages use their own group-scoped handle
const { group, requests } = fixture((request) =>
Response.json(
new URL(request.url).searchParams.has('before')
- ? { messages: [{ ...message, id: 'older' }], next_cursor: null }
- : { messages: [message], next_cursor: 'message' },
+ ? { messages: [{ ...message, id: 'older' }], nextCursor: null }
+ : { messages: [message], nextCursor: 'message' },
),
);
const iterator = group.messages({ limit: 1 });
@@ -265,7 +265,7 @@ test('read cursors and permission changes use standalone routes and reject cross
() => new Response(null, { status: 204 }),
);
await group.markRead(WhatsAppMessage.byId(macro._client, group, 'message'));
- expect(await requests[0].json()).toEqual({ message_id: 'message' });
+ expect(await requests[0].json()).toEqual({ messageId: 'message' });
await group.updatePermissions({ teamShareAccessLevel: 'view' });
expect(requests[1].method).toBe('PATCH');
expect(new URL(requests[1].url).pathname).toBe(
@@ -295,7 +295,7 @@ test('owner-token send preserves intent and unknown delivery is read without res
expect(sent.group.id).toBe('group');
expect(await sent.state()).toBe('unknown');
expect(await requests[0].json()).toEqual({
- idempotency_key: 'stable',
+ idempotencyKey: 'stable',
message: { type: 'text', text: 'hello', mentions: [] },
});
await sent.refresh();
@@ -312,7 +312,7 @@ test('owner-token send preserves intent and unknown delivery is read without res
test('staged uploads stay scoped to their adopted group and carry no credentials', async () => {
const { macro, group, requests } = fixture(() =>
Response.json({
- upload_id: 'upload',
+ uploadId: 'upload',
filename: 'note.txt',
kind: 'document',
}),
@@ -341,10 +341,10 @@ test('mutations and replies accept only standalone WhatsApp messages', async ()
{ idempotencyKey: 'reaction' },
);
expect(await requests[0].json()).toEqual({
- idempotency_key: 'reaction',
+ idempotencyKey: 'reaction',
message: {
type: 'mutation',
- message_id: 'message',
+ messageId: 'message',
operation: 'reaction',
text: '👍',
},
@@ -363,7 +363,7 @@ test("a text reply mentions roster participants and refuses another chat's", asy
{ idempotencyKey: 'mention' },
);
expect(await requests[1].json()).toEqual({
- idempotency_key: 'mention',
+ idempotencyKey: 'mention',
message: {
type: 'text',
text: 'hi @15550001111',
@@ -383,6 +383,16 @@ test("a text reply mentions roster participants and refuses another chat's", asy
expect(requests).toHaveLength(2);
});
+test('a message handle reads only its own message', async () => {
+ const { macro, group, requests } = fixture(() => Response.json(message));
+ const handle = WhatsAppMessage.byId(macro._client, group, 'message');
+ expect(await handle.body()).toBe('hello');
+ expect(handle.group.id).toBe('group');
+ expect(requests.map((r) => new URL(r.url).pathname)).toEqual([
+ '/meta/linked/whatsapp-groups/group/messages/message',
+ ]);
+});
+
test('a chat handle reads its entry from the chat list', async () => {
const { macro, requests } = fixture(() =>
Response.json({
@@ -417,15 +427,15 @@ test('sends, delivery and attachment states stay scoped to the chat', async () =
if (path.endsWith('/messages/attachments'))
return Response.json([
{
- message_id: 'message',
- linked_attachments: [
+ messageId: 'message',
+ linkedAttachments: [
{
ordinal: 0,
state: 'ready',
- file_name: 'note.txt',
+ fileName: 'note.txt',
mime: 'text/plain',
size: 5,
- document_id: 'document',
+ documentId: 'document',
},
],
},
@@ -459,8 +469,8 @@ test('a send recovers its original intent as handles', async () => {
{
...progress,
payload: {
- idempotency_key: 'stable',
- reply_to: 'quoted',
+ idempotencyKey: 'stable',
+ replyTo: 'quoted',
message: {
type: 'text',
text: 'hi @15550001111',
diff --git a/services/document_storage_service/src/api/swagger.rs b/services/document_storage_service/src/api/swagger.rs
index 6af3d5d759..efc9e59d2e 100644
--- a/services/document_storage_service/src/api/swagger.rs
+++ b/services/document_storage_service/src/api/swagger.rs
@@ -466,6 +466,7 @@ use utoipa::OpenApi;
whatsapp_linked::inbound::router::message_attachments,
whatsapp_linked::inbound::router::adopted_groups,
whatsapp_linked::inbound::router::messages,
+ whatsapp_linked::inbound::router::message,
whatsapp_linked::inbound::router::mark_read,
whatsapp_linked::inbound::router::open_sends,
whatsapp_linked::inbound::router::permissions,
diff --git a/services/document_storage_service/src/whatsapp_linked.rs b/services/document_storage_service/src/whatsapp_linked.rs
index ce9eb54eca..13c9440d2b 100644
--- a/services/document_storage_service/src/whatsapp_linked.rs
+++ b/services/document_storage_service/src/whatsapp_linked.rs
@@ -34,14 +34,8 @@ use whatsapp_linked::{
service::LinkedService,
},
inbound::router::LinkedRouterState,
- outbound::{
- access::EntityAccessAuthorizer,
- pg::{
- PgLinkedRepository,
- signals::{self, Change, ChangeSignal},
- },
- trace_context,
- },
+ outbound::pg::PgLinkedRepository,
+ signals::{self, Change, ChangeSignal, trace_context},
};
/// Router state mounted at `/meta/linked`.
@@ -97,7 +91,6 @@ pub(crate) fn build(dependencies: Dependencies) -> State {
let service = LinkedService::new(
features,
repository.clone(),
- Arc::new(EntityAccessAuthorizer::new(access.clone())),
Arc::new(SendRequestLimiter(rate_limit::RateLimitServiceImpl {
repo: rate_limit::RedisRateLimitAdapter { redis },
})),
@@ -358,7 +351,12 @@ struct DssGroupPublisher {
}
#[async_trait]
impl GroupPublisher for DssGroupPublisher {
- #[tracing::instrument(name="whatsapp.groups.notify",skip_all,err,fields(group_id=%effect.group_id,message_id=%effect.message_id))]
+ #[tracing::instrument(
+ name = "whatsapp.linked.notify",
+ skip_all,
+ err,
+ fields(group_id = %effect.group_id, message_id = %effect.message_id)
+ )]
async fn publish(&self, effect: &GroupEffect) -> LinkedResult<()> {
if !effect.first_publication || effect.origin == Origin::History {
return Ok(());
@@ -428,9 +426,9 @@ impl DocumentStore for DssDocumentStore {
name = "whatsapp.linked.store_document",
skip_all,
err,
- fields(document_id = %import.document_id, group_id = %import.group_id, size = import.bytes.len())
+ fields(document_id = %import.document_id, group_id = %import.group_id, size = bytes.len())
)]
- async fn store(&self, import: &DocumentImport) -> LinkedResult<()> {
+ async fn store(&self, import: &DocumentImport, bytes: Vec<u8>) -> LinkedResult<()> {
let id = import.document_id.to_string();
let owner = MacroUserIdStr::try_from(import.owner.clone()).map_err(unavailable)?;
let file_type = FileType::all()
@@ -494,9 +492,7 @@ impl DocumentStore for DssDocumentStore {
))
.content_type(file_type.mime_type())
.checksum_sha256(base64::engine::general_purpose::STANDARD.encode(import.sha256))
- .body(aws_sdk_s3::primitives::ByteStream::from(
- import.bytes.clone(),
- ))
+ .body(aws_sdk_s3::primitives::ByteStream::from(bytes))
.send()
.await
.map_err(unavailable)?;
@@ -512,9 +508,9 @@ struct SendRequestLimiter<R>(R);
#[async_trait]
impl<R: rate_limit::RateLimitService> SendRateLimiter for SendRequestLimiter<R> {
#[tracing::instrument(name = "whatsapp.linked.send_rate_limit", skip_all, err)]
- async fn check(&self, user: &str) -> LinkedResult<()> {
+ async fn check(&self, user: &MacroUserIdStr<'_>) -> LinkedResult<()> {
let key = rate_limit::RateLimitKey::builder(&"whatsapp-linked-send")
- .append(&user)
+ .append(&user.as_ref())
.finish();
let result = self
.0
diff --git a/services/document_storage_service/src/whatsapp_linked/test.rs b/services/document_storage_service/src/whatsapp_linked/test.rs
index e6a7190bdc..42c36cf609 100644
--- a/services/document_storage_service/src/whatsapp_linked/test.rs
+++ b/services/document_storage_service/src/whatsapp_linked/test.rs
@@ -1,4 +1,11 @@
use super::*;
+
+/// A test person's typed id.
+fn person(name: &str) -> MacroUserIdStr<'static> {
+ format!("macro|{name}@example.com")
+ .try_into()
+ .expect("test user ids are valid")
+}
use rate_limit::outbound::redis::RedisRateLimitOps;
use std::{
collections::HashMap,
@@ -47,14 +54,15 @@ async fn a_users_budget_is_shared_across_replicas_and_recovers_after_one_second(
let counter = Counter::default();
let first_replica = limiter(counter.clone());
let second_replica = limiter(counter.clone());
- let (first, second) = tokio::join!(first_replica.check("alice"), second_replica.check("alice"));
+ let alice = person("alice");
+ let (first, second) = tokio::join!(first_replica.check(&alice), second_replica.check(&alice));
assert_eq!(usize::from(first.is_ok()) + usize::from(second.is_ok()), 1);
let denied = first.err().or_else(|| second.err()).unwrap();
assert_eq!(denied.current_context(), &LinkedError::RateLimited);
- second_replica.check("bob").await.unwrap();
+ second_replica.check(&person("bob")).await.unwrap();
assert_eq!(counter.windows.lock().unwrap().len(), 2);
counter.now.store(1, Ordering::Relaxed);
- second_replica.check("alice").await.unwrap();
+ second_replica.check(&person("alice")).await.unwrap();
}
struct Unavailable;
@@ -80,7 +88,11 @@ async fn unavailable_shared_counter_fails_closed() {
repo: rate_limit::RedisRateLimitAdapter { redis: Unavailable },
});
assert_eq!(
- limiter.check("alice").await.unwrap_err().current_context(),
+ limiter
+ .check(&person("alice"))
+ .await
+ .unwrap_err()
+ .current_context(),
&LinkedError::Unavailable
);
}
@@ -99,6 +111,7 @@ async fn redis_enforces_the_shared_budget_without_affecting_another_user() {
});
let alice = format!("whatsapp-rate-test-{}", uuid::Uuid::now_v7());
let bob = format!("whatsapp-rate-test-{}", uuid::Uuid::now_v7());
+ let (alice, bob) = (person(&alice), person(&bob));
let (one, two, other) = tokio::join!(
first.check(&alice),
second.check(&alice),
diff --git a/services/whatsapp_session_service/AGENTS.md b/services/whatsapp_session_service/AGENTS.md
index 28e93538e6..7aed63d053 100644
--- a/services/whatsapp_session_service/AGENTS.md
+++ b/services/whatsapp_session_service/AGENTS.md
@@ -22,8 +22,14 @@ current, ingests standalone `whatsapp_group` traffic through `whatsapp_linked`'s
- `domain/account.rs`: one account. `begin_lease` bumps `lease_epoch`; every
domain and store write is fenced by it, and `Fenced` stops the account.
Pairing an account that is not connected deletes the stored device first
- (fresh keys); `whatsapp_account_changed` to `disconnected` logs the device
- out at WhatsApp (the remote unlink DSS's disconnect promises).
+ (`PgWhatsAppStore::reset_device`, without unwrapping its key; fresh keys).
+ A device that can never be read again (KMS refused its data key, or it
+ doesn't decrypt: `SessionError::DeviceUnreadable`) is replaced once when
+ pairing, and without a pairing marks a connected account `logged_out`, so
+ the web asks its owner to reconnect. A KMS outage (`KmsUnavailable`) wipes
+ nothing: the account exits `Failed` and the next rescan retries.
+ `whatsapp_account_changed` to `disconnected` logs the device out at
+ WhatsApp (the remote unlink DSS's disconnect promises).
- `domain/inbound.rs`: durable inbound. The client's event handler (with
`synchronous_ack`) calls the `InboundGate`: drop unadopted groups, else
`enqueue_inbound` (one fenced insert), and only then is the node acked;
@@ -38,8 +44,13 @@ current, ingests standalone `whatsapp_group` traffic through `whatsapp_linked`'s
`SessionService` (`discoverable_accounts`, `fleet_health`).
- `outbound/signals.rs`: `LISTEN` for `whatsapp_{account_released,
pairing_requested, send_requested, groups_requested, account_changed}`.
- Payloads are `whatsapp_linked::outbound::pg::signals::Signal` JSON; each
- one's `traceparent` parents a `whatsapp.signal.receive` span.
+ Payloads are `whatsapp_linked::signals::Signal` JSON; each
+ one's `traceparent` parents a `whatsapp.signal.receive` span that travels
+ with the signal (`ports::Traced`): the supervisor's work and the runner's
+ `whatsapp.account.signal` span run inside it, and a runner started by it
+ links its `whatsapp.account.connect` span to it. By hand,
+ send JSON: `SELECT pg_notify('whatsapp_pairing_requested',
+ '{"id":"<pairing id>"}')`.
- Group rosters: the whole list is read on connect, on resync, and on
`whatsapp_groups_requested` (pages opening; at most once per
`groups_refresh_interval`, 30 s, per account). Live `JoinedGroup` /
@@ -80,9 +91,14 @@ current, ingests standalone `whatsapp_group` traffic through `whatsapp_linked`'s
`Client::parse_web_message`, ingested as history events through the inbound
gate, then reported as a `HistoryPage`. The runner's `backfill` asks the
phone for pages of added groups (`request_history`, plus `request_message`
- for an anchor that predates adoption), marks unanswered requests
+ for an anchor that predates adoption), marks a group with no anchor
+ `waiting_for_message` (an `update_chats` that gives it one returns true and
+ the runner imports at once), marks unanswered requests
`waiting_for_phone` after `backfill_timeout` and retries after
`backfill_retry` or on reconnect.
+- QR pairing: whatsmeow rotates codes (60 s, then 20 s each) and then
+ times out; that timeout ends the pairing as `expired`
+ (`SessionEvent::PairExpired`), not `failed`, so the web starts a new one.
- Passkey pairing: `PairPasskeyRequest` → `PairingUpdate::Passkey { challenge }`;
on `whatsapp_pairing_requested`, and on every tick in case the notify was
missed, the runner takes the owner's assertion (`take_passkey_response`)
@@ -110,7 +126,8 @@ current, ingests standalone `whatsapp_group` traffic through `whatsapp_linked`'s
Spans: `whatsapp.account.{lease,release,rescan,connect}`,
`whatsapp.inbound.ingest`, `whatsapp.media.import`, `whatsapp.send.dispatch`
(parented on the trace of the request that recorded the send),
-`whatsapp.groups.{refresh,event}`, `whatsapp.signal.receive`, `whatsapp.drain`,
+`whatsapp.groups.{refresh,event}`, `whatsapp.signal.receive`,
+`whatsapp.account.signal`, `whatsapp.drain`,
`whatsapp.history.{sync,page}`, `whatsapp.backfill.request`
(`whatsapp.inbound.ingest` records the message `kind`; `whatsapp.history.page`
counts what a page stored, could not parse and skipped, by stub type). Log events read by `infra/stacks/monitoring/monitors/
@@ -129,9 +146,13 @@ JIDs, phone numbers, QR codes or message text.
- **All accounts offline**: check the lock URL points at the instance endpoint,
replicas are not crash-looping on a lost lock connection, and capacity
(`accounts_running` vs `WHATSAPP_SESSION_MAX_ACCOUNTS` × replicas).
-- **KMS failure**: accounts exit `Failed` at open (`whatsapp.account.connect`
- outcome `failed`, error "KMS refused"); check the task role can use the key
- alias and the key is enabled. Nothing is lost; the next rescan retries.
+- **KMS failure**: an outage (throttled, unreachable) makes accounts exit
+ `Failed` at open (`whatsapp.account.connect` outcome `failed`); nothing is
+ lost and the next rescan retries. A refusal (key deleted or disabled, no
+ permission, a LocalStack that lost its key) is outcome
+ `device_unreadable`: connected accounts become `logged_out` and must pair
+ again, which replaces the device. Check the task role can use the key
+ alias and the key is enabled before people re-pair.
- **Unknown sends**: never resent automatically; a later echo with the same
message id settles them.
diff --git a/services/whatsapp_session_service/Cargo.toml b/services/whatsapp_session_service/Cargo.toml
index f610f4f373..e73c3667af 100644
--- a/services/whatsapp_session_service/Cargo.toml
+++ b/services/whatsapp_session_service/Cargo.toml
@@ -47,5 +47,6 @@ workspace-hack = { version = "0.1", path = "../../crates/workspace-hack" }
[dev-dependencies]
macro_db_migrator = { path = "../../crates/macro_db_migrator" }
sha2 = { workspace = true }
+tracing-subscriber = { workspace = true }
whatsapp_fake_server = { path = "../../crates/whatsapp_fake_server" }
whatsapp_store_pg = { path = "../../crates/whatsapp_store_pg", features = ["fake-kms"] }
diff --git a/services/whatsapp_session_service/src/domain/account.rs b/services/whatsapp_session_service/src/domain/account.rs
index a5f4e921e8..80b93906f3 100644
--- a/services/whatsapp_session_service/src/domain/account.rs
+++ b/services/whatsapp_session_service/src/domain/account.rs
@@ -23,7 +23,7 @@ use super::inbound::InboundGate;
use super::media::{MEDIA_LIMIT_BYTES, MediaImports, TRANSFERS_PER_ACCOUNT};
use super::ports::{
AccountControl, AccountExit, AccountRunner, AccountSignal, SendFailure, SessionConnector,
- SessionError, SessionEvent, UploadedMedia, WhatsAppSession,
+ SessionError, SessionEvent, Traced, UploadedMedia, WhatsAppSession,
};
#[cfg(test)]
@@ -151,9 +151,12 @@ impl<Connector: SessionConnector> AccountRunner for AccountSessions<Connector> {
account_id = %account,
lease_epoch = lease.scope.lease_epoch,
paired = tracing::field::Empty,
+ fresh_device = tracing::field::Empty,
pairing = pairing.is_some(),
outcome = tracing::field::Empty,
);
+ // Linked, not parented: the session outlives the signal that started it.
+ connect_span.follows_from(&control.cause);
let gate = Arc::new(InboundGate::new(self.sessions.clone(), lease.scope));
let opened = self
.open(&lease, pairing.as_ref(), Arc::clone(&gate))
@@ -165,6 +168,7 @@ impl<Connector: SessionConnector> AccountRunner for AccountSessions<Connector> {
Ok(Some(_)) => "connecting",
Ok(None) => "idle",
Err(AccountExit::Fenced) => "fenced",
+ Err(AccountExit::Idle) => "device_unreadable",
Err(_) => "failed",
},
);
@@ -178,7 +182,8 @@ impl<Connector: SessionConnector> AccountRunner for AccountSessions<Connector> {
let media_wake = Arc::new(Notify::new());
let (connected, connected_receiver) = watch::channel(false);
let media_stop = CancellationToken::new();
- let imports = tokio::spawn(
+ // Aborted if this runner is: the import loop never outlives it.
+ let imports = tokio_util::task::AbortOnDropHandle::new(tokio::spawn(
MediaImports {
sessions: self.sessions.clone(),
scope: lease.scope,
@@ -190,7 +195,7 @@ impl<Connector: SessionConnector> AccountRunner for AccountSessions<Connector> {
fenced: gate.fenced.clone(),
}
.run(media_stop.clone()),
- );
+ ));
let mut running = Running {
sessions: &self.sessions,
config: self.config,
@@ -203,13 +208,20 @@ impl<Connector: SessionConnector> AccountRunner for AccountSessions<Connector> {
pairing,
reconnecting: false,
groups_refreshed_at: None,
+ release: control.release.clone(),
+ stop: control.stop.clone(),
};
let exit = running.serve(events, control).await;
media_stop.cancel();
if exit == AccountExit::Stopped {
imports.abort();
}
- let _ = imports.await;
+ match imports.await {
+ Err(error) if error.is_panic() => {
+ tracing::error!(error = %error, "The WhatsApp attachment import loop panicked");
+ }
+ Ok(()) | Err(_) => {}
+ }
exit
}
}
@@ -219,6 +231,12 @@ impl<Connector: SessionConnector> AccountSessions<Connector> {
/// device has no pairing transaction to serve. Pairing an account that
/// is not connected starts from a fresh device: the old one was logged
/// out or disconnected and its keys are useless.
+ ///
+ /// A stored device that can never be read again (KMS lost its data key)
+ /// is replaced when pairing, once. Without a pairing, a connected account
+ /// with such a device is recorded as logged out, so its owner is asked to
+ /// reconnect. A KMS outage replaces nothing: the account fails, and the
+ /// next rescan tries again.
async fn open(
&self,
lease: &Lease,
@@ -226,15 +244,38 @@ impl<Connector: SessionConnector> AccountSessions<Connector> {
gate: Arc<InboundGate>,
) -> Result<Option<(Connector::Session, mpsc::UnboundedReceiver<SessionEvent>)>, AccountExit>
{
- let fresh_device = pairing.is_some() && lease.state != AccountState::Connected;
- let (session, events) = match self.connector.open(lease.scope, fresh_device, gate).await {
- Ok(opened) => opened,
- Err(SessionError::Fenced) => return Err(AccountExit::Fenced),
- Err(error) => {
- tracing::error!(error = %error, "Opening the WhatsApp device failed");
- return Err(AccountExit::Failed);
+ let mut fresh_device = pairing.is_some() && lease.state != AccountState::Connected;
+ let mut replaced = false;
+ let (session, events) = loop {
+ match self
+ .connector
+ .open(lease.scope, fresh_device, gate.clone())
+ .await
+ {
+ Ok(opened) => break opened,
+ Err(SessionError::Fenced) => return Err(AccountExit::Fenced),
+ Err(SessionError::DeviceUnreadable) if pairing.is_some() && !replaced => {
+ tracing::warn!(
+ fresh_device,
+ "The stored WhatsApp device cannot be read; pairing a fresh one"
+ );
+ fresh_device = true;
+ replaced = true;
+ }
+ Err(SessionError::DeviceUnreadable) if pairing.is_none() => {
+ tracing::error!(
+ "The stored WhatsApp device cannot be read; the owner must reconnect"
+ );
+ survive(self.sessions.logged_out(lease.scope).await, "logged_out")?;
+ return Err(AccountExit::Idle);
+ }
+ Err(error) => {
+ tracing::error!(error = %error, "Opening the WhatsApp device failed");
+ return Err(AccountExit::Failed);
+ }
}
};
+ tracing::Span::current().record("fresh_device", fresh_device);
let paired = session.identity_jid().await.is_some();
tracing::Span::current().record("paired", paired);
if !paired {
@@ -271,6 +312,9 @@ struct Running<'service, Session> {
reconnecting: bool,
/// When the group list was last read, for rate limiting requested refreshes.
groups_refreshed_at: Option<tokio::time::Instant>,
+ /// The runner's release and stop requests, checked between sends.
+ release: CancellationToken,
+ stop: CancellationToken,
}
impl<Session: WhatsAppSession> Running<'_, Session> {
@@ -354,13 +398,8 @@ impl<Session: WhatsAppSession> Running<'_, Session> {
let result = self.confirm_passkey(code).await;
self.exit_on(result)
}
- SessionEvent::PairFailed => {
- let result = self.update_pairing(PairingUpdate::Failed).await;
- match result {
- Ok(()) => Next::Exit(AccountExit::Idle),
- Err(exit) => Next::Exit(exit),
- }
- }
+ SessionEvent::PairExpired => self.end_pairing(PairingUpdate::Expired).await,
+ SessionEvent::PairFailed => self.end_pairing(PairingUpdate::Failed).await,
SessionEvent::Connected => {
if self.reconnecting {
tracing::info!(
@@ -393,11 +432,18 @@ impl<Session: WhatsAppSession> Running<'_, Session> {
Next::Exit(AccountExit::Failed)
}
SessionEvent::Chats(chats) => {
- let result = survive(
- self.sessions.update_chats(self.scope, &chats).await,
- "update_chats",
- )
- .map(|_| ());
+ let result = async {
+ let anchored = survive(
+ self.sessions.update_chats(self.scope, &chats).await,
+ "update_chats",
+ )?;
+ // A chat waiting for its first message got one: import now.
+ if anchored == Some(true) {
+ Box::pin(self.backfill(false)).await?;
+ }
+ Ok(())
+ }
+ .await;
self.exit_on(result)
}
SessionEvent::HistoryPage(page) => {
@@ -461,14 +507,26 @@ impl<Session: WhatsAppSession> Running<'_, Session> {
.await
}
- async fn on_signal(&mut self, signal: AccountSignal) -> Next {
- let result = match signal {
- AccountSignal::Pairing(pairing) => self.check_pairing(pairing).await,
- AccountSignal::Send => self.dispatch_sends().await,
- AccountSignal::Groups => self.requested_refresh().await,
- AccountSignal::Changed => self.account_changed().await,
- AccountSignal::Resync => self.resync().await,
- };
+ /// Handles a signal inside a child of the notification's span, so the
+ /// sender's trace continues into what it caused here.
+ async fn on_signal(&mut self, Traced { signal, span }: Traced<AccountSignal>) -> Next {
+ let handling = tracing::info_span!(
+ parent: &span,
+ "whatsapp.account.signal",
+ account_id = %self.scope.account_id,
+ signal = ?signal,
+ );
+ let result = async {
+ match signal {
+ AccountSignal::Pairing(pairing) => self.check_pairing(pairing).await,
+ AccountSignal::Send => self.dispatch_sends().await,
+ AccountSignal::Groups => self.requested_refresh().await,
+ AccountSignal::Changed => self.account_changed().await,
+ AccountSignal::Resync => self.resync().await,
+ }
+ }
+ .instrument(handling)
+ .await;
self.exit_on(result)
}
@@ -592,6 +650,14 @@ impl<Session: WhatsAppSession> Running<'_, Session> {
}
}
+ /// WhatsApp ended the pairing; the session goes idle until the next one.
+ async fn end_pairing(&mut self, update: PairingUpdate) -> Next {
+ match self.update_pairing(update).await {
+ Ok(()) => Next::Exit(AccountExit::Idle),
+ Err(exit) => Next::Exit(exit),
+ }
+ }
+
/// Hands the owner's passkey assertion to WhatsApp, once.
async fn forward_passkey(&mut self, pairing: Uuid) -> Result<(), AccountExit> {
let Some(Some(response)) = survive(
@@ -715,7 +781,15 @@ impl<Session: WhatsAppSession> Running<'_, Session> {
/// before the group was added and so was not kept).
async fn request_page(&mut self, group: &BackfillWork) -> Result<(), AccountExit> {
let Some(before) = group.cursor.as_ref().or(group.anchor.as_ref()) else {
- // No message seen in this chat yet: the first one starts it.
+ // No message known in this chat yet: the first one starts it.
+ if group.state != BackfillState::WaitingForMessage {
+ survive(
+ self.sessions
+ .backfill_waiting_for_message(self.scope, group.group_id)
+ .await,
+ "backfill_waiting_for_message",
+ )?;
+ }
return Ok(());
};
let span = tracing::info_span!(
@@ -843,6 +917,10 @@ impl<Session: WhatsAppSession> Running<'_, Session> {
return Ok(());
}
for send in &claimed {
+ // Claims not dispatched yet go back on release or takeover.
+ if self.release.is_cancelled() || self.stop.is_cancelled() {
+ return Ok(());
+ }
self.dispatch(send).await?;
}
}
@@ -886,7 +964,7 @@ impl<Session: WhatsAppSession> Running<'_, Session> {
outcome = tracing::field::Empty,
);
// The dispatch joins the trace of the request that recorded the send.
- whatsapp_linked::outbound::trace_context::adopt(&span, send.traceparent.as_deref());
+ whatsapp_linked::signals::trace_context::adopt(&span, send.traceparent.as_deref());
async {
let uploaded = self.upload(send).await?;
let message_id = self.session.new_message_id().await;
diff --git a/services/whatsapp_session_service/src/domain/account/test.rs b/services/whatsapp_session_service/src/domain/account/test.rs
index e3cd449d4d..17881e6808 100644
--- a/services/whatsapp_session_service/src/domain/account/test.rs
+++ b/services/whatsapp_session_service/src/domain/account/test.rs
@@ -22,7 +22,8 @@ use super::{AccountConfig, AccountSessions};
use crate::domain::inbound::InboundGate;
use crate::domain::ports::{
AccountControl, AccountExit, AccountRunner, AccountSignal, DownloadFailure, InboundSink,
- SendFailure, SessionConnector, SessionError, SessionEvent, UploadedMedia, WhatsAppSession,
+ SendFailure, SessionConnector, SessionError, SessionEvent, Traced, UploadedMedia,
+ WhatsAppSession,
};
const IDENTITY: &str = "[email protected]";
@@ -55,6 +56,14 @@ struct FakeWhatsApp {
identity: Arc<Mutex<Option<String>>>,
/// What reading one group returns.
group: Arc<Mutex<Option<GroupInfo>>>,
+ /// Failures the next opens return, in order, before opening succeeds.
+ open_failures: Arc<Mutex<Vec<OpenFailure>>>,
+}
+
+#[derive(Debug, Clone, Copy)]
+enum OpenFailure {
+ DeviceUnreadable,
+ KmsUnavailable,
}
struct FakeSession {
@@ -70,12 +79,21 @@ impl SessionConnector for FakeWhatsApp {
fresh_device: bool,
inbound: Arc<dyn InboundSink>,
) -> Result<(FakeSession, mpsc::UnboundedReceiver<SessionEvent>), SessionError> {
- let (sender, receiver) = mpsc::unbounded_channel();
- *self.events.lock().unwrap() = Some(sender);
- *self.inbound.lock().unwrap() = Some(inbound);
self.calls
.send(Call::Open(scope.lease_epoch, fresh_device))
.unwrap();
+ let failure = {
+ let mut failures = self.open_failures.lock().unwrap();
+ (!failures.is_empty()).then(|| failures.remove(0))
+ };
+ match failure {
+ Some(OpenFailure::DeviceUnreadable) => return Err(SessionError::DeviceUnreadable),
+ Some(OpenFailure::KmsUnavailable) => return Err(SessionError::KmsUnavailable),
+ None => {}
+ }
+ let (sender, receiver) = mpsc::unbounded_channel();
+ *self.events.lock().unwrap() = Some(sender);
+ *self.inbound.lock().unwrap() = Some(inbound);
Ok((
FakeSession {
whatsapp: self.clone(),
@@ -284,6 +302,7 @@ fn runner_with(
inbound: Arc::default(),
identity: Arc::default(),
group: Arc::default(),
+ open_failures: Arc::default(),
};
let runner = Arc::new(AccountSessions::new(
SessionService::new(Arc::new(PgLinkedRepository::new(pool.clone()))),
@@ -301,7 +320,7 @@ fn runner_with(
}
struct Started {
- signals: mpsc::Sender<AccountSignal>,
+ signals: mpsc::Sender<Traced<AccountSignal>>,
release: CancellationToken,
running: tokio::task::JoinHandle<AccountExit>,
}
@@ -311,6 +330,7 @@ fn start(runner: &Arc<AccountSessions<FakeWhatsApp>>, account: Uuid) -> Started
let release = CancellationToken::new();
let control = AccountControl {
signals: signal_receiver,
+ cause: tracing::Span::none(),
release: release.clone(),
stop: CancellationToken::new(),
};
@@ -380,6 +400,43 @@ async fn pairing_records_the_qr_and_identity_then_refreshes_groups(pool: PgPool)
assert_eq!(roster, vec![GROUP.to_owned()]);
}
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn running_out_of_qr_codes_expires_the_pairing_instead_of_failing_it(pool: PgPool) {
+ let (account, pairing) = insert_pairing_account(&pool).await;
+ let (runner, whatsapp, mut calls) = runner(&pool);
+ let started = start(&runner, account);
+ assert_eq!(calls.recv().await, Some(Call::Open(1, true)));
+ assert_eq!(calls.recv().await, Some(Call::StartPairing));
+ assert_eq!(calls.recv().await, Some(Call::Connect));
+
+ let events = event_sender(&whatsapp);
+ events.send(SessionEvent::Qr("qr-1".to_owned())).unwrap();
+ events.send(SessionEvent::PairExpired).unwrap();
+ assert_eq!(started.running.await.unwrap(), AccountExit::Idle);
+
+ let ended = sqlx::query!(
+ "SELECT state, consumed_at IS NOT NULL AS \"consumed!\", qr_code FROM whatsapp_pairing WHERE id = $1",
+ pairing
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ assert_eq!(
+ ended.state, "expired",
+ "the web rolls an expired code on its own"
+ );
+ assert!(ended.consumed);
+ assert_eq!(ended.qr_code, None);
+ let state = sqlx::query_scalar!(
+ "SELECT state FROM whatsapp_linked_account WHERE id = $1",
+ account
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ assert_eq!(state, "disconnected");
+}
+
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn a_replica_whose_epoch_was_taken_over_cannot_write_and_stops(pool: PgPool) {
let (account, pairing) = insert_pairing_account(&pool).await;
@@ -445,7 +502,11 @@ async fn an_owner_who_disconnects_gets_the_device_unlinked(pool: PgPool) {
.execute(&pool)
.await
.unwrap();
- started.signals.send(AccountSignal::Changed).await.unwrap();
+ started
+ .signals
+ .send(AccountSignal::Changed.into())
+ .await
+ .unwrap();
assert_eq!(calls.recv().await, Some(Call::Logout));
assert_eq!(started.running.await.unwrap(), AccountExit::Idle);
@@ -494,7 +555,7 @@ async fn passkey_pairing_shows_the_challenge_forwards_the_assertion_once_and_con
.unwrap();
started
.signals
- .send(AccountSignal::Pairing(pairing))
+ .send(AccountSignal::Pairing(pairing).into())
.await
.unwrap();
assert_eq!(calls.recv().await, Some(Call::PasskeyResponse(assertion)));
@@ -658,8 +719,16 @@ async fn requested_group_refreshes_are_rate_limited_per_account(pool: PgPool) {
let (_, _, mut calls, started) = connected(&pool, Duration::from_secs(3600)).await;
// Opening the page right after connecting does not read the groups again;
// a resync (missed notifications) always does. Signals run in order.
- started.signals.send(AccountSignal::Groups).await.unwrap();
- started.signals.send(AccountSignal::Resync).await.unwrap();
+ started
+ .signals
+ .send(AccountSignal::Groups.into())
+ .await
+ .unwrap();
+ started
+ .signals
+ .send(AccountSignal::Resync.into())
+ .await
+ .unwrap();
assert_eq!(calls.recv().await, Some(Call::JoinedGroups));
started.release.cancel();
assert_eq!(started.running.await.unwrap(), AccountExit::Released);
@@ -673,7 +742,11 @@ async fn requested_group_refreshes_are_rate_limited_per_account(pool: PgPool) {
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn requested_group_refreshes_run_once_the_interval_passed(pool: PgPool) {
let (_, _, mut calls, started) = connected(&pool, Duration::ZERO).await;
- started.signals.send(AccountSignal::Groups).await.unwrap();
+ started
+ .signals
+ .send(AccountSignal::Groups.into())
+ .await
+ .unwrap();
assert_eq!(calls.recv().await, Some(Call::JoinedGroups));
started.release.cancel();
assert_eq!(started.running.await.unwrap(), AccountExit::Released);
@@ -686,7 +759,7 @@ async fn live_group_events_update_the_one_group(pool: PgPool) {
.await
.unwrap();
listener
- .listen(whatsapp_linked::outbound::pg::signals::CHANGED)
+ .listen(whatsapp_linked::signals::CHANGED)
.await
.unwrap();
let (account, whatsapp, mut calls, started) = connected(&pool, Duration::from_secs(3600)).await;
@@ -746,3 +819,113 @@ async fn live_group_events_update_the_one_group(pool: PgPool) {
started.release.cancel();
assert_eq!(started.running.await.unwrap(), AccountExit::Released);
}
+
+/// Marks the account connected; `pairing` keeps its pairing transaction live
+/// (the owner asked to pair again).
+async fn make_connected(pool: &PgPool, account: Uuid, pairing: bool) {
+ sqlx::query!(
+ "UPDATE whatsapp_linked_account SET state = 'connected', identity_jid = $2 WHERE id = $1",
+ account,
+ IDENTITY,
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+ if !pairing {
+ sqlx::query!(
+ "UPDATE whatsapp_pairing SET state = 'success', consumed_at = now() WHERE account_id = $1",
+ account
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+ }
+}
+
+async fn account_state(pool: &PgPool, account: Uuid) -> String {
+ sqlx::query_scalar!(
+ "SELECT state FROM whatsapp_linked_account WHERE id = $1",
+ account
+ )
+ .fetch_one(pool)
+ .await
+ .unwrap()
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn pairing_replaces_a_device_kms_can_no_longer_read_once(pool: PgPool) {
+ let (account, _pairing) = insert_pairing_account(&pool).await;
+ make_connected(&pool, account, true).await;
+ let (runner, whatsapp, mut calls) = runner(&pool);
+ whatsapp
+ .open_failures
+ .lock()
+ .unwrap()
+ .push(OpenFailure::DeviceUnreadable);
+ let started = start(&runner, account);
+ // Connected, so the device is kept at first; it can't be read, so the
+ // pairing starts from a fresh one instead of failing forever.
+ assert_eq!(calls.recv().await, Some(Call::Open(1, false)));
+ assert_eq!(calls.recv().await, Some(Call::Open(1, true)));
+ assert_eq!(calls.recv().await, Some(Call::StartPairing));
+ assert_eq!(calls.recv().await, Some(Call::Connect));
+ started.release.cancel();
+ assert_eq!(started.running.await.unwrap(), AccountExit::Released);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn pairing_gives_up_when_even_a_fresh_device_cannot_be_opened(pool: PgPool) {
+ let (account, _pairing) = insert_pairing_account(&pool).await;
+ let (runner, whatsapp, mut calls) = runner(&pool);
+ whatsapp
+ .open_failures
+ .lock()
+ .unwrap()
+ .extend([OpenFailure::DeviceUnreadable; 3]);
+ let started = start(&runner, account);
+ assert_eq!(calls.recv().await, Some(Call::Open(1, true)));
+ assert_eq!(calls.recv().await, Some(Call::Open(1, true)));
+ assert_eq!(started.running.await.unwrap(), AccountExit::Failed);
+ assert!(calls.try_recv().is_err(), "replaced once, not in a loop");
+ assert_eq!(account_state(&pool, account).await, "pairing");
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_connected_account_whose_device_cannot_be_read_is_asked_to_reconnect(pool: PgPool) {
+ let (account, _pairing) = insert_pairing_account(&pool).await;
+ make_connected(&pool, account, false).await;
+ let (runner, whatsapp, mut calls) = runner(&pool);
+ whatsapp
+ .open_failures
+ .lock()
+ .unwrap()
+ .push(OpenFailure::DeviceUnreadable);
+ let started = start(&runner, account);
+ assert_eq!(calls.recv().await, Some(Call::Open(1, false)));
+ assert_eq!(started.running.await.unwrap(), AccountExit::Idle);
+ assert!(
+ calls.try_recv().is_err(),
+ "nothing is replaced without a pairing"
+ );
+ assert_eq!(account_state(&pool, account).await, "logged_out");
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_kms_outage_leaves_a_connected_account_and_its_device_alone(pool: PgPool) {
+ let (account, _pairing) = insert_pairing_account(&pool).await;
+ make_connected(&pool, account, false).await;
+ let (runner, whatsapp, mut calls) = runner(&pool);
+ whatsapp
+ .open_failures
+ .lock()
+ .unwrap()
+ .push(OpenFailure::KmsUnavailable);
+ let started = start(&runner, account);
+ assert_eq!(calls.recv().await, Some(Call::Open(1, false)));
+ assert_eq!(started.running.await.unwrap(), AccountExit::Failed);
+ assert!(
+ calls.try_recv().is_err(),
+ "no fresh device on a transient failure"
+ );
+ assert_eq!(account_state(&pool, account).await, "connected");
+}
diff --git a/services/whatsapp_session_service/src/domain/ports.rs b/services/whatsapp_session_service/src/domain/ports.rs
index 04560a7747..a948c10ea5 100644
--- a/services/whatsapp_session_service/src/domain/ports.rs
+++ b/services/whatsapp_session_service/src/domain/ports.rs
@@ -86,10 +86,33 @@ pub enum AccountSignal {
Resync,
}
+/// A signal and the span of the notification it came from, so the work it
+/// causes continues the sender's trace. Signals without one (rescans,
+/// resyncs) carry [`tracing::Span::none`].
+#[derive(Debug, Clone)]
+pub struct Traced<SignalKind> {
+ /// The signal.
+ pub signal: SignalKind,
+ /// `whatsapp.signal.receive` of the notification, or none.
+ pub span: tracing::Span,
+}
+
+impl<SignalKind> From<SignalKind> for Traced<SignalKind> {
+ fn from(signal: SignalKind) -> Self {
+ Traced {
+ signal,
+ span: tracing::Span::none(),
+ }
+ }
+}
+
/// What a runner receives for its account.
pub struct AccountControl {
/// Signals for this account, coalesced when the runner is busy.
- pub signals: mpsc::Receiver<AccountSignal>,
+ pub signals: mpsc::Receiver<Traced<AccountSignal>>,
+ /// The span that started the runner (a notification, a rescan); the
+ /// account's connect span links to it.
+ pub cause: tracing::Span,
/// Graceful release (drain): stop taking sends, wait for in-flight
/// acknowledgements, disconnect, then return [`AccountExit::Released`].
pub release: CancellationToken,
@@ -135,7 +158,9 @@ pub enum SessionEvent {
/// Verified phone-number JID of the linked account.
identity_jid: String,
},
- /// Pairing failed or timed out.
+ /// WhatsApp's QR codes ran out before one was scanned.
+ PairExpired,
+ /// Pairing failed.
PairFailed,
/// WhatsApp asked for a passkey assertion; `challenge` is the WebAuthn
/// request options to show the owner.
@@ -191,9 +216,14 @@ pub enum SessionError {
/// Another replica took the account over.
#[error("the account lease moved to another replica")]
Fenced,
- /// KMS refused to unwrap or generate the account's data key.
- #[error("KMS refused the account's data key")]
- Kms,
+ /// KMS could not be reached right now; opening again later can succeed.
+ #[error("KMS is unavailable for the account's data key")]
+ KmsUnavailable,
+ /// The stored device can never be read again (KMS refused its data key,
+ /// or it does not decrypt). Only a fresh device, and so a new pairing,
+ /// helps.
+ #[error("the account's stored WhatsApp device cannot be read")]
+ DeviceUnreadable,
/// Any other failure.
#[error("WhatsApp session failed: {0}")]
Internal(rootcause::Report),
diff --git a/services/whatsapp_session_service/src/domain/supervisor.rs b/services/whatsapp_session_service/src/domain/supervisor.rs
index 3e960ce238..668f4f796b 100644
--- a/services/whatsapp_session_service/src/domain/supervisor.rs
+++ b/services/whatsapp_session_service/src/domain/supervisor.rs
@@ -6,14 +6,14 @@ use std::sync::Arc;
use std::time::Duration;
use tokio::sync::mpsc;
-use tokio::task::{Id, JoinError, JoinSet};
+use tokio::task::{AbortHandle, Id, JoinError, JoinSet};
use tokio_util::sync::CancellationToken;
use tracing::Instrument;
use uuid::Uuid;
use super::ports::{
AccountControl, AccountDirectory, AccountExit, AccountLocks, AccountRunner, AccountSignal,
- LeaseError,
+ LeaseError, Traced,
};
#[cfg(test)]
@@ -71,9 +71,11 @@ pub enum SupervisorError {
const ACCOUNT_SIGNAL_CAPACITY: usize = 8;
struct Running {
- signals: mpsc::Sender<AccountSignal>,
+ signals: mpsc::Sender<Traced<AccountSignal>>,
release: CancellationToken,
stop: CancellationToken,
+ /// Ends the runner's task when it ignores `stop` for `stop_timeout`.
+ abort: AbortHandle,
}
/// Runs the accounts this replica holds locks for.
@@ -115,7 +117,7 @@ where
/// are lost (then stops every account and returns the error).
pub async fn run(
mut self,
- signals: &mut mpsc::Receiver<Signal>,
+ signals: &mut mpsc::Receiver<Traced<Signal>>,
shutdown: CancellationToken,
) -> Result<(), SupervisorError> {
let lost = self.locks.lost();
@@ -134,7 +136,10 @@ where
self.finished(joined, false).await
}
signal = signals.recv() => match signal {
- Some(signal) => self.handle(signal).await,
+ // The work a notification causes joins the sender's trace.
+ Some(Traced { signal, span }) => {
+ self.handle(signal, &span).instrument(span.clone()).await
+ }
None => {
self.stop_all().await;
return Err(SupervisorError::SignalsClosed);
@@ -156,13 +161,13 @@ where
}
}
- async fn handle(&mut self, signal: Signal) -> Result<(), LeaseError> {
+ async fn handle(&mut self, signal: Signal, span: &tracing::Span) -> Result<(), LeaseError> {
match signal {
Signal::AccountReleased(account) => self.take(account).await,
Signal::PairingRequested(pairing) => {
match self.directory.pairing_account(pairing).await? {
Some(account) if self.accounts.contains_key(&account) => {
- self.forward(account, AccountSignal::Pairing(pairing));
+ self.forward(account, AccountSignal::Pairing(pairing), span);
Ok(())
}
Some(account) => self.take(account).await,
@@ -170,31 +175,34 @@ where
}
}
Signal::SendRequested(account) => {
- self.forward(account, AccountSignal::Send);
+ self.forward(account, AccountSignal::Send, span);
Ok(())
}
Signal::GroupsRequested(account) => {
- self.forward(account, AccountSignal::Groups);
+ self.forward(account, AccountSignal::Groups, span);
Ok(())
}
Signal::AccountChanged(account) if self.accounts.contains_key(&account) => {
- self.forward(account, AccountSignal::Changed);
+ self.forward(account, AccountSignal::Changed, span);
Ok(())
}
Signal::AccountChanged(account) => self.take(account).await,
Signal::Resync => {
for running in self.accounts.values() {
- let _ = running.signals.try_send(AccountSignal::Resync);
+ let _ = running.signals.try_send(AccountSignal::Resync.into());
}
self.rescan().await
}
}
}
- fn forward(&self, account: Uuid, signal: AccountSignal) {
+ fn forward(&self, account: Uuid, signal: AccountSignal, span: &tracing::Span) {
if let Some(running) = self.accounts.get(&account) {
// Full means the runner already has work queued; see the capacity.
- let _ = running.signals.try_send(signal);
+ let _ = running.signals.try_send(Traced {
+ signal,
+ span: span.clone(),
+ });
}
}
@@ -231,20 +239,22 @@ where
let stop = self.locks.lost().child_token();
let control = AccountControl {
signals: receiver,
+ cause: tracing::Span::current(),
release: release.clone(),
stop: stop.clone(),
};
let runner = Arc::clone(&self.runner);
- let task = self
+ let abort = self
.tasks
.spawn(async move { runner.run(account, control).await });
- self.task_accounts.insert(task.id(), account);
+ self.task_accounts.insert(abort.id(), account);
self.accounts.insert(
account,
Running {
signals: sender,
release,
stop,
+ abort,
},
);
}
@@ -258,6 +268,9 @@ where
) -> Result<(), LeaseError> {
let (id, exit) = match joined {
Ok((id, exit)) => (id, exit),
+ // Aborted by the drain after ignoring `stop`: it still needs a
+ // session, so it is announced like any stopped account.
+ Err(error) if error.is_cancelled() && draining => (error.id(), AccountExit::Stopped),
Err(error) => {
tracing::error!(error = %error, "WhatsApp account task panicked");
(error.id(), AccountExit::Failed)
@@ -321,7 +334,9 @@ where
/// Hands every account over in batches, so other replicas take them while
/// the rest keep running. Accounts still running at `drain_deadline` are
- /// stopped together, so the whole drain fits the platform's stop timeout.
+ /// stopped together, and a stopped account that has not returned within
+ /// `stop_timeout` is aborted, so the whole drain fits the platform's stop
+ /// timeout.
async fn drain(mut self) -> Result<(), SupervisorError> {
let started = tokio::time::Instant::now();
let drain_end = started + self.config.drain_deadline;
@@ -359,11 +374,12 @@ where
}
}
}
- let deadline = tokio::time::sleep_until(
- (tokio::time::Instant::now() + self.config.release_timeout).min(drain_end),
- );
- tokio::pin!(deadline);
- let mut stopped = past_deadline;
+ let release_end =
+ (tokio::time::Instant::now() + self.config.release_timeout).min(drain_end);
+ // Set once the batch is stopped: when to abort what is still running.
+ let mut abort_at =
+ past_deadline.then(|| tokio::time::Instant::now() + self.config.stop_timeout);
+ let mut aborted = false;
while !pending.is_empty() {
let step = tokio::select! {
biased;
@@ -383,8 +399,8 @@ where
}
result
}
- () = &mut deadline, if !stopped => {
- stopped = true;
+ () = tokio::time::sleep_until(release_end), if abort_at.is_none() => {
+ abort_at = Some(tokio::time::Instant::now() + self.config.stop_timeout);
timed_out += pending.len() as u32;
for account in &pending {
if let Some(running) = self.accounts.get(account) {
@@ -393,6 +409,22 @@ where
}
Ok(())
}
+ () = tokio::time::sleep_until(abort_at.unwrap_or(release_end)),
+ if abort_at.is_some() && !aborted =>
+ {
+ aborted = true;
+ tracing::error!(
+ parent: &span,
+ count = pending.len(),
+ "WhatsApp accounts did not stop in time; aborting them"
+ );
+ for account in &pending {
+ if let Some(running) = self.accounts.get(account) {
+ running.abort.abort();
+ }
+ }
+ Ok(())
+ }
};
match step {
Ok(()) => {}
diff --git a/services/whatsapp_session_service/src/domain/supervisor/test.rs b/services/whatsapp_session_service/src/domain/supervisor/test.rs
index ac0f4fc0ba..55e8c45774 100644
--- a/services/whatsapp_session_service/src/domain/supervisor/test.rs
+++ b/services/whatsapp_session_service/src/domain/supervisor/test.rs
@@ -9,7 +9,7 @@ use uuid::Uuid;
use super::{Signal, Supervisor, SupervisorConfig, SupervisorError};
use crate::domain::ports::{
AccountControl, AccountDirectory, AccountExit, AccountLocks, AccountRunner, AccountSignal,
- FleetHealth, LeaseError,
+ FleetHealth, LeaseError, Traced,
};
/// Locks shared by every fake replica, like advisory locks on one server.
@@ -75,10 +75,12 @@ enum RunnerEvent {
}
/// Runs until released or stopped. With `ignore_release`, only a stop ends
-/// it, like an account whose in-flight send never gets an acknowledgement.
+/// it, like an account whose in-flight send never gets an acknowledgement;
+/// with `ignore_stop` too, nothing does, like a runner stuck in a send.
struct FakeRunner {
events: mpsc::UnboundedSender<RunnerEvent>,
ignore_release: bool,
+ ignore_stop: bool,
}
impl AccountRunner for FakeRunner {
@@ -86,7 +88,7 @@ impl AccountRunner for FakeRunner {
self.events.send(RunnerEvent::Started(account)).unwrap();
loop {
tokio::select! {
- () = control.stop.cancelled() => {
+ () = control.stop.cancelled(), if !self.ignore_stop => {
self.events.send(RunnerEvent::Stopped(account)).unwrap();
return AccountExit::Stopped;
}
@@ -95,7 +97,7 @@ impl AccountRunner for FakeRunner {
return AccountExit::Released;
}
Some(signal) = control.signals.recv() => {
- self.events.send(RunnerEvent::Signal(account, signal)).unwrap();
+ self.events.send(RunnerEvent::Signal(account, signal.signal)).unwrap();
}
}
}
@@ -129,6 +131,7 @@ async fn takes_free_accounts_up_to_its_cap_and_forwards_their_signals() {
Arc::new(FakeRunner {
events,
ignore_release: false,
+ ignore_stop: false,
}),
CONFIG,
);
@@ -145,9 +148,18 @@ async fn takes_free_accounts_up_to_its_cap_and_forwards_their_signals() {
runner_events.recv().await,
Some(RunnerEvent::Started(second))
);
- signals.send(Signal::SendRequested(second)).await.unwrap();
- signals.send(Signal::SendRequested(third)).await.unwrap();
- signals.send(Signal::GroupsRequested(first)).await.unwrap();
+ signals
+ .send(Signal::SendRequested(second).into())
+ .await
+ .unwrap();
+ signals
+ .send(Signal::SendRequested(third).into())
+ .await
+ .unwrap();
+ signals
+ .send(Signal::GroupsRequested(first).into())
+ .await
+ .unwrap();
assert_eq!(
runner_events.recv().await,
Some(RunnerEvent::Signal(second, AccountSignal::Send))
@@ -166,6 +178,71 @@ async fn takes_free_accounts_up_to_its_cap_and_forwards_their_signals() {
running.await.unwrap().unwrap();
}
+/// Reports that it started, then each signal with the id of the span it
+/// arrived in.
+struct SpanRunner {
+ started: mpsc::UnboundedSender<Uuid>,
+ signals: mpsc::UnboundedSender<(AccountSignal, Option<tracing::span::Id>)>,
+}
+
+impl AccountRunner for SpanRunner {
+ async fn run(&self, account: Uuid, mut control: AccountControl) -> AccountExit {
+ self.started.send(account).unwrap();
+ loop {
+ tokio::select! {
+ () = control.stop.cancelled() => return AccountExit::Stopped,
+ () = control.release.cancelled() => return AccountExit::Released,
+ Some(Traced { signal, span }) = control.signals.recv() => {
+ self.signals.send((signal, span.id())).unwrap();
+ }
+ }
+ }
+ }
+}
+
+#[tokio::test(start_paused = true)]
+async fn a_forwarded_signal_carries_the_span_of_its_notification() {
+ let _subscriber = tracing::subscriber::set_default(tracing_subscriber::registry());
+ let account = Uuid::from_u128(1);
+ let (announced, _announcements) = mpsc::unbounded_channel();
+ let (reported, mut received) = mpsc::unbounded_channel();
+ let (started, mut starts) = mpsc::unbounded_channel();
+ let supervisor = Supervisor::new(
+ FakeLocks::default(),
+ FakeDirectory {
+ candidates: vec![account],
+ announced,
+ },
+ Arc::new(SpanRunner {
+ started,
+ signals: reported,
+ }),
+ CONFIG,
+ );
+ let (signals, mut receiver) = mpsc::channel(8);
+ let shutdown = CancellationToken::new();
+ let stop = shutdown.clone();
+ let running = tokio::spawn(async move { supervisor.run(&mut receiver, stop).await });
+ assert_eq!(starts.recv().await, Some(account));
+
+ let notification = tracing::info_span!("whatsapp.signal.receive");
+ signals
+ .send(Traced {
+ signal: Signal::SendRequested(account),
+ span: notification.clone(),
+ })
+ .await
+ .unwrap();
+
+ assert_eq!(
+ received.recv().await,
+ Some((AccountSignal::Send, notification.id()))
+ );
+ assert!(notification.id().is_some());
+ shutdown.cancel();
+ running.await.unwrap().unwrap();
+}
+
#[tokio::test(start_paused = true)]
async fn drain_releases_every_account_then_unlocks_and_announces_it() {
let first = Uuid::from_u128(1);
@@ -182,6 +259,7 @@ async fn drain_releases_every_account_then_unlocks_and_announces_it() {
Arc::new(FakeRunner {
events,
ignore_release: false,
+ ignore_stop: false,
}),
CONFIG,
);
@@ -231,6 +309,7 @@ async fn drain_stops_an_account_that_does_not_release_in_time_and_still_announce
Arc::new(FakeRunner {
events,
ignore_release: true,
+ ignore_stop: false,
}),
CONFIG,
);
@@ -254,6 +333,46 @@ async fn drain_stops_an_account_that_does_not_release_in_time_and_still_announce
assert!(locks.held.lock().unwrap().is_empty());
}
+#[tokio::test(start_paused = true)]
+async fn drain_aborts_an_account_that_ignores_its_stop_and_still_announces_it() {
+ let account = Uuid::from_u128(1);
+ let locks = FakeLocks::default();
+ let (announced, mut announcements) = mpsc::unbounded_channel();
+ let (events, mut runner_events) = mpsc::unbounded_channel();
+ let supervisor = Supervisor::new(
+ locks.clone(),
+ FakeDirectory {
+ candidates: vec![account],
+ announced,
+ },
+ Arc::new(FakeRunner {
+ events,
+ ignore_release: true,
+ ignore_stop: true,
+ }),
+ CONFIG,
+ );
+ let (_signals, mut receiver) = mpsc::channel(8);
+ let shutdown = CancellationToken::new();
+ let stop = shutdown.clone();
+ let running = tokio::spawn(async move { supervisor.run(&mut receiver, stop).await });
+ assert_eq!(
+ runner_events.recv().await,
+ Some(RunnerEvent::Started(account))
+ );
+
+ let started = tokio::time::Instant::now();
+ shutdown.cancel();
+ running.await.unwrap().unwrap();
+
+ assert_eq!(
+ started.elapsed(),
+ CONFIG.release_timeout + CONFIG.stop_timeout
+ );
+ assert_eq!(announcements.recv().await, Some(account));
+ assert!(locks.held.lock().unwrap().is_empty());
+}
+
#[tokio::test(start_paused = true)]
async fn losing_the_locks_stops_every_account_without_unlocking_or_announcing() {
let first = Uuid::from_u128(1);
@@ -270,6 +389,7 @@ async fn losing_the_locks_stops_every_account_without_unlocking_or_announcing()
Arc::new(FakeRunner {
events,
ignore_release: false,
+ ignore_stop: false,
}),
CONFIG,
);
diff --git a/services/whatsapp_session_service/src/outbound/lease.rs b/services/whatsapp_session_service/src/outbound/lease.rs
index d9c9938898..6eac93091c 100644
--- a/services/whatsapp_session_service/src/outbound/lease.rs
+++ b/services/whatsapp_session_service/src/outbound/lease.rs
@@ -10,7 +10,7 @@
use std::time::Duration;
-use sqlx::postgres::{PgConnectOptions, PgPool};
+use sqlx::postgres::PgConnectOptions;
use sqlx::{ConnectOptions, Connection, PgConnection};
use tokio::sync::{mpsc, oneshot};
use tokio_util::sync::CancellationToken;
@@ -21,7 +21,6 @@ use whatsapp_linked::domain::models::LinkedError;
use whatsapp_linked::domain::session::SessionService;
use crate::domain::ports::{AccountDirectory, AccountLocks, FleetHealth, LeaseError};
-use whatsapp_linked::outbound::pg::signals::{ACCOUNT_RELEASED, Signal};
#[cfg(test)]
mod test;
@@ -205,18 +204,16 @@ impl AccountLocks for PgAccountLocks {
}
}
-/// Discovery through the linked-devices domain, and release announcements
-/// (the service's own `NOTIFY` channel) over the shared pool.
+/// Discovery and release announcements through the linked-devices domain.
#[derive(Clone)]
pub struct PgAccountDirectory {
- pool: PgPool,
sessions: SessionService,
}
impl PgAccountDirectory {
- /// Wraps the shared pool and the domain service.
- pub fn new(pool: PgPool, sessions: SessionService) -> Self {
- PgAccountDirectory { pool, sessions }
+ /// Wraps the domain service.
+ pub fn new(sessions: SessionService) -> Self {
+ PgAccountDirectory { sessions }
}
}
@@ -242,15 +239,10 @@ impl AccountDirectory for PgAccountDirectory {
}
async fn announce_released(&self, account: Uuid) -> Result<(), LeaseError> {
- let payload = serde_json::to_string(&Signal {
- id: account,
- traceparent: whatsapp_linked::outbound::trace_context::current(),
- })
- .map_err(|error| LeaseError::Internal(rootcause::Report::new(error).into_dynamic()))?;
- sqlx::query!("SELECT pg_notify($1, $2)", ACCOUNT_RELEASED, payload)
- .execute(&self.pool)
- .await?;
- Ok(())
+ self.sessions
+ .announce_released(account)
+ .await
+ .map_err(domain_error)
}
async fn health(&self) -> Result<FleetHealth, LeaseError> {
diff --git a/services/whatsapp_session_service/src/outbound/lease/test.rs b/services/whatsapp_session_service/src/outbound/lease/test.rs
index ed9c9b72eb..53383fd787 100644
--- a/services/whatsapp_session_service/src/outbound/lease/test.rs
+++ b/services/whatsapp_session_service/src/outbound/lease/test.rs
@@ -70,10 +70,9 @@ async fn only_one_replica_locks_an_account_and_discovery_skips_it(
let second = PgAccountLocks::connect(&options, KEEPALIVE, &tracker)
.await
.unwrap();
- let directory = PgAccountDirectory::new(
- pool.clone(),
- SessionService::new(Arc::new(PgLinkedRepository::new(pool.clone()))),
- );
+ let directory = PgAccountDirectory::new(SessionService::new(Arc::new(
+ PgLinkedRepository::new(pool.clone()),
+ )));
sqlx::query!(
r#"INSERT INTO whatsapp_pairing (id, account_id, user_id, generation, state, expires_at)
@@ -175,10 +174,9 @@ async fn start_replica(
let (started_sender, started) = mpsc::unbounded_channel();
let supervisor = Supervisor::new(
locks,
- PgAccountDirectory::new(
+ PgAccountDirectory::new(SessionService::new(Arc::new(PgLinkedRepository::new(
pool.clone(),
- SessionService::new(Arc::new(PgLinkedRepository::new(pool.clone()))),
- ),
+ )))),
Arc::new(ReportingRunner {
started: started_sender,
}),
diff --git a/services/whatsapp_session_service/src/outbound/signals.rs b/services/whatsapp_session_service/src/outbound/signals.rs
index 12e21eb774..57566c7589 100644
--- a/services/whatsapp_session_service/src/outbound/signals.rs
+++ b/services/whatsapp_session_service/src/outbound/signals.rs
@@ -7,18 +7,19 @@
//! so it emits [`Signal::Resync`] and the supervisor re-reads everything.
//!
//! Payloads are `whatsapp_linked`'s JSON signals; each one's `traceparent`
-//! parents a `whatsapp.signal.receive` span, so the sender's trace continues
-//! here.
+//! parents a `whatsapp.signal.receive` span that travels with the signal, so
+//! the supervisor's and the runner's work continues the sender's trace.
use sqlx::postgres::{PgConnectOptions, PgListener, PgPoolOptions};
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
-use whatsapp_linked::outbound::pg::signals::{
+use whatsapp_linked::signals::{
ACCOUNT_CHANGED, ACCOUNT_RELEASED, GROUPS_REQUESTED, PAIRING_REQUESTED, SEND_REQUESTED,
+ trace_context,
};
-use whatsapp_linked::outbound::trace_context;
+use crate::domain::ports::Traced;
use crate::domain::supervisor::Signal;
const CHANNELS: [&str; 5] = [
@@ -58,7 +59,7 @@ impl SignalListener {
}
/// Forwards notifications until `stop` or until the supervisor goes away.
- pub async fn run(mut self, signals: mpsc::Sender<Signal>, stop: CancellationToken) {
+ pub async fn run(mut self, signals: mpsc::Sender<Traced<Signal>>, stop: CancellationToken) {
loop {
let received = tokio::select! {
() = stop.cancelled() => return,
@@ -74,8 +75,9 @@ impl SignalListener {
signal = ?signal,
);
trace_context::adopt(&span, traceparent.as_deref());
- span.in_scope(|| tracing::trace!("WhatsApp signal received"));
- signal
+ // Handed on: the supervisor and the account's
+ // runner do the signal's work inside it.
+ Traced { signal, span }
}
None => {
tracing::warn!(
@@ -87,10 +89,10 @@ impl SignalListener {
}
}
// The connection dropped; the next call reconnects and resubscribes.
- Ok(None) => Signal::Resync,
+ Ok(None) => Signal::Resync.into(),
Err(error) => {
tracing::warn!(error = %error, "WhatsApp signal listener failed; reconnecting");
- Signal::Resync
+ Signal::Resync.into()
}
};
if signals.send(signal).await.is_err() {
@@ -103,7 +105,7 @@ impl SignalListener {
/// Maps one notification to a signal and the sender's trace context; `None`
/// for unknown channels or payloads.
pub fn parse(channel: &str, payload: &str) -> Option<(Signal, Option<String>)> {
- let payload = whatsapp_linked::outbound::pg::signals::Signal::parse(payload)?;
+ let payload = whatsapp_linked::signals::Signal::parse(payload)?;
let id = payload.id;
let signal = match channel {
ACCOUNT_RELEASED => Some(Signal::AccountReleased(id)),
diff --git a/services/whatsapp_session_service/src/outbound/whatsapp.rs b/services/whatsapp_session_service/src/outbound/whatsapp.rs
index e1831463e9..46c85b69d4 100644
--- a/services/whatsapp_session_service/src/outbound/whatsapp.rs
+++ b/services/whatsapp_session_service/src/outbound/whatsapp.rs
@@ -102,7 +102,8 @@ impl<Kms: WhatsAppKms + 'static> WhatsmeowConnector<Kms> {
fn store_error(error: WhatsAppStoreError) -> SessionError {
match error {
WhatsAppStoreError::Fenced => SessionError::Fenced,
- WhatsAppStoreError::Kms(_) => SessionError::Kms,
+ error if error.is_unreadable_device() => SessionError::DeviceUnreadable,
+ WhatsAppStoreError::Kms(_) => SessionError::KmsUnavailable,
error => internal(error),
}
}
@@ -134,16 +135,16 @@ impl<Kms: WhatsAppKms + 'static> SessionConnector for WhatsmeowConnector<Kms> {
fresh_device: bool,
inbound: Arc<dyn InboundSink>,
) -> Result<(WhatsmeowSession, mpsc::UnboundedReceiver<SessionEvent>), SessionError> {
- let store = self.open_store(scope).await?;
- let mut device = self.load_device(&store).await?;
- if fresh_device && device.id.is_some() {
- // Deleting the device row drops its data key and every stored
- // value; reopening generates both anew.
- device.delete().await.map_err(internal)?;
- let store = self.open_store(scope).await?;
- device = self.load_device(&store).await?;
- return self.start(scope, store, device, inbound);
+ if fresh_device {
+ // Deleted before opening, so a device whose data key KMS no longer
+ // unwraps is replaced too. Its data key and every stored value go
+ // with the row; opening generates both anew.
+ PgWhatsAppStore::reset_device(&self.pool, scope.account_id, scope.lease_epoch)
+ .await
+ .map_err(store_error)?;
}
+ let store = self.open_store(scope).await?;
+ let device = self.load_device(&store).await?;
self.start(scope, store, device, inbound)
}
}
@@ -781,8 +782,8 @@ impl WhatsAppSession for WhatsmeowSession {
while let Some(item) = codes.recv().await {
let event = match item {
QrChannelItem::Code { code, .. } => SessionEvent::Qr(code),
+ QrChannelItem::Timeout => SessionEvent::PairExpired,
QrChannelItem::Error(_)
- | QrChannelItem::Timeout
| QrChannelItem::ErrUnexpectedEvent
| QrChannelItem::ClientOutdated
| QrChannelItem::ScannedWithoutMultidevice => SessionEvent::PairFailed,
@@ -902,8 +903,9 @@ impl WhatsAppSession for WhatsmeowSession {
}
async fn group(&self, group_jid: &str) -> Result<Option<GroupInfo>, SessionError> {
- let jid: Jid = group_jid.parse().map_err(|error| {
- SessionError::Internal(rootcause::report!("{error:?}").into_dynamic())
+ // The parse error repeats the JID; keep it out of logs.
+ let jid: Jid = group_jid.parse().map_err(|_| {
+ SessionError::Internal(rootcause::report!("invalid group JID").into_dynamic())
})?;
match self.client.get_group_info(&jid).await {
Ok(group) => Ok(Some(group_info(group, Utc::now()))),
diff --git a/services/whatsapp_session_service/src/outbound/whatsapp/test.rs b/services/whatsapp_session_service/src/outbound/whatsapp/test.rs
index 721420ed29..2bc92526de 100644
--- a/services/whatsapp_session_service/src/outbound/whatsapp/test.rs
+++ b/services/whatsapp_session_service/src/outbound/whatsapp/test.rs
@@ -146,6 +146,7 @@ async fn a_phone_scanning_the_qr_links_the_account_through_the_encrypted_store(p
let release = CancellationToken::new();
let control = AccountControl {
signals: signal_receiver,
+ cause: tracing::Span::none(),
release: release.clone(),
stop: CancellationToken::new(),
};
@@ -221,6 +222,7 @@ async fn a_phone_scanning_the_qr_links_the_account_through_the_encrypted_store(p
let release = CancellationToken::new();
let control = AccountControl {
signals: signal_receiver,
+ cause: tracing::Span::none(),
release: release.clone(),
stop: CancellationToken::new(),
};
@@ -466,6 +468,50 @@ fn group_metadata_keeps_the_timer_and_tells_a_community_from_its_groups() {
assert_eq!(turned_off.disappearing_seconds, None);
}
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_fresh_device_replaces_one_whose_data_key_kms_lost(pool: PgPool) {
+ let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();
+ let whatsapp = FakeWhatsApp::start().await.unwrap();
+ let account = insert_pairing_account(&pool).await;
+ let scope = SessionService::new(Arc::new(PgLinkedRepository::new(pool.clone())))
+ .begin_lease(account)
+ .await
+ .unwrap()
+ .scope;
+ let connector = |kms| {
+ WhatsmeowConnector::new(
+ pool.clone(),
+ kms,
+ test_signal(),
+ whatsapp.dialer(),
+ Some(whatsapp.media_base_url()),
+ Duration::from_secs(10),
+ )
+ };
+ let (sink, _received) = mpsc::unbounded_channel();
+ let sink: Arc<dyn InboundSink> = Arc::new(RecordingSink(sink));
+ let (session, _events) = connector(FakeWhatsAppKms::new("arn:aws:kms:test:key/lost"))
+ .open(scope, false, Arc::clone(&sink))
+ .await
+ .unwrap();
+ session.disconnect().await;
+
+ // KMS lost the key that wrapped the device's data key.
+ let replaced = connector(FakeWhatsAppKms::new("arn:aws:kms:test:key/lost"));
+ let error = replaced
+ .open(scope, false, Arc::clone(&sink))
+ .await
+ .err()
+ .unwrap();
+ assert!(matches!(error, SessionError::DeviceUnreadable), "{error:?}");
+ let (session, _events) = replaced
+ .open(scope, true, Arc::clone(&sink))
+ .await
+ .expect("a fresh device does not need the lost key");
+ assert_eq!(session.identity_jid().await, None);
+ session.disconnect().await;
+}
+
/// IQ errors keep the whole response node, whose attributes carry JIDs; the
/// session error's message (what `%error` logs) must not repeat them.
#[test]
diff --git a/services/whatsapp_session_service/src/replica.rs b/services/whatsapp_session_service/src/replica.rs
index d49543ff57..306cc96429 100644
--- a/services/whatsapp_session_service/src/replica.rs
+++ b/services/whatsapp_session_service/src/replica.rs
@@ -174,7 +174,7 @@ pub async fn start<Kms: WhatsAppKms + 'static>(
);
let supervisor = Supervisor::new(
locks,
- PgAccountDirectory::new(deps.pool, sessions),
+ PgAccountDirectory::new(sessions),
Arc::new(runner),
SupervisorConfig {
max_accounts: deps.max_accounts,