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(agent-work): show accounts' registered work in agent DMs and calls (#9868)

Eric Hayes94bd77fbdde3
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index 9ccbcd418d..995556d108 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -847,6 +847,7 @@
"crates/share_permission_db_utils",
"crates/skills",
"crates/soup",
+ "crates/soup_realtime",
"crates/sqs_client",
"crates/sqs_worker",
"crates/static_file",
@@ -4091,6 +4092,7 @@
"crates/graphql_notification_inbox",
"crates/graphql_permission",
"crates/graphql_properties",
+ "crates/graphql_registered_work",
"crates/graphql_scheduled_action",
"crates/graphql_soup",
"crates/graphql_soup_filter_input",
@@ -5191,6 +5193,7 @@
"crates/graphql_notification_inbox",
"crates/graphql_permission",
"crates/graphql_properties",
+ "crates/graphql_registered_work",
"crates/graphql_scheduled_action",
"crates/graphql_soup",
"crates/graphql_soup_filter_input",
@@ -8592,6 +8595,158 @@
"crates/system_properties",
"crates/workspace-hack"
],
+ "graphql_registered_work": [
+ "crates/activity",
+ "crates/agent",
+ "crates/agent_changes",
+ "crates/agent_runtime_protocol",
+ "crates/agent_session",
+ "crates/ai_billing",
+ "crates/ai_engine",
+ "crates/ai_toolset",
+ "crates/ai_usage",
+ "crates/analytics_client",
+ "crates/attachment",
+ "crates/attention_feed",
+ "crates/authentication_service_client",
+ "crates/bot_id",
+ "crates/bot_token",
+ "crates/bots",
+ "crates/broadcast",
+ "crates/calendar_events",
+ "crates/call",
+ "crates/channel_sender",
+ "crates/channels",
+ "crates/chat",
+ "crates/comms_db_client",
+ "crates/connection",
+ "crates/connection_gateway_client",
+ "crates/connection_gateway_models",
+ "crates/contacts",
+ "crates/cowlike",
+ "crates/crm",
+ "crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
+ "crates/document_sub_type",
+ "crates/documents",
+ "crates/docx_engine",
+ "crates/dynamic_ui",
+ "crates/dynamodb_client",
+ "crates/email",
+ "crates/email_api_client",
+ "crates/email_db_client",
+ "crates/email_utils",
+ "crates/email_validator",
+ "crates/embedding",
+ "crates/entity_access",
+ "crates/entity_access_db_utils",
+ "crates/entity_access_management",
+ "crates/entity_mutation",
+ "crates/entity_registry/entity_registry",
+ "crates/entity_registry/entity_registry_db_utils",
+ "crates/entity_registry/shared_entity_registry",
+ "crates/favorites",
+ "crates/fig_engine",
+ "crates/filter_ast",
+ "crates/folds/agent_fold",
+ "crates/foreign_entity",
+ "crates/frecency",
+ "crates/genai_telemetry",
+ "crates/generic_email_domains",
+ "crates/git_patch",
+ "crates/github_pull_requests",
+ "crates/gmail_client",
+ "crates/google_token",
+ "crates/graphql_common",
+ "crates/graphql_email",
+ "crates/graphql_permission",
+ "crates/graphql_registered_work",
+ "crates/graphql_soup",
+ "crates/graphql_soup_filter_input",
+ "crates/harness_id",
+ "crates/harness_token",
+ "crates/initiative",
+ "crates/invite_email",
+ "crates/ip_extractor",
+ "crates/item_filter_index",
+ "crates/item_filters",
+ "crates/jev",
+ "crates/kafka_util",
+ "crates/last_online_tracker",
+ "crates/lexical_client",
+ "crates/macro_auth",
+ "crates/macro_authorization",
+ "crates/macro_aws_config",
+ "crates/macro_db_client",
+ "crates/macro_entrypoint",
+ "crates/macro_env",
+ "crates/macro_env_var",
+ "crates/macro_event_broker",
+ "crates/macro_event_topics",
+ "crates/macro_service_urls",
+ "crates/macro_sha_count_client",
+ "crates/macro_sync_service_jwt",
+ "crates/macro_tower_layers",
+ "crates/macro_user_id",
+ "crates/macro_uuid",
+ "crates/maybe_send",
+ "crates/mention_utils",
+ "crates/messages",
+ "crates/model",
+ "crates/model-entity",
+ "crates/model-error-response",
+ "crates/model_file_type",
+ "crates/model_notifications",
+ "crates/model_owner",
+ "crates/model_user",
+ "crates/models_ai_projection",
+ "crates/models_bulk_upload",
+ "crates/models_databases",
+ "crates/models_dcs",
+ "crates/models_email",
+ "crates/models_entity_access_management",
+ "crates/models_grouping",
+ "crates/models_opensearch",
+ "crates/models_pagination",
+ "crates/models_permissions",
+ "crates/models_properties",
+ "crates/models_sfs",
+ "crates/models_soup",
+ "crates/models_team",
+ "crates/non_empty",
+ "crates/notification",
+ "crates/notification_state",
+ "crates/pptx_engine",
+ "crates/predicate_index",
+ "crates/projects",
+ "crates/prompt",
+ "crates/properties",
+ "crates/psd_engine",
+ "crates/rate_limit",
+ "crates/readonly_pool",
+ "crates/remote_env_var",
+ "crates/roles_and_permissions",
+ "crates/s3_key",
+ "crates/secretsmanager_client",
+ "crates/share_permission_db_utils",
+ "crates/soup",
+ "crates/soup_filter_projection",
+ "crates/soup_realtime",
+ "crates/sqs_client",
+ "crates/sqs_worker",
+ "crates/static_file_service_client",
+ "crates/sync_service",
+ "crates/sync_service_client",
+ "crates/system_properties",
+ "crates/system_skills",
+ "crates/task_dedup",
+ "crates/teams",
+ "crates/trigger_context",
+ "crates/unfurl",
+ "crates/user_quota",
+ "crates/workspace-hack"
+ ],
"graphql_scheduled_action": [
"crates/activity",
"crates/agent",
diff --git a/.sqlx/query-0a81a75b24c12de70c3a0e852ff1bcca6e83aa31da7e0b713e6ccc5e686d85c5.json b/.sqlx/query-0a81a75b24c12de70c3a0e852ff1bcca6e83aa31da7e0b713e6ccc5e686d85c5.json
new file mode 100644
index 0000000000..0822dd1c31
--- /dev/null
+++ b/.sqlx/query-0a81a75b24c12de70c3a0e852ff1bcca6e83aa31da7e0b713e6ccc5e686d85c5.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT EXISTS (\n SELECT 1\n FROM work_registration\n WHERE agent_session_id = $1 AND (ended_at IS NULL OR ended_at > $2)\n ) AS \"current!\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "current!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Timestamptz"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "0a81a75b24c12de70c3a0e852ff1bcca6e83aa31da7e0b713e6ccc5e686d85c5"
+}
diff --git a/.sqlx/query-3549683ecd8e6122aeec073ab5835ed049eed260cc1343c5ad66b1ff4ec2e071.json b/.sqlx/query-3549683ecd8e6122aeec073ab5835ed049eed260cc1343c5ad66b1ff4ec2e071.json
new file mode 100644
index 0000000000..f473d775d0
--- /dev/null
+++ b/.sqlx/query-3549683ecd8e6122aeec073ab5835ed049eed260cc1343c5ad66b1ff4ec2e071.json
@@ -0,0 +1,41 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id, account_id, agent_session_id, registered_at\n FROM work_registration\n WHERE account_id = $1 AND agent_session_id = $2 AND ended_at IS NULL\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "account_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "agent_session_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 3,
+ "name": "registered_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "3549683ecd8e6122aeec073ab5835ed049eed260cc1343c5ad66b1ff4ec2e071"
+}
diff --git a/.sqlx/query-3c6402a09e4af8bf76d46830e410bb62629726946df5a5023f986e62cc3799b4.json b/.sqlx/query-3c6402a09e4af8bf76d46830e410bb62629726946df5a5023f986e62cc3799b4.json
new file mode 100644
index 0000000000..7511976219
--- /dev/null
+++ b/.sqlx/query-3c6402a09e4af8bf76d46830e410bb62629726946df5a5023f986e62cc3799b4.json
@@ -0,0 +1,54 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT registration.id, registration.account_id, registration.agent_session_id,\n registration.registered_at,\n registration.ended_at IS NOT NULL AS \"ended!\",\n session.archived_by IS NOT NULL AS \"session_archived!\"\n FROM work_registration registration\n JOIN agent_session session ON session.id = registration.agent_session_id\n WHERE registration.agent_session_id = ANY($1)\n AND registration.account_id = ANY($2)\n AND (registration.ended_at IS NULL OR registration.ended_at > $3)\n ORDER BY (registration.ended_at IS NULL), registration.registered_at\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "account_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "agent_session_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 3,
+ "name": "registered_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 4,
+ "name": "ended!",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 5,
+ "name": "session_archived!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "UuidArray",
+ "TextArray",
+ "Timestamptz"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ null,
+ null
+ ]
+ },
+ "hash": "3c6402a09e4af8bf76d46830e410bb62629726946df5a5023f986e62cc3799b4"
+}
diff --git a/.sqlx/query-570a9ef3c70caea5e99bf9b82c0caabe54f85e8d4195f66081759f655693e640.json b/.sqlx/query-570a9ef3c70caea5e99bf9b82c0caabe54f85e8d4195f66081759f655693e640.json
new file mode 100644
index 0000000000..823522b876
--- /dev/null
+++ b/.sqlx/query-570a9ef3c70caea5e99bf9b82c0caabe54f85e8d4195f66081759f655693e640.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT archived_by IS NOT NULL AS \"archived!\"\n FROM agent_session\n WHERE id = $1\n FOR SHARE\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "archived!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "570a9ef3c70caea5e99bf9b82c0caabe54f85e8d4195f66081759f655693e640"
+}
diff --git a/.sqlx/query-9100a3a74e30a9eb6555184c11d83dda2de68d240b7b1627fd298e4da122c2af.json b/.sqlx/query-9100a3a74e30a9eb6555184c11d83dda2de68d240b7b1627fd298e4da122c2af.json
new file mode 100644
index 0000000000..d7ce965952
--- /dev/null
+++ b/.sqlx/query-9100a3a74e30a9eb6555184c11d83dda2de68d240b7b1627fd298e4da122c2af.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE work_registration\n SET ended_at = NOW(), end_reason = 'pull_request_finished'\n WHERE ended_at IS NULL\n AND agent_session_id IN (\n SELECT link.agent_session_id\n FROM agent_session_pull_request link\n WHERE lower(link.github_key) = lower($1)\n AND NOT EXISTS (\n SELECT 1\n FROM agent_session_pull_request other\n LEFT JOIN github_pull_request pull_request\n ON lower(pull_request.github_key) = lower(other.github_key)\n WHERE other.agent_session_id = link.agent_session_id\n AND pull_request.status IS DISTINCT FROM 'merged'\n AND pull_request.status IS DISTINCT FROM 'closed'\n )\n )\n RETURNING agent_session_id\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "agent_session_id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "9100a3a74e30a9eb6555184c11d83dda2de68d240b7b1627fd298e4da122c2af"
+}
diff --git a/.sqlx/query-9521cfd333a1db6c463d7e6f0b115fe576c973cd090478412d9ee404f829d90e.json b/.sqlx/query-9521cfd333a1db6c463d7e6f0b115fe576c973cd090478412d9ee404f829d90e.json
new file mode 100644
index 0000000000..dc049fa8ae
--- /dev/null
+++ b/.sqlx/query-9521cfd333a1db6c463d7e6f0b115fe576c973cd090478412d9ee404f829d90e.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO work_registration (id, account_id, agent_session_id)\n VALUES ($1, $2, $3)\n ON CONFLICT (account_id, agent_session_id) WHERE ended_at IS NULL DO NOTHING\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "9521cfd333a1db6c463d7e6f0b115fe576c973cd090478412d9ee404f829d90e"
+}
diff --git a/.sqlx/query-9c51bc6f44efc4da58b1125d86c051ed98197f89dac0de7044aaf9ccaac60e93.json b/.sqlx/query-9c51bc6f44efc4da58b1125d86c051ed98197f89dac0de7044aaf9ccaac60e93.json
new file mode 100644
index 0000000000..a8ef935b19
--- /dev/null
+++ b/.sqlx/query-9c51bc6f44efc4da58b1125d86c051ed98197f89dac0de7044aaf9ccaac60e93.json
@@ -0,0 +1,30 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH due AS (\n SELECT registration.id,\n CASE\n WHEN pull_requests.finished THEN 'pull_request_finished'\n WHEN session.archived_by IS NOT NULL THEN 'session_archived'\n WHEN session.turn_state = 'blocked' THEN 'blocked_timeout'\n ELSE 'idle'\n END AS reason\n FROM work_registration registration\n JOIN agent_session session ON session.id = registration.agent_session_id\n CROSS JOIN LATERAL (\n SELECT COALESCE(\n bool_and(COALESCE(pull_request.status IN ('merged', 'closed'), false)),\n false\n ) AS finished\n FROM agent_session_pull_request link\n LEFT JOIN github_pull_request pull_request\n ON lower(pull_request.github_key) = lower(link.github_key)\n WHERE link.agent_session_id = session.id\n ) pull_requests\n WHERE registration.ended_at IS NULL\n AND (\n pull_requests.finished\n OR session.archived_by IS NOT NULL\n OR (session.turn_state = 'blocked' AND session.modified_at < $2)\n OR (session.turn_state IS DISTINCT FROM 'blocked'\n AND session.modified_at < $1)\n )\n ORDER BY registration.registered_at\n LIMIT $3\n )\n UPDATE work_registration registration\n SET ended_at = NOW(),\n end_reason = due.reason::work_registration_end_reason\n FROM due\n WHERE registration.id = due.id AND registration.ended_at IS NULL\n RETURNING registration.agent_session_id, due.reason AS \"reason!\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "agent_session_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "reason!",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Timestamptz",
+ "Timestamptz",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false,
+ null
+ ]
+ },
+ "hash": "9c51bc6f44efc4da58b1125d86c051ed98197f89dac0de7044aaf9ccaac60e93"
+}
diff --git a/.sqlx/query-bb82d28ac0ecc72cac7ad62f91ab37166201cfb7295311f6f95a129dc5828ec4.json b/.sqlx/query-bb82d28ac0ecc72cac7ad62f91ab37166201cfb7295311f6f95a129dc5828ec4.json
new file mode 100644
index 0000000000..4422bbe3c8
--- /dev/null
+++ b/.sqlx/query-bb82d28ac0ecc72cac7ad62f91ab37166201cfb7295311f6f95a129dc5828ec4.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE work_registration\n SET ended_at = NOW(), end_reason = 'unregistered'\n WHERE account_id = $1 AND agent_session_id = $2 AND ended_at IS NULL\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "bb82d28ac0ecc72cac7ad62f91ab37166201cfb7295311f6f95a129dc5828ec4"
+}
diff --git a/.sqlx/query-c458535c7a78c1b18f5decc7b6d9c3ae74b144dab628fa58b929b67e07506c1e.json b/.sqlx/query-c458535c7a78c1b18f5decc7b6d9c3ae74b144dab628fa58b929b67e07506c1e.json
new file mode 100644
index 0000000000..29be3653d4
--- /dev/null
+++ b/.sqlx/query-c458535c7a78c1b18f5decc7b6d9c3ae74b144dab628fa58b929b67e07506c1e.json
@@ -0,0 +1,41 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT registration.id, registration.account_id, registration.agent_session_id,\n registration.registered_at\n FROM work_registration registration\n JOIN agent_session session ON session.id = registration.agent_session_id\n WHERE registration.account_id = ANY($1)\n AND registration.ended_at IS NULL\n AND session.archived_by IS NULL\n ORDER BY registration.registered_at DESC, registration.id DESC\n LIMIT $2\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "account_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "agent_session_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 3,
+ "name": "registered_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "TextArray",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "c458535c7a78c1b18f5decc7b6d9c3ae74b144dab628fa58b929b67e07506c1e"
+}
diff --git a/.sqlx/query-e346331f6fdffe1949e7d8574d41e1a73c605a757324396675cfd0b17921eebd.json b/.sqlx/query-e346331f6fdffe1949e7d8574d41e1a73c605a757324396675cfd0b17921eebd.json
new file mode 100644
index 0000000000..d235ef49fe
--- /dev/null
+++ b/.sqlx/query-e346331f6fdffe1949e7d8574d41e1a73c605a757324396675cfd0b17921eebd.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE work_registration\n SET ended_at = NOW(), end_reason = 'session_archived'\n WHERE agent_session_id = $1 AND ended_at IS NULL\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "e346331f6fdffe1949e7d8574d41e1a73c605a757324396675cfd0b17921eebd"
+}
diff --git a/Cargo.lock b/Cargo.lock
index 78ac464cc3..cc11ad6015 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -678,6 +678,7 @@ dependencies = [
"serde_json",
"share_permission_db_utils",
"soup",
+ "soup_realtime",
"sqlx",
"sqs_client",
"sqs_worker",
@@ -858,6 +859,7 @@ dependencies = [
"entity_access_db_utils",
"entity_registry",
"entity_registry_db_utils",
+ "futures",
"genai_telemetry",
"harness_id",
"jev",
@@ -4873,6 +4875,7 @@ dependencies = [
"graphql_notification_inbox",
"graphql_permission",
"graphql_properties",
+ "graphql_registered_work",
"graphql_scheduled_action",
"graphql_soup",
"graphql_work_feed",
@@ -9494,6 +9497,27 @@ dependencies = [
"workspace-hack",
]
+[[package]]
+name = "graphql_registered_work"
+version = "0.1.0"
+dependencies = [
+ "agent_session",
+ "async-graphql",
+ "async-stream",
+ "attention_feed",
+ "chrono",
+ "futures",
+ "graphql_common",
+ "graphql_soup",
+ "macro_user_id",
+ "model-entity",
+ "soup_realtime",
+ "tokio",
+ "tracing",
+ "uuid",
+ "workspace-hack",
+]
+
[[package]]
name = "graphql_scheduled_action"
version = "0.1.0"
diff --git a/Cargo.toml b/Cargo.toml
index bca938e633..e77655676f 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -90,6 +90,7 @@ members = [
"crates/graphql_scheduled_action",
"crates/graphql_soup",
"crates/graphql_soup_filter_input",
+ "crates/graphql_registered_work",
"crates/graphql_work_feed",
"crates/gtm_invite",
"crates/harness_id",
diff --git a/apps/web/src/components/ui/components/Tabs.tsx b/apps/web/src/components/ui/components/Tabs.tsx
index 52444a4708..5531077913 100644
--- a/apps/web/src/components/ui/components/Tabs.tsx
+++ b/apps/web/src/components/ui/components/Tabs.tsx
@@ -19,6 +19,8 @@ export type TabOption<T extends string> = {
icon?: Component<{ class?: string }>;
/** Shown after the label in muted figures; strings retain caller formatting. */
count?: number | string;
+ /** A small attention dot after the label. */
+ dot?: boolean;
disabled?: boolean;
};
@@ -215,6 +217,12 @@ function OptionContent<T extends string>(props: {
{props.option.count}
</span>
</Show>
+ <Show when={props.option.dot && !props.iconOnly}>
+ <span
+ aria-hidden="true"
+ class="size-1.5 shrink-0 rounded-full bg-accent"
+ />
+ </Show>
</>
);
}
diff --git a/apps/web/src/features/agent-work/components/WorkIdentity.tsx b/apps/web/src/features/agent-work/components/WorkIdentity.tsx
new file mode 100644
index 0000000000..c43e923a3f
--- /dev/null
+++ b/apps/web/src/features/agent-work/components/WorkIdentity.tsx
@@ -0,0 +1,20 @@
+import { AgentTag } from '@core/component/AgentTag';
+import type { JSX } from 'solid-js';
+
+/** A Work section's heading: picture, name, and the agent tag. */
+export function WorkIdentity(props: {
+ avatar: JSX.Element;
+ name: string;
+ isAgent: boolean;
+ /** Something true of this person right now, such as speaking in a call. */
+ note?: JSX.Element;
+}) {
+ return (
+ <span class="flex min-w-0 items-center gap-2 text-sm font-semibold text-ink">
+ {props.avatar}
+ <span class="min-w-0 truncate">{props.name}</span>
+ {props.isAgent ? <AgentTag /> : null}
+ {props.note}
+ </span>
+ );
+}
diff --git a/apps/web/src/features/agent-work/components/WorkList.tsx b/apps/web/src/features/agent-work/components/WorkList.tsx
new file mode 100644
index 0000000000..ad8d7fb282
--- /dev/null
+++ b/apps/web/src/features/agent-work/components/WorkList.tsx
@@ -0,0 +1,61 @@
+import { t } from '@app/lib/i18n';
+import GitPullRequestIcon from '@icon/system/regular/git-pull-request.svg';
+import { cn } from '@ui';
+import { For, Show } from 'solid-js';
+import type { WorkItem, WorkItemState } from '../core/work-item';
+
+function WorkDot(props: { state: WorkItemState }) {
+ return (
+ <span
+ aria-hidden="true"
+ class={cn(
+ 'size-1.5 shrink-0 rounded-full',
+ props.state === 'running' && 'bg-accent motion-safe:animate-pulse',
+ props.state === 'needs_input' && 'bg-warning',
+ props.state === 'failed' && 'bg-failure',
+ props.state === 'idle' && 'bg-ink-disabled'
+ )}
+ />
+ );
+}
+
+function stateLabel(state: WorkItemState) {
+ if (state === 'needs_input') return t('agentWork.needsInput');
+ if (state === 'failed') return t('agentWork.failed');
+ return undefined;
+}
+
+/** The sessions an account is working on. Rows never reorder as state changes. */
+export function WorkList(props: {
+ items: readonly WorkItem[];
+ onOpen: (item: WorkItem, event: MouseEvent) => void;
+}) {
+ return (
+ <For each={props.items}>
+ {(item) => (
+ <button
+ type="button"
+ class="flex h-8 w-full min-w-0 shrink-0 items-center gap-1.5 rounded-lg px-2 text-left text-sm text-ink outline-none not-touch:hover:bg-hover focus-visible:outline-2 focus-visible:outline-accent touch:h-11"
+ onClick={(event) => props.onOpen(item, event)}
+ >
+ <WorkDot state={item.state} />
+ <span class="min-w-0 flex-1 truncate">{item.title}</span>
+ <Show when={item.pullRequestNumber}>
+ {(number) => (
+ <span class="flex shrink-0 items-center gap-1 text-xs text-ink-extra-muted tabular-nums">
+ <GitPullRequestIcon class="size-3.5" />#{number()}
+ </span>
+ )}
+ </Show>
+ <Show when={stateLabel(item.state)}>
+ {(label) => (
+ <span class="shrink-0 text-xs font-medium text-ink">
+ {label()}
+ </span>
+ )}
+ </Show>
+ </button>
+ )}
+ </For>
+ );
+}
diff --git a/apps/web/src/features/agent-work/core/work-item.ts b/apps/web/src/features/agent-work/core/work-item.ts
new file mode 100644
index 0000000000..2362367d42
--- /dev/null
+++ b/apps/web/src/features/agent-work/core/work-item.ts
@@ -0,0 +1,50 @@
+import { parseGithubPrUrl } from '@app/features/block-pr/util/prKey';
+import type { RegisteredWorkEntryFieldsFragment } from '@service-storage/graphql/generated/graphql';
+
+/** How a registered session reads in Work. */
+export type WorkItemState = 'running' | 'needs_input' | 'failed' | 'idle';
+
+/** A session an account registered as its work. */
+export type WorkItem = {
+ /** The registration, which a removal names. */
+ registrationId: string;
+ accountId: string;
+ registeredAt: string;
+ sessionId: string;
+ title: string;
+ state: WorkItemState;
+ pullRequestNumber?: number;
+};
+
+function workItemState(turn: string | null | undefined): WorkItemState {
+ if (turn === 'blocked') return 'needs_input';
+ if (turn === 'failed') return 'failed';
+ if (turn === 'starting' || turn === 'running' || turn === 'stopping')
+ return 'running';
+ return 'idle';
+}
+
+export function workItemFromEntry(
+ entry: RegisteredWorkEntryFieldsFragment
+): WorkItem {
+ const pullRequest = parseGithubPrUrl(entry.session.pullRequestUrl ?? '');
+
+ return {
+ registrationId: entry.id,
+ accountId: entry.accountId,
+ registeredAt: entry.registeredAt,
+ sessionId: entry.session.id,
+ title: entry.session.sessionName ?? '',
+ state: workItemState(entry.session.turnState),
+ pullRequestNumber: pullRequest?.number,
+ };
+}
+
+/** Oldest first, so rows stay put as work comes and goes. */
+export function sortWorkItems(items: Iterable<WorkItem>): WorkItem[] {
+ return [...items].sort(
+ (left, right) =>
+ left.registeredAt.localeCompare(right.registeredAt) ||
+ left.registrationId.localeCompare(right.registrationId)
+ );
+}
diff --git a/apps/web/src/features/agent-work/core/work-visibility.test.ts b/apps/web/src/features/agent-work/core/work-visibility.test.ts
new file mode 100644
index 0000000000..e603400450
--- /dev/null
+++ b/apps/web/src/features/agent-work/core/work-visibility.test.ts
@@ -0,0 +1,64 @@
+import { describe, expect, it } from 'vitest';
+import { callWorkAccounts, dmWorkAccount } from './work-visibility';
+
+const isAgentAccount = (id: string) => id === 'macro|[email protected]';
+
+describe('dmWorkAccount', () => {
+ it('picks the other account when it is an agent', () => {
+ expect(
+ dmWorkAccount({
+ isDirectMessage: true,
+ participantIds: ['macro|[email protected]', 'macro|[email protected]'],
+ viewerId: 'macro|[email protected]',
+ isAgentAccount,
+ })
+ ).toBe('macro|[email protected]');
+ });
+
+ it('shows nothing in a DM with a person', () => {
+ expect(
+ dmWorkAccount({
+ isDirectMessage: true,
+ participantIds: ['macro|[email protected]', 'macro|[email protected]'],
+ viewerId: 'macro|[email protected]',
+ isAgentAccount,
+ })
+ ).toBeUndefined();
+ });
+
+ it('shows nothing in a group or a channel', () => {
+ expect(
+ dmWorkAccount({
+ isDirectMessage: true,
+ participantIds: [
+ ],
+ viewerId: 'macro|[email protected]',
+ isAgentAccount,
+ })
+ ).toBeUndefined();
+ expect(
+ dmWorkAccount({
+ isDirectMessage: false,
+ participantIds: ['macro|[email protected]', 'macro|[email protected]'],
+ viewerId: 'macro|[email protected]',
+ isAgentAccount,
+ })
+ ).toBeUndefined();
+ });
+});
+
+describe('callWorkAccounts', () => {
+ it('ignores guests and repeat connections, whatever the join order', () => {
+ expect(
+ callWorkAccounts([
+ undefined,
+ ])
+ ).toEqual(['macro|[email protected]', 'macro|[email protected]']);
+ });
+});
diff --git a/apps/web/src/features/agent-work/core/work-visibility.ts b/apps/web/src/features/agent-work/core/work-visibility.ts
new file mode 100644
index 0000000000..afa934dbfc
--- /dev/null
+++ b/apps/web/src/features/agent-work/core/work-visibility.ts
@@ -0,0 +1,28 @@
+/**
+ * Where registered work shows. Registering is open to every account; these
+ * only decide display, and are kept here so the rules are easy to change.
+ */
+
+/** A direct message shows the other account's work only if it's an agent. */
+export function dmWorkAccount(options: {
+ isDirectMessage: boolean;
+ participantIds: readonly string[];
+ viewerId: string | undefined;
+ isAgentAccount: (id: string) => boolean;
+}): string | undefined {
+ if (!options.isDirectMessage) return undefined;
+
+ const others = options.participantIds.filter((id) => id !== options.viewerId);
+ if (others.length !== 1) return undefined;
+
+ const [other] = others;
+ return options.isAgentAccount(other) ? other : undefined;
+}
+
+/** A call shows the work of everyone else in it, person or agent. */
+export function callWorkAccounts(
+ participantIds: readonly (string | undefined)[]
+): string[] {
+ const accounts = participantIds.filter((id) => id !== undefined);
+ return [...new Set(accounts)].sort();
+}
diff --git a/apps/web/src/features/agent-work/primitives/create-registered-work.test.ts b/apps/web/src/features/agent-work/primitives/create-registered-work.test.ts
new file mode 100644
index 0000000000..dd45495743
--- /dev/null
+++ b/apps/web/src/features/agent-work/primitives/create-registered-work.test.ts
@@ -0,0 +1,162 @@
+import type { Client } from '@urql/core';
+import { createRoot, createSignal } from 'solid-js';
+import { describe, expect, it, vi } from 'vitest';
+import { makeSubject } from 'wonka';
+import { createRegisteredWork } from './create-registered-work';
+
+function entry(
+ id: string,
+ accountId: string,
+ registeredAt = '2026-11-05T10:00:00Z'
+) {
+ return {
+ id,
+ accountId,
+ registeredAt,
+ session: {
+ id: `session-${id}`,
+ sessionName: `Session ${id}`,
+ turnState: 'running',
+ pullRequestUrl: null,
+ },
+ };
+}
+
+function setup(reads: ReturnType<typeof entry>[][]) {
+ const events: string[] = [];
+ const stream = makeSubject<unknown>();
+ const client = {
+ subscription: () => {
+ events.push('subscribe');
+ return stream.source;
+ },
+ query: () => ({
+ toPromise: async () => {
+ events.push('read');
+ return { data: { user: { registeredWork: reads.shift() ?? [] } } };
+ },
+ }),
+ } as unknown as Client;
+ const reconnectListeners = new Set<() => void>();
+ const [accountIds, setAccountIds] = createSignal<readonly string[]>([
+ 'a',
+ 'b',
+ ]);
+ const dispose = { run: () => {} };
+ const work = createRoot((disposer) => {
+ dispose.run = disposer;
+ return createRegisteredWork({
+ client: () => client,
+ accountIds,
+ enabled: () => true,
+ onReconnected: (listener) => {
+ reconnectListeners.add(listener);
+ return () => reconnectListeners.delete(listener);
+ },
+ });
+ });
+ const patch = (patches: unknown[]) =>
+ stream.next({ data: { registeredWorkUpdates: patches } });
+ return { work, events, patch, reconnectListeners, setAccountIds, dispose };
+}
+
+const settled = () => vi.waitFor(() => Promise.resolve());
+
+describe('createRegisteredWork', () => {
+ it('follows the stream before reading', async () => {
+ const { work, events, dispose } = setup([[entry('1', 'a')]]);
+ await vi.waitFor(() => expect(work.loaded()).toBe(true));
+
+ expect(events).toEqual(['subscribe', 'read']);
+ expect(work.accountsWithWork()).toEqual(['a']);
+ dispose.run();
+ });
+
+ it('applies upserts and removals as they arrive', async () => {
+ const { work, patch, dispose } = setup([[entry('1', 'a')]]);
+ await vi.waitFor(() => expect(work.loaded()).toBe(true));
+
+ patch([
+ { __typename: 'GraphqlRegisteredWorkUpsert', entry: entry('2', 'b') },
+ ]);
+ expect(work.accountsWithWork()).toEqual(['a', 'b']);
+
+ patch([{ __typename: 'GraphqlRegisteredWorkRemove', registrationId: '1' }]);
+ expect(work.accountsWithWork()).toEqual(['b']);
+ dispose.run();
+ });
+
+ it('keeps rows in registration order when a session changes', async () => {
+ const { work, patch, dispose } = setup([
+ [
+ entry('1', 'a', '2026-11-05T10:00:00Z'),
+ entry('2', 'a', '2026-11-05T11:00:00Z'),
+ ],
+ ]);
+ await vi.waitFor(() => expect(work.loaded()).toBe(true));
+
+ const blocked = entry('1', 'a', '2026-11-05T10:00:00Z');
+ blocked.session.turnState = 'blocked';
+ patch([{ __typename: 'GraphqlRegisteredWorkUpsert', entry: blocked }]);
+
+ const rows = work.byAccount().get('a') ?? [];
+ expect(rows.map((row) => row.registrationId)).toEqual(['1', '2']);
+ expect(rows[0]?.state).toBe('needs_input');
+ dispose.run();
+ });
+
+ it('follows the new client when the transport changes', async () => {
+ const plain = {
+ subscription: vi.fn(() => makeSubject<unknown>().source),
+ query: () => ({
+ toPromise: async () => ({
+ data: { user: { registeredWork: [entry('1', 'a')] } },
+ }),
+ }),
+ } as unknown as Client;
+ const realtime = {
+ subscription: vi.fn(() => makeSubject<unknown>().source),
+ query: () => ({
+ toPromise: async () => ({
+ data: { user: { registeredWork: [entry('1', 'a')] } },
+ }),
+ }),
+ } as unknown as Client;
+ const [client, setClient] = createSignal(plain);
+ const dispose = { run: () => {} };
+ const work = createRoot((disposer) => {
+ dispose.run = disposer;
+ return createRegisteredWork({
+ client,
+ accountIds: () => ['a'],
+ enabled: () => true,
+ onReconnected: () => () => {},
+ });
+ });
+ await vi.waitFor(() => expect(work.loaded()).toBe(true));
+
+ setClient(() => realtime);
+ await vi.waitFor(() =>
+ expect(realtime.subscription).toHaveBeenCalledTimes(1)
+ );
+ expect(work.accountsWithWork()).toEqual(['a']);
+ dispose.run();
+ });
+
+ it('reads again when told changes may have been missed', async () => {
+ const { work, patch, reconnectListeners, dispose } = setup([
+ [entry('1', 'a')],
+ [],
+ [entry('3', 'b')],
+ ]);
+ await vi.waitFor(() => expect(work.loaded()).toBe(true));
+
+ patch([{ __typename: 'GraphqlRegisteredWorkInvalidate', refresh: true }]);
+ await vi.waitFor(() => expect(work.accountsWithWork()).toEqual([]));
+
+ for (const listener of reconnectListeners) listener();
+ await vi.waitFor(() => expect(work.accountsWithWork()).toEqual(['b']));
+ await settled();
+ dispose.run();
+ });
+});
diff --git a/apps/web/src/features/agent-work/primitives/create-registered-work.ts b/apps/web/src/features/agent-work/primitives/create-registered-work.ts
new file mode 100644
index 0000000000..dd1be4bf31
--- /dev/null
+++ b/apps/web/src/features/agent-work/primitives/create-registered-work.ts
@@ -0,0 +1,155 @@
+import { fireAndForget } from '@core/util/fireAndForget';
+import { Telemetry } from '@macro-inc/observability';
+import {
+ RegisteredWorkDocument,
+ RegisteredWorkUpdatesDocument,
+} from '@service-storage/graphql/generated/graphql';
+import type { Client } from '@urql/core';
+import {
+ type Accessor,
+ createEffect,
+ createMemo,
+ createSignal,
+ on,
+ onCleanup,
+} from 'solid-js';
+import { pipe, subscribe } from 'wonka';
+import {
+ sortWorkItems,
+ type WorkItem,
+ workItemFromEntry,
+} from '../core/work-item';
+
+const RESUBSCRIBE_DELAY_MS = 3_000;
+
+/**
+ * Live registered work for a set of accounts. It follows the stream before
+ * reading, so nothing committed during the read is missed, and reads again
+ * whenever the stream says changes may have been missed.
+ */
+export function createRegisteredWork(options: {
+ client: Accessor<Client>;
+ accountIds: Accessor<readonly string[]>;
+ enabled: Accessor<boolean>;
+ /** Subscribes to transport reconnects, after which changes may be missed. */
+ onReconnected: (listener: () => void) => () => void;
+}) {
+ const [items, setItems] = createSignal<ReadonlyMap<string, WorkItem>>(
+ new Map()
+ );
+ const [loaded, setLoaded] = createSignal(false);
+ const key = createMemo(() =>
+ options.enabled() ? [...options.accountIds()].sort().join(',') : ''
+ );
+
+ const follow = (accountIds: string[], client: Client) => {
+ let latestRead = 0;
+ let retry: ReturnType<typeof setTimeout> | undefined;
+ let stopStream: (() => void) | undefined;
+ let disposed = false;
+
+ const read = async () => {
+ const readId = ++latestRead;
+ const result = await Telemetry.span(
+ 'agent_work.read',
+ { attributes: { 'agent_work.account_count': accountIds.length } },
+ () =>
+ client
+ .query(
+ RegisteredWorkDocument,
+ { accountIds },
+ { requestPolicy: 'network-only' }
+ )
+ .toPromise()
+ );
+ if (disposed || readId !== latestRead) return;
+
+ const entries = result.data?.user.registeredWork;
+ if (!entries) return;
+
+ setItems(
+ new Map(
+ entries.map((entry) => [entry.id, workItemFromEntry(entry)] as const)
+ )
+ );
+ setLoaded(true);
+ };
+
+ const startStream = () => {
+ const { unsubscribe } = pipe(
+ client.subscription(RegisteredWorkUpdatesDocument, { accountIds }),
+ subscribe((result) => {
+ if (result.error) {
+ stopStream?.();
+ retry = setTimeout(startStream, RESUBSCRIBE_DELAY_MS);
+ return;
+ }
+
+ const patches = result.data?.registeredWorkUpdates ?? [];
+ if (patches.length === 0) return;
+
+ let invalidated = false;
+ const next = new Map(items());
+ for (const patch of patches) {
+ if (patch.__typename === 'GraphqlRegisteredWorkUpsert') {
+ next.set(patch.entry.id, workItemFromEntry(patch.entry));
+ } else if (patch.__typename === 'GraphqlRegisteredWorkRemove') {
+ next.delete(patch.registrationId);
+ } else {
+ invalidated = true;
+ }
+ }
+
+ setItems(next);
+ if (invalidated) refresh();
+ })
+ );
+ stopStream = unsubscribe;
+ };
+
+ const refresh = () => fireAndForget(read(), 'agent_work.read');
+
+ startStream();
+ refresh();
+ const stopListening = options.onReconnected(refresh);
+
+ return () => {
+ disposed = true;
+ clearTimeout(retry);
+ stopStream?.();
+ stopListening();
+ };
+ };
+
+ createEffect(
+ on([key, options.client], ([current, client], previous) => {
+ if (current !== previous?.[0]) {
+ setItems(new Map());
+ setLoaded(false);
+ }
+ if (!current) return;
+
+ onCleanup(follow(current.split(','), client));
+ })
+ );
+
+ const byAccount = createMemo(() => {
+ const grouped = new Map<string, WorkItem[]>();
+ for (const item of sortWorkItems(items().values())) {
+ const list = grouped.get(item.accountId);
+ if (list) list.push(item);
+ else grouped.set(item.accountId, [item]);
+ }
+ return grouped;
+ });
+
+ return {
+ /** False until the first read lands, so existing work isn't announced. */
+ loaded,
+ byAccount,
+ /** Accounts with work, in the order they were asked for. */
+ accountsWithWork: createMemo(() =>
+ options.accountIds().filter((id) => byAccount().has(id))
+ ),
+ };
+}
diff --git a/apps/web/src/features/agent-work/primitives/create-work-arrivals.test.ts b/apps/web/src/features/agent-work/primitives/create-work-arrivals.test.ts
new file mode 100644
index 0000000000..ec57268b0e
--- /dev/null
+++ b/apps/web/src/features/agent-work/primitives/create-work-arrivals.test.ts
@@ -0,0 +1,79 @@
+import { createRoot, createSignal } from 'solid-js';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { createWorkArrivals } from './create-work-arrivals';
+
+const flush = () => Promise.resolve();
+
+describe('createWorkArrivals', () => {
+ beforeEach(() => vi.useFakeTimers());
+ afterEach(() => vi.useRealTimers());
+
+ function setup(announceInitial?: boolean) {
+ const [loaded, setLoaded] = createSignal(false);
+ const [accounts, setAccounts] = createSignal<readonly string[]>([]);
+ const dispose = { run: () => {} };
+ const arrivals = createRoot((disposer) => {
+ dispose.run = disposer;
+ return createWorkArrivals({
+ loaded,
+ accountsWithWork: accounts,
+ announceInitial,
+ durationMs: 1_000,
+ });
+ });
+ return { arrivals, setLoaded, setAccounts, dispose };
+ }
+
+ it('does not announce work already there when the list loads', async () => {
+ const { arrivals, setLoaded, setAccounts, dispose } = setup();
+ setAccounts(['a']);
+ setLoaded(true);
+ await flush();
+
+ expect(arrivals.arrivals()).toEqual([]);
+ dispose.run();
+ });
+
+ it('announces an account that starts working, then lets it go', async () => {
+ const { arrivals, setLoaded, setAccounts, dispose } = setup();
+ setLoaded(true);
+ await flush();
+ setAccounts(['a']);
+ await flush();
+ expect(arrivals.arrivals()).toEqual(['a']);
+
+ vi.advanceTimersByTime(1_000);
+ expect(arrivals.arrivals()).toEqual([]);
+ dispose.run();
+ });
+
+ it('announces again only after the work has gone away', async () => {
+ const { arrivals, setLoaded, setAccounts, dispose } = setup();
+ setLoaded(true);
+ await flush();
+ setAccounts(['a']);
+ await flush();
+ arrivals.dismiss();
+
+ setAccounts(['a']);
+ await flush();
+ expect(arrivals.arrivals()).toEqual([]);
+
+ setAccounts([]);
+ await flush();
+ setAccounts(['a']);
+ await flush();
+ expect(arrivals.arrivals()).toEqual(['a']);
+ dispose.run();
+ });
+
+ it('announces existing work on load when asked to', async () => {
+ const { arrivals, setLoaded, setAccounts, dispose } = setup(true);
+ setAccounts(['a']);
+ setLoaded(true);
+ await flush();
+
+ expect(arrivals.arrivals()).toEqual(['a']);
+ dispose.run();
+ });
+});
diff --git a/apps/web/src/features/agent-work/primitives/create-work-arrivals.ts b/apps/web/src/features/agent-work/primitives/create-work-arrivals.ts
new file mode 100644
index 0000000000..ad9146bdb9
--- /dev/null
+++ b/apps/web/src/features/agent-work/primitives/create-work-arrivals.ts
@@ -0,0 +1,55 @@
+import {
+ type Accessor,
+ createEffect,
+ createSignal,
+ on,
+ onCleanup,
+} from 'solid-js';
+
+/**
+ * Accounts that just went from no work to having some, for as long as the
+ * moment should be announced. Each account is announced once until its work
+ * has gone away.
+ */
+export function createWorkArrivals(options: {
+ loaded: Accessor<boolean>;
+ accountsWithWork: Accessor<readonly string[]>;
+ /** Also announce work that's already there when the list first loads. */
+ announceInitial?: boolean;
+ durationMs: number;
+}) {
+ const [arrivals, setArrivals] = createSignal<readonly string[]>([]);
+ let known = new Set<string>();
+ let baselineTaken = false;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+
+ const dismiss = () => {
+ clearTimeout(timer);
+ setArrivals([]);
+ };
+
+ createEffect(
+ on([options.loaded, options.accountsWithWork], ([loaded, accounts]) => {
+ if (!loaded) {
+ known = new Set();
+ baselineTaken = false;
+ dismiss();
+ return;
+ }
+
+ const fresh = accounts.filter((id) => !known.has(id));
+ const announce =
+ fresh.length > 0 && (baselineTaken || options.announceInitial === true);
+ known = new Set(accounts);
+ baselineTaken = true;
+ if (!announce) return;
+
+ setArrivals((current) => [...new Set([...current, ...fresh])]);
+ clearTimeout(timer);
+ timer = setTimeout(() => setArrivals([]), options.durationMs);
+ })
+ );
+ onCleanup(() => clearTimeout(timer));
+
+ return { arrivals, dismiss };
+}
diff --git a/apps/web/src/features/agent-work/views/call-work.tsx b/apps/web/src/features/agent-work/views/call-work.tsx
new file mode 100644
index 0000000000..6af12dbdc7
--- /dev/null
+++ b/apps/web/src/features/agent-work/views/call-work.tsx
@@ -0,0 +1,161 @@
+import { CollapsibleSection } from '@app/components/view-shell/CollapsibleSection';
+import { useFeatureFlag } from '@app/lib/analytics/posthog';
+import { t } from '@app/lib/i18n';
+import { UserGroup } from '@core/component/UserGroup';
+import { UserIcon } from '@core/component/UserIcon';
+import { enableAgentWork } from '@core/constant/featureFlags';
+import { getDisplayName, isAgentAccount, tryMacroId } from '@core/user';
+import XIcon from '@icon/system/regular/x.svg';
+import { subscribeGraphqlSoupReconnected } from '@service-storage/graphql-soup';
+import { Button } from '@ui';
+import { type Accessor, createSignal, For, Show } from 'solid-js';
+import { WorkIdentity } from '../components/WorkIdentity';
+import { WorkList } from '../components/WorkList';
+import type { WorkItem } from '../core/work-item';
+import { callWorkAccounts } from '../core/work-visibility';
+import { createRegisteredWork } from '../primitives/create-registered-work';
+import { createWorkArrivals } from '../primitives/create-work-arrivals';
+import { useOpenWorkItem } from './open-work-item';
+import { useWorkClient } from './use-work-client';
+
+/** How long the active work prompt stays over the call. */
+const WORK_PROMPT_DURATION_MS = 8_000;
+
+type CallPanelTab = 'chat' | 'participants' | 'work';
+
+/** The Work state of a call: who has work, and what its panel should show. */
+export function createCallWork(options: {
+ accountIds: Accessor<readonly (string | undefined)[]>;
+ selectedTab: Accessor<CallPanelTab>;
+ panelOpen: Accessor<boolean>;
+ canChat: Accessor<boolean>;
+}) {
+ const flag = useFeatureFlag(enableAgentWork);
+ const work = createRegisteredWork({
+ client: useWorkClient(),
+ accountIds: () => callWorkAccounts(options.accountIds()),
+ enabled: () => flag().enabled,
+ onReconnected: subscribeGraphqlSoupReconnected,
+ });
+ const hasWork = () => work.accountsWithWork().length > 0;
+ const activeTab = (): CallPanelTab => {
+ const tab = options.selectedTab();
+ if (tab === 'work' && hasWork()) return 'work';
+ if (!options.canChat()) return 'participants';
+ return tab === 'work' ? 'chat' : tab;
+ };
+
+ const viewingWork = () => options.panelOpen() && activeTab() === 'work';
+ const arrivals = createWorkArrivals({
+ loaded: work.loaded,
+ accountsWithWork: work.accountsWithWork,
+ announceInitial: true,
+ durationMs: WORK_PROMPT_DURATION_MS,
+ });
+
+ return {
+ work,
+ hasWork,
+ activeTab,
+ arrivals,
+ showTabDot: () => hasWork() && !viewingWork(),
+ showButtonDot: () => hasWork() && !options.panelOpen(),
+ showPrompt: () => !viewingWork() && arrivals.arrivals().length > 0,
+ };
+}
+
+function CallWorkSection(props: {
+ accountId: string;
+ items: readonly WorkItem[];
+ isSpeaking: boolean;
+}) {
+ const [open, setOpen] = createSignal(true);
+ const openItem = useOpenWorkItem();
+
+ return (
+ <CollapsibleSection.Root open={open()} onOpenChange={setOpen}>
+ <CollapsibleSection.Header>
+ <CollapsibleSection.Trigger class="flex-1">
+ <WorkIdentity
+ name={getDisplayName(tryMacroId(props.accountId))}
+ isAgent={isAgentAccount(tryMacroId(props.accountId))}
+ avatar={
+ <UserIcon
+ id={props.accountId}
+ size="md"
+ suppressClick
+ showTooltip={false}
+ />
+ }
+ note={
+ <Show when={props.isSpeaking}>
+ <span class="shrink-0 text-xs font-medium text-accent">
+ {t('calls.speaking')}
+ </span>
+ </Show>
+ }
+ />
+ <CollapsibleSection.Indicator />
+ </CollapsibleSection.Trigger>
+ </CollapsibleSection.Header>
+ <CollapsibleSection.Content>
+ <nav class="flex flex-col gap-(--sidebar-row-gap)">
+ <WorkList items={props.items} onOpen={openItem} />
+ </nav>
+ </CollapsibleSection.Content>
+ </CollapsibleSection.Root>
+ );
+}
+
+/** The call panel's Work tab: one section per participant with work. */
+export function CallWorkTab(props: {
+ accounts: readonly string[];
+ itemsFor: (accountId: string) => readonly WorkItem[];
+ isSpeaking: (accountId: string) => boolean;
+}) {
+ return (
+ <div class="flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto overscroll-contain px-1 pb-3">
+ <For each={props.accounts}>
+ {(accountId) => (
+ <CallWorkSection
+ accountId={accountId}
+ items={props.itemsFor(accountId)}
+ isSpeaking={props.isSpeaking(accountId)}
+ />
+ )}
+ </For>
+ </div>
+ );
+}
+
+/**
+ * Announces active work over the call stage, above the local video tile that
+ * holds the bottom-right corner. Specific to calls: it belongs to the room,
+ * not to the app's notifications.
+ */
+export function CallWorkPrompt(props: {
+ accounts: readonly string[];
+ onView: () => void;
+ onDismiss: () => void;
+}) {
+ return (
+ <div class="menu-surface absolute right-4 bottom-33 z-30 flex items-center gap-1 p-1 pointer-events-auto">
+ <button
+ type="button"
+ class="flex h-9 min-w-0 items-center gap-2 rounded-lg pr-2 pl-1.5 text-sm font-medium text-ink outline-none not-touch:hover:bg-hover focus-visible:outline-2 focus-visible:outline-accent [--avatar-group-separator:var(--color-menu)]"
+ onClick={props.onView}
+ >
+ <UserGroup userIds={[...props.accounts]} size="md" suppressClick />
+ <span class="truncate">{t('agentWork.viewActiveWork')}</span>
+ </button>
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ aria-label={t('agentWork.dismissActiveWork')}
+ onClick={props.onDismiss}
+ >
+ <XIcon class="size-3.5" />
+ </Button>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/agent-work/views/dm-work.tsx b/apps/web/src/features/agent-work/views/dm-work.tsx
new file mode 100644
index 0000000000..f66e82bfb3
--- /dev/null
+++ b/apps/web/src/features/agent-work/views/dm-work.tsx
@@ -0,0 +1,198 @@
+import { useFeatureFlag } from '@app/lib/analytics/posthog';
+import { t } from '@app/lib/i18n';
+import { SidePanel, useSidePanel } from '@components/app/side-panel';
+import { UserIcon } from '@core/component/UserIcon';
+import { enableAgentWork } from '@core/constant/featureFlags';
+import { useUserId } from '@core/context/user';
+import { getDisplayName, isAgentAccount, tryMacroId } from '@core/user';
+import { subscribeGraphqlSoupReconnected } from '@service-storage/graphql-soup';
+import {
+ type Accessor,
+ createContext,
+ createMemo,
+ type ParentProps,
+ Show,
+ useContext,
+} from 'solid-js';
+import { Transition } from 'solid-transition-group';
+import { WorkIdentity } from '../components/WorkIdentity';
+import { WorkList } from '../components/WorkList';
+import type { WorkItem } from '../core/work-item';
+import { dmWorkAccount } from '../core/work-visibility';
+import { createRegisteredWork } from '../primitives/create-registered-work';
+import { createWorkArrivals } from '../primitives/create-work-arrivals';
+import { useOpenWorkItem } from './open-work-item';
+import { useWorkClient } from './use-work-client';
+
+const ARRIVAL_DURATION_MS = 6_000;
+
+type DmWork = {
+ account: Accessor<string | undefined>;
+ items: Accessor<readonly WorkItem[]>;
+ arriving: Accessor<boolean>;
+ dismissArrival: () => void;
+};
+
+const DmWorkContext = createContext<DmWork>();
+
+/**
+ * Owns a DM's Work and its side panel state, around the header and the body.
+ * Everything inside stays inert unless the other account is an agent with work.
+ */
+export function DmWorkProvider(
+ props: ParentProps<{
+ isDirectMessage: boolean;
+ participantIds: readonly string[];
+ }>
+) {
+ const flag = useFeatureFlag(enableAgentWork);
+ const viewerId = useUserId();
+ const account = createMemo(() => {
+ if (!flag().enabled) return undefined;
+
+ return dmWorkAccount({
+ isDirectMessage: props.isDirectMessage,
+ participantIds: props.participantIds,
+ viewerId: viewerId(),
+ isAgentAccount: (id) => isAgentAccount(tryMacroId(id)),
+ });
+ });
+ const accountIds = createMemo(() => {
+ const id = account();
+ return id ? [id] : [];
+ });
+ const work = createRegisteredWork({
+ client: useWorkClient(),
+ accountIds,
+ enabled: () => account() !== undefined,
+ onReconnected: subscribeGraphqlSoupReconnected,
+ });
+ const arrivals = createWorkArrivals({
+ loaded: work.loaded,
+ accountsWithWork: work.accountsWithWork,
+ durationMs: ARRIVAL_DURATION_MS,
+ });
+ const value: DmWork = {
+ account,
+ items: () => work.byAccount().get(account() ?? '') ?? [],
+ arriving: () => arrivals.arrivals().length > 0,
+ dismissArrival: arrivals.dismiss,
+ };
+
+ return (
+ <SidePanel.Root floating defaultOpen={false} persistKey="dm-work">
+ <DmWorkContext.Provider value={value}>
+ {props.children}
+ </DmWorkContext.Provider>
+ </SidePanel.Root>
+ );
+}
+
+function ArrivalLabel(props: { account: string }) {
+ const work = useContext(DmWorkContext);
+ const panel = useSidePanel();
+
+ return (
+ <button
+ type="button"
+ class="flex h-7 max-w-56 min-w-0 shrink items-center gap-1.5 rounded-full border border-edge-button bg-control pr-2.5 pl-1 text-xs font-medium text-ink outline-none not-touch:hover:bg-hover focus-visible:outline-2 focus-visible:outline-accent"
+ onClick={() => {
+ work?.dismissArrival();
+ panel?.setIsOpen(true);
+ }}
+ >
+ <span class="relative flex shrink-0">
+ <UserIcon
+ id={props.account}
+ size="md"
+ suppressClick
+ showTooltip={false}
+ />
+ <span
+ aria-hidden="true"
+ class="absolute -right-0.5 -bottom-0.5 size-1.5 rounded-full bg-accent ring-2 ring-control motion-safe:animate-pulse"
+ />
+ </span>
+ <span class="min-w-0 truncate">
+ {t('agentWork.startedWorking', {
+ name: getDisplayName(tryMacroId(props.account)),
+ })}
+ </span>
+ </button>
+ );
+}
+
+/**
+ * The panel toggle, once there's work. When work first appears it announces
+ * itself beside the toggle for a moment, without opening a closed panel.
+ */
+export function DmWorkToggle() {
+ const work = useContext(DmWorkContext);
+
+ return (
+ <Show when={work?.account() && (work?.items().length ?? 0) > 0}>
+ <Transition
+ appear
+ enterActiveClass="transition-[opacity,translate] duration-200 ease-out motion-reduce:duration-0"
+ enterClass="opacity-0 translate-x-2"
+ enterToClass="opacity-100 translate-x-0"
+ exitActiveClass="transition-opacity duration-150 ease-out motion-reduce:duration-0"
+ exitClass="opacity-100"
+ exitToClass="opacity-0"
+ >
+ <Show when={work?.arriving() && work?.account()}>
+ {(account) => <ArrivalLabel account={account()} />}
+ </Show>
+ </Transition>
+ <SidePanel.Toggle />
+ </Show>
+ );
+}
+
+/**
+ * The floating side panel over a DM's body. It renders nothing of its own
+ * until there's work, so the conversation underneath never remounts.
+ */
+export function DmWorkPanel() {
+ const work = useContext(DmWorkContext);
+ const open = useOpenWorkItem();
+
+ return (
+ <Show
+ when={
+ work?.account() && (work?.items().length ?? 0) > 0 && work?.account()
+ }
+ >
+ {(account) => (
+ <div class="pointer-events-none absolute inset-0">
+ <SidePanel.Layout headerToggle={false} floating>
+ <SidePanel.Section
+ id="work"
+ defaultOpen
+ order={5}
+ title={
+ <WorkIdentity
+ isAgent
+ name={getDisplayName(tryMacroId(account()))}
+ avatar={
+ <UserIcon
+ id={account()}
+ size="md"
+ suppressClick
+ showTooltip={false}
+ />
+ }
+ />
+ }
+ >
+ <nav class="-mx-1 flex flex-col gap-(--sidebar-row-gap)">
+ <WorkList items={work?.items() ?? []} onOpen={open} />
+ </nav>
+ </SidePanel.Section>
+ <div />
+ </SidePanel.Layout>
+ </div>
+ )}
+ </Show>
+ );
+}
diff --git a/apps/web/src/features/agent-work/views/open-work-item.ts b/apps/web/src/features/agent-work/views/open-work-item.ts
new file mode 100644
index 0000000000..81789a340e
--- /dev/null
+++ b/apps/web/src/features/agent-work/views/open-work-item.ts
@@ -0,0 +1,13 @@
+import { useSplitLayout } from '@components/app/split-layout/layout';
+import type { WorkItem } from '../core/work-item';
+
+/** Opens a registered session beside whatever you're in, keeping it live. */
+export function useOpenWorkItem() {
+ const layout = useSplitLayout();
+
+ return (item: WorkItem) =>
+ layout?.openWithSplit(
+ { type: 'agent', id: item.sessionId },
+ { activate: true, preferNewSplit: true }
+ );
+}
diff --git a/apps/web/src/features/agent-work/views/use-work-client.ts b/apps/web/src/features/agent-work/views/use-work-client.ts
new file mode 100644
index 0000000000..6e43c8f0dd
--- /dev/null
+++ b/apps/web/src/features/agent-work/views/use-work-client.ts
@@ -0,0 +1,17 @@
+import { useFeatureFlag } from '@app/lib/analytics/posthog';
+import { enableGraphqlSoup } from '@core/constant/featureFlags';
+import { getGraphqlSoupClient } from '@service-storage/graphql-soup';
+
+/**
+ * The Soup client, reread when its transport flag resolves. Only the realtime
+ * client carries subscriptions, so a stream started on the plain client that
+ * serves before then would never deliver.
+ */
+export function useWorkClient() {
+ const transport = useFeatureFlag(enableGraphqlSoup);
+
+ return () => {
+ transport();
+ return getGraphqlSoupClient();
+ };
+}
diff --git a/apps/web/src/features/channel/Call/CallOverlay.tsx b/apps/web/src/features/channel/Call/CallOverlay.tsx
index dd33cfe183..e5873e47d9 100644
--- a/apps/web/src/features/channel/Call/CallOverlay.tsx
+++ b/apps/web/src/features/channel/Call/CallOverlay.tsx
@@ -1,3 +1,8 @@
+import {
+ CallWorkPrompt,
+ CallWorkTab,
+ createCallWork,
+} from '@app/features/agent-work/views/call-work';
import { t } from '@app/lib/i18n';
import { FloatRegion } from '@components/app/mobile/float-regions/FloatRegion';
import { Resize } from '@core/component/Resize';
@@ -324,7 +329,6 @@ export function CallOverlay(props: {
const [sidebarMount, setSidebarMount] = createSignal<HTMLDivElement>();
const [overlayMount, setOverlayMount] = createSignal<HTMLDivElement>();
const widePanel = () => !isMobile() && (resizeContext()?.size() ?? 0) >= 800;
- const activeTab = () => (canChat() ? selectedTab() : 'participants');
const [settingsOpen, setSettingsOpen] = createSignal(false);
const [sharingOpen, setSharingOpen] = createSignal(false);
const [keyboardFocus, setKeyboardFocus] = createSignal(false);
@@ -360,6 +364,7 @@ export function CallOverlay(props: {
const PanelToggle = () => (
<Button
ref={panelButton}
+ class="relative"
variant="secondary"
size={isMobile() ? 'icon-xl' : 'icon-lg'}
aria-label={panelOpen() ? t('calls.closePanel') : t('calls.openPanel')}
@@ -377,12 +382,48 @@ export function CallOverlay(props: {
>
<ChatIcon class="size-4 mobile:size-6" />
</Show>
+ <Show when={callWork.showButtonDot()}>
+ <span
+ aria-hidden="true"
+ class="absolute top-1 right-1 size-1.5 rounded-full bg-accent"
+ />
+ </Show>
</Button>
);
const participants = () =>
Array.from(callCtx.remoteParticipants().values()).filter((p) => !p.isAgent);
+ const callWork = createCallWork({
+ accountIds: () =>
+ participants().map((participant) => tryMacroId(participant.identity)),
+ selectedTab,
+ panelOpen,
+ canChat,
+ });
+ const work = callWork.work;
+ const hasWork = callWork.hasWork;
+ const activeTab = callWork.activeTab;
+ const workArrivals = callWork.arrivals;
+ const workTab = () => {
+ if (!hasWork()) return undefined;
+
+ return (
+ <CallWorkTab
+ accounts={work.accountsWithWork()}
+ itemsFor={(id) => work.byAccount().get(id) ?? []}
+ isSpeaking={isAccountSpeaking}
+ />
+ );
+ };
+ const openWork = () => {
+ workArrivals.dismiss();
+ setFocusChatOnOpen(false);
+ setSelectedTab('work');
+ setPanelMounted(true);
+ setPanelOpen(true);
+ };
+
const [selectedParticipant, setSelectedParticipant] = createSignal<
RemoteParticipant | 'local'
>();
@@ -437,6 +478,13 @@ export function CallOverlay(props: {
});
};
+ const isAccountSpeaking = (accountId: string) => {
+ const participant = participants().find(
+ (candidate) => tryMacroId(candidate.identity) === accountId
+ );
+ return participant ? callCtx.isParticipantSpeaking(participant) : false;
+ };
+
const hasAnyScreenShare = () =>
callCtx.isScreenSharing() || remoteScreenShares().length > 0;
@@ -579,6 +627,14 @@ export function CallOverlay(props: {
</For>
</div>
+ <Show when={callWork.showPrompt()}>
+ <CallWorkPrompt
+ accounts={work.accountsWithWork()}
+ onView={openWork}
+ onDismiss={workArrivals.dismiss}
+ />
+ </Show>
+
{/* Local participant PIP (Google Meet style: small, bottom-right) */}
<div
class={cn(
@@ -671,6 +727,8 @@ export function CallOverlay(props: {
chatAvailable={canChat()}
participantCount={participants().length + 1}
participants={<CallParticipantsList localName={props.localName} />}
+ work={workTab()}
+ workDot={callWork.showTabDot()}
sidebarMount={widePanel() ? sidebarMount() : undefined}
overlayMount={overlayMount()}
returnFocus={panelButton}
diff --git a/apps/web/src/features/channel/Call/chat/components/CallChatPanel.tsx b/apps/web/src/features/channel/Call/chat/components/CallChatPanel.tsx
index edab3ba1ba..cbafa0264b 100644
--- a/apps/web/src/features/channel/Call/chat/components/CallChatPanel.tsx
+++ b/apps/web/src/features/channel/Call/chat/components/CallChatPanel.tsx
@@ -5,7 +5,7 @@ import XIcon from '@icon/system/regular/x.svg';
import { Button, cn, Tabs } from '@ui';
import { createEffect, createSignal, type JSX, on, onCleanup } from 'solid-js';
-export type CallPanelTab = 'chat' | 'participants';
+export type CallPanelTab = 'chat' | 'participants' | 'work';
/** Share one mounted panel between the desktop sidebar and phone drawer. */
export function CallChatPanel(props: {
@@ -17,6 +17,10 @@ export function CallChatPanel(props: {
chatAvailable: boolean;
participantCount: number;
participants: JSX.Element;
+ /** Present while someone in the call has work the viewer can see. */
+ work?: JSX.Element;
+ /** Marks the Work tab while the viewer is elsewhere. */
+ workDot?: boolean;
children: JSX.Element;
sidebarMount?: HTMLElement;
overlayMount?: HTMLElement;
@@ -119,6 +123,15 @@ export function CallChatPanel(props: {
label: t('calls.participants'),
count: props.participantCount.toLocaleString(formatLocale()),
},
+ ...(props.work
+ ? [
+ {
+ value: 'work' as const,
+ label: t('agentWork.title'),
+ dot: props.workDot,
+ },
+ ]
+ : []),
]}
/>
<Button
@@ -153,6 +166,17 @@ export function CallChatPanel(props: {
>
{props.participants}
</section>
+ <section
+ aria-label={t('agentWork.title')}
+ hidden={props.activeTab !== 'work'}
+ inert={props.activeTab !== 'work'}
+ class={cn(
+ 'flex min-h-0 flex-1 flex-col',
+ props.activeTab !== 'work' && 'hidden'
+ )}
+ >
+ {props.work}
+ </section>
</div>
</MobileDrawer>
);
diff --git a/apps/web/src/features/channel/Call/tests/call-overlay-muted.test.tsx b/apps/web/src/features/channel/Call/tests/call-overlay-muted.test.tsx
index b7528e7f8a..cdd7d20dc3 100644
--- a/apps/web/src/features/channel/Call/tests/call-overlay-muted.test.tsx
+++ b/apps/web/src/features/channel/Call/tests/call-overlay-muted.test.tsx
@@ -2,7 +2,14 @@
* @vitest-environment jsdom
*/
-import { fireEvent, render, screen, within } from '@solidjs/testing-library';
+import type { WorkItem } from '@app/features/agent-work/core/work-item';
+import {
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+ within,
+} from '@solidjs/testing-library';
import type { RemoteParticipant, Track } from 'livekit-client';
import { createSignal, type JSX, type Setter } from 'solid-js';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -20,6 +27,32 @@ vi.mock('@components/app/split-layout/layoutUtils', () => ({
useSplitPanel: () => undefined,
}));
+vi.mock('@app/lib/analytics/posthog', () => ({
+ useFeatureFlag: () => () => ({ enabled: false }),
+}));
+
+const registeredWork = vi.hoisted(() => ({
+ accounts: undefined as undefined | (() => readonly string[]),
+ items: undefined as
+ | undefined
+ | (() => ReadonlyMap<string, readonly WorkItem[]>),
+ loaded: undefined as undefined | (() => boolean),
+}));
+
+vi.mock('@core/component/UserGroup', () => ({ UserGroup: () => null }));
+
+vi.mock('@app/features/agent-work/views/use-work-client', () => ({
+ useWorkClient: () => () => undefined,
+}));
+
+vi.mock('@app/features/agent-work/primitives/create-registered-work', () => ({
+ createRegisteredWork: () => ({
+ loaded: () => registeredWork.loaded?.() ?? false,
+ byAccount: () => registeredWork.items?.() ?? new Map(),
+ accountsWithWork: () => registeredWork.accounts?.() ?? [],
+ }),
+}));
+
vi.mock('@core/mobile/isMobile', () => ({
isMobile: () => mocks.mobile,
}));
@@ -38,6 +71,7 @@ vi.mock('@core/signal/profilePicture', () => ({
}));
vi.mock('@core/user', () => ({
+ isAgentAccount: () => true,
tryMacroId: (identity: string) => identity,
getDisplayName: (identity: string) =>
mocks.displayNames.get(identity) ?? identity,
@@ -522,6 +556,73 @@ describe('CallOverlay muted microphone badges', () => {
);
});
+describe('CallOverlay Work', () => {
+ const account = 'macro|[email protected]';
+ const row: WorkItem = {
+ registrationId: 'registration-1',
+ accountId: account,
+ registeredAt: '2026-11-05T10:00:00Z',
+ sessionId: 'session-1',
+ title: 'Tavily web search',
+ state: 'needs_input',
+ };
+
+ function setUpWork() {
+ const [accounts, setAccounts] = createSignal<readonly string[]>([]);
+ registeredWork.accounts = accounts;
+ registeredWork.items = () => new Map(accounts().map((id) => [id, [row]]));
+ registeredWork.loaded = () => true;
+ setUpCallState([createRemoteParticipant(account, {}, 'Agent teammate')]);
+ return setAccounts;
+ }
+
+ afterEach(() => {
+ registeredWork.accounts = undefined;
+ registeredWork.items = undefined;
+ registeredWork.loaded = undefined;
+ });
+
+ it('prompts when work appears and opens it in the Work tab', async () => {
+ const setAccounts = setUpWork();
+ render(() => <CallOverlay onLeave={() => undefined} />);
+ expect(screen.queryByText('View active work')).toBeNull();
+
+ setAccounts([account]);
+ fireEvent.click(await screen.findByText('View active work'));
+
+ expect(await screen.findByText('Tavily web search')).toBeTruthy();
+ expect(screen.getByText('Needs input')).toBeTruthy();
+ expect(screen.queryByText('View active work')).toBeNull();
+ });
+
+ it('dismisses the prompt without opening the panel', async () => {
+ const setAccounts = setUpWork();
+ render(() => <CallOverlay onLeave={() => undefined} />);
+
+ setAccounts([account]);
+ await screen.findByText('View active work');
+ fireEvent.click(screen.getByRole('button', { name: 'Dismiss' }));
+
+ expect(screen.queryByText('View active work')).toBeNull();
+ expect(screen.queryByText('Tavily web search')).toBeNull();
+ });
+
+ it('returns to Chat when the last work ends', async () => {
+ const setAccounts = setUpWork();
+ render(() => <CallOverlay onLeave={() => undefined} />);
+
+ setAccounts([account]);
+ fireEvent.click(await screen.findByText('View active work'));
+ await screen.findByText('Tavily web search');
+
+ setAccounts([]);
+ await waitFor(() =>
+ expect(screen.queryByRole('radio', { name: 'Work' })).toBeNull()
+ );
+ expect(screen.queryByText('Tavily web search')).toBeNull();
+ });
+});
+
describe('CallParticipantsList live roster', () => {
it('tracks human arrivals and departures without counting recording agents', () => {
const guest = createRemoteParticipant('guest-1', {}, 'Guest attendee');
diff --git a/apps/web/src/features/channel/Channel/ChannelDetail.tsx b/apps/web/src/features/channel/Channel/ChannelDetail.tsx
index b7b8d76690..ee0d6f84e0 100644
--- a/apps/web/src/features/channel/Channel/ChannelDetail.tsx
+++ b/apps/web/src/features/channel/Channel/ChannelDetail.tsx
@@ -7,6 +7,11 @@ import {
PriorityCollapseOverflowSensor,
} from '@app/components/priority-collapse/PriorityCollapseOverflowSensor';
import { ViewShell } from '@app/components/view-shell';
+import {
+ DmWorkPanel,
+ DmWorkProvider,
+ DmWorkToggle,
+} from '@app/features/agent-work/views/dm-work';
import { ChatWithAgentButton } from '@app/features/chat/ChatWithAgentButton';
import { useAnalytics } from '@app/lib/analytics/analytics-context';
import { TraceFlow } from '@app/observability/flow';
@@ -178,6 +183,7 @@ export function ChannelDetailActions(props: ChannelDetailHeaderProps) {
return (
<div class="header-actions ml-auto flex shrink-0 items-center gap-2 touch:gap-1">
+ <DmWorkToggle />
<DebugSuspense name="ChannelDetail.live-indicators">
<ChannelLiveIndicators channelId={props.channelId} />
</DebugSuspense>
@@ -285,6 +291,7 @@ function ChannelDetailContent(props: ChannelDetailProps) {
const channelId = props.channelId;
const conversationChannel = useChannel(channelId);
const canCall = useChannelCanCall(channelId);
+ const conversationType = useChannelType(channelId);
const channelName = useChannelName(channelId, props.fallbackName);
useSplitDisplayName(() => channelName() ?? 'New Channel');
const analytics = useAnalytics();
@@ -417,71 +424,81 @@ function ChannelDetailContent(props: ChannelDetailProps) {
onHandled={() => setPendingJoinCall(false)}
/>
</DebugSuspense>
- <div class="flex size-full min-h-0 flex-col">
- <DebugSuspense name="ChannelDetail.header">
- <ChannelDetailHeader
- render={props.children}
- context={{
- channelId,
- name: () => channelName() ?? 'New Channel',
- }}
- />
- </DebugSuspense>
- <div
- class="flex min-h-0 flex-1 flex-col px-2"
- data-channel-tab-content
- >
- <Switch>
- <Match when={activeTab() === 'messages'}>
- <DebugSuspense
- name="ChannelDetail.messages"
- fallback={<ChannelLoading />}
- >
- <TraceFlow name="channel.messages.view">
- <ChannelMessages autofocus={props.autofocus ?? false} />
- </TraceFlow>
- </DebugSuspense>
- </Match>
- <Match when={activeTab() === 'attachments'}>
- <DebugSuspense name="ChannelDetail.attachments">
- <TraceFlow name="channel.attachments.view">
- <ChannelAttachmentsTab channelId={channelId} />
- </TraceFlow>
- </DebugSuspense>
- </Match>
- <Match when={activeTab() === 'calls' && ENABLE_CALLS}>
- <DebugSuspense name="ChannelDetail.calls">
- <TraceFlow name="channel.calls.view">
- <ChannelCallsTab channelId={channelId} />
- </TraceFlow>
- </DebugSuspense>
- </Match>
- <Match when={activeTab() === 'participants'}>
- <DebugSuspense name="ChannelDetail.participants">
- <TraceFlow name="channel.participants.view">
- <ChannelParticipantsTab
- channelId={channelId}
- botManagementEnabled={botManagement.enabled()}
- onCreateBot={botManagement.openCreateBot}
- inviteBotFocusRequest={botManagement.inviteFocusRequest()}
- onOpenBot={botManagement.openBot}
- />
- </TraceFlow>
- </DebugSuspense>
- </Match>
- <Match when={activeTab() === 'call' && canUseInlineCallTab()}>
- <DebugSuspense name="ChannelDetail.call">
- <TraceFlow name="channel.call.view">
- <ChannelCallTab
- channelId={channelId}
- pendingJoin={pendingJoinCall}
- />
- </TraceFlow>
- </DebugSuspense>
- </Match>
- </Switch>
+ <DmWorkProvider
+ isDirectMessage={conversationType() === 'direct_message'}
+ participantIds={
+ conversationChannel()?.participants.map(
+ (participant) => participant.user_id
+ ) ?? []
+ }
+ >
+ <div class="flex size-full min-h-0 flex-col">
+ <DebugSuspense name="ChannelDetail.header">
+ <ChannelDetailHeader
+ render={props.children}
+ context={{
+ channelId,
+ name: () => channelName() ?? 'New Channel',
+ }}
+ />
+ </DebugSuspense>
+ <div
+ class="relative flex min-h-0 flex-1 flex-col px-2"
+ data-channel-tab-content
+ >
+ <DmWorkPanel />
+ <Switch>
+ <Match when={activeTab() === 'messages'}>
+ <DebugSuspense
+ name="ChannelDetail.messages"
+ fallback={<ChannelLoading />}
+ >
+ <TraceFlow name="channel.messages.view">
+ <ChannelMessages autofocus={props.autofocus ?? false} />
+ </TraceFlow>
+ </DebugSuspense>
+ </Match>
+ <Match when={activeTab() === 'attachments'}>
+ <DebugSuspense name="ChannelDetail.attachments">
+ <TraceFlow name="channel.attachments.view">
+ <ChannelAttachmentsTab channelId={channelId} />
+ </TraceFlow>
+ </DebugSuspense>
+ </Match>
+ <Match when={activeTab() === 'calls' && ENABLE_CALLS}>
+ <DebugSuspense name="ChannelDetail.calls">
+ <TraceFlow name="channel.calls.view">
+ <ChannelCallsTab channelId={channelId} />
+ </TraceFlow>
+ </DebugSuspense>
+ </Match>
+ <Match when={activeTab() === 'participants'}>
+ <DebugSuspense name="ChannelDetail.participants">
+ <TraceFlow name="channel.participants.view">
+ <ChannelParticipantsTab
+ channelId={channelId}
+ botManagementEnabled={botManagement.enabled()}
+ onCreateBot={botManagement.openCreateBot}
+ inviteBotFocusRequest={botManagement.inviteFocusRequest()}
+ onOpenBot={botManagement.openBot}
+ />
+ </TraceFlow>
+ </DebugSuspense>
+ </Match>
+ <Match when={activeTab() === 'call' && canUseInlineCallTab()}>
+ <DebugSuspense name="ChannelDetail.call">
+ <TraceFlow name="channel.call.view">
+ <ChannelCallTab
+ channelId={channelId}
+ pendingJoin={pendingJoinCall}
+ />
+ </TraceFlow>
+ </DebugSuspense>
+ </Match>
+ </Switch>
+ </div>
</div>
- </div>
+ </DmWorkProvider>
</ChannelTabProvider>
</ChannelSurface>
);
diff --git a/apps/web/src/features/channel/Channel/tests/channel-detail-navigation.test.tsx b/apps/web/src/features/channel/Channel/tests/channel-detail-navigation.test.tsx
index b387cd9def..81b4b683d9 100644
--- a/apps/web/src/features/channel/Channel/tests/channel-detail-navigation.test.tsx
+++ b/apps/web/src/features/channel/Channel/tests/channel-detail-navigation.test.tsx
@@ -14,6 +14,12 @@ const mocks = vi.hoisted(() => ({
}));
const analytics = vi.hoisted(() => ({ pageView: vi.fn(), track: vi.fn() }));
+vi.mock('@app/features/agent-work/views/dm-work', () => ({
+ DmWorkProvider: (props: { children: unknown }) => props.children,
+ DmWorkPanel: () => null,
+ DmWorkToggle: () => null,
+}));
+
vi.mock('@app/lib/analytics/analytics-context', () => ({
useAnalytics: () => analytics,
}));
diff --git a/apps/web/src/lib/core/constant/featureFlags.ts b/apps/web/src/lib/core/constant/featureFlags.ts
index 58909d2ba1..8906345781 100644
--- a/apps/web/src/lib/core/constant/featureFlags.ts
+++ b/apps/web/src/lib/core/constant/featureFlags.ts
@@ -864,6 +864,14 @@ export const enableUnifiedNotifications = defineFlag({
// Agents home: pending updates from coding agents shown as a stack under the
// new-chat composer, and the Open PRs section in the Agents sidebar.
// Override with VITE_ENABLE_AGENT_UPDATES.
+// Work: what an account registered as its work, in DMs with agent accounts and
+// in calls.
+export const enableAgentWork = defineFlag({
+ key: 'enable-agent-work',
+ env: 'ENABLE_AGENT_WORK',
+ default: onInDev,
+});
+
export const enableAgentUpdates = defineFlag({
key: 'enable-agent-updates',
env: 'ENABLE_AGENT_UPDATES',
diff --git a/apps/web/src/lib/i18n/locales/en.ts b/apps/web/src/lib/i18n/locales/en.ts
index 019c4f5848..e01c4969b9 100644
--- a/apps/web/src/lib/i18n/locales/en.ts
+++ b/apps/web/src/lib/i18n/locales/en.ts
@@ -1,5 +1,6 @@
import agentAutoArchive from './en/agent-auto-archive';
import agentSetup from './en/agent-setup';
+import agentWork from './en/agent-work';
import calls from './en/calls';
import channelComposer from './en/channel-composer';
import channelLabels from './en/channel-labels';
@@ -28,6 +29,7 @@ import viewMenus from './en/view-menus';
export default {
agentAutoArchive,
agentSetup,
+ agentWork,
calls,
channelComposer,
channelLabels,
diff --git a/apps/web/src/lib/i18n/locales/en/agent-work.ts b/apps/web/src/lib/i18n/locales/en/agent-work.ts
new file mode 100644
index 0000000000..166fd05d62
--- /dev/null
+++ b/apps/web/src/lib/i18n/locales/en/agent-work.ts
@@ -0,0 +1,8 @@
+export default {
+ title: 'Work',
+ needsInput: 'Needs input',
+ failed: 'Failed',
+ startedWorking: '{{name}} started working',
+ viewActiveWork: 'View active work',
+ dismissActiveWork: 'Dismiss',
+};
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts
index a21f9516ec..e3321457e3 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts
@@ -71,6 +71,7 @@ import type {
UpdateSharePermissionRequestV2,
WarmAgentSessionRequest,
WarmAgentSessionResponse,
+ WorkRegistrationResponse,
} from './schemas';
/**
@@ -3878,6 +3879,194 @@ export const presentSessionView = async (
} as presentSessionViewResponse;
};
+/**
+ * @summary Register a session as the caller's work. Requires edit access. Repeating returns the active
+registration. Registering does not share the session: viewers who cannot open it do not see
+it, so share it too.
+ */
+export type registerAgentSessionWorkResponse200 = {
+ data: WorkRegistrationResponse;
+ status: 200;
+};
+
+export type registerAgentSessionWorkResponse401 = {
+ data: string;
+ status: 401;
+};
+
+export type registerAgentSessionWorkResponse403 = {
+ data: string;
+ status: 403;
+};
+
+export type registerAgentSessionWorkResponse409 = {
+ data: string;
+ status: 409;
+};
+
+export type registerAgentSessionWorkResponse500 = {
+ data: string;
+ status: 500;
+};
+
+export type registerAgentSessionWorkResponseSuccess =
+ registerAgentSessionWorkResponse200 & {
+ headers: Headers;
+ };
+export type registerAgentSessionWorkResponseError = (
+ | registerAgentSessionWorkResponse401
+ | registerAgentSessionWorkResponse403
+ | registerAgentSessionWorkResponse409
+ | registerAgentSessionWorkResponse500
+) & {
+ headers: Headers;
+};
+
+export type registerAgentSessionWorkResponse =
+ | registerAgentSessionWorkResponseSuccess
+ | registerAgentSessionWorkResponseError;
+
+export const getRegisterAgentSessionWorkUrl = (sessionId: string) => {
+ return `/agent-sessions/${sessionId}/work-registration`;
+};
+
+export const registerAgentSessionWork = async (
+ sessionId: string,
+ options?: RequestInit
+): Promise<registerAgentSessionWorkResponse> => {
+ const res = await fetch(getRegisterAgentSessionWorkUrl(sessionId), {
+ ...options,
+ method: 'PUT',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: registerAgentSessionWorkResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as registerAgentSessionWorkResponse;
+};
+
+/**
+ * @summary End the caller's own registration of a session. Repeating does nothing. It touches only the
+caller's own row, so it needs no access to the session: losing access must not strand it.
+ */
+export type unregisterAgentSessionWorkResponse204 = {
+ data: void;
+ status: 204;
+};
+
+export type unregisterAgentSessionWorkResponse401 = {
+ data: string;
+ status: 401;
+};
+
+export type unregisterAgentSessionWorkResponse500 = {
+ data: string;
+ status: 500;
+};
+
+export type unregisterAgentSessionWorkResponseSuccess =
+ unregisterAgentSessionWorkResponse204 & {
+ headers: Headers;
+ };
+export type unregisterAgentSessionWorkResponseError = (
+ | unregisterAgentSessionWorkResponse401
+ | unregisterAgentSessionWorkResponse500
+) & {
+ headers: Headers;
+};
+
+export type unregisterAgentSessionWorkResponse =
+ | unregisterAgentSessionWorkResponseSuccess
+ | unregisterAgentSessionWorkResponseError;
+
+export const getUnregisterAgentSessionWorkUrl = (sessionId: string) => {
+ return `/agent-sessions/${sessionId}/work-registration`;
+};
+
+export const unregisterAgentSessionWork = async (
+ sessionId: string,
+ options?: RequestInit
+): Promise<unregisterAgentSessionWorkResponse> => {
+ const res = await fetch(getUnregisterAgentSessionWorkUrl(sessionId), {
+ ...options,
+ method: 'DELETE',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: unregisterAgentSessionWorkResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as unregisterAgentSessionWorkResponse;
+};
+
+/**
+ * @summary List the caller's active registrations of sessions they can still view, newest first.
+ */
+export type listAgentWorkRegistrationsResponse200 = {
+ data: WorkRegistrationResponse[];
+ status: 200;
+};
+
+export type listAgentWorkRegistrationsResponse401 = {
+ data: string;
+ status: 401;
+};
+
+export type listAgentWorkRegistrationsResponse500 = {
+ data: string;
+ status: 500;
+};
+
+export type listAgentWorkRegistrationsResponseSuccess =
+ listAgentWorkRegistrationsResponse200 & {
+ headers: Headers;
+ };
+export type listAgentWorkRegistrationsResponseError = (
+ | listAgentWorkRegistrationsResponse401
+ | listAgentWorkRegistrationsResponse500
+) & {
+ headers: Headers;
+};
+
+export type listAgentWorkRegistrationsResponse =
+ | listAgentWorkRegistrationsResponseSuccess
+ | listAgentWorkRegistrationsResponseError;
+
+export const getListAgentWorkRegistrationsUrl = () => {
+ return `/agent-work-registrations`;
+};
+
+export const listAgentWorkRegistrations = async (
+ options?: RequestInit
+): Promise<listAgentWorkRegistrationsResponse> => {
+ const res = await fetch(getListAgentWorkRegistrationsUrl(), {
+ ...options,
+ method: 'GET',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: listAgentWorkRegistrationsResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as listAgentWorkRegistrationsResponse;
+};
+
/**
* @summary Classify a draft for the authenticated user.
*/
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts
index 185071a11c..0665bcbb4e 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts
@@ -422,3 +422,4 @@ export * from './warmAgentSessionResponse';
export * from './warmAgentSessionResponseSession';
export * from './weekdayCode';
export * from './withAgentSessionId';
+export * from './workRegistrationResponse';
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/workRegistrationResponse.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/workRegistrationResponse.ts
new file mode 100644
index 0000000000..ef2a12054d
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/workRegistrationResponse.ts
@@ -0,0 +1,20 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * One account's active registration of one session as its work.
+ */
+export interface WorkRegistrationResponse {
+ /** The account whose work this is. */
+ accountId: string;
+ /** The session registered. */
+ agentSessionId: string;
+ /** The registration. */
+ id: string;
+ /** When the account registered it. */
+ registeredAt: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/openapi.json b/apps/web/src/lib/service-clients/service-agent-harness/openapi.json
index c707c9a5ff..1dddeb619c 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/openapi.json
+++ b/apps/web/src/lib/service-clients/service-agent-harness/openapi.json
@@ -3345,6 +3345,161 @@
}
}
},
+ "/agent-sessions/{session_id}/work-registration": {
+ "put": {
+ "tags": ["agent-sessions"],
+ "summary": "Register a session as the caller's work. Requires edit access. Repeating returns the active\nregistration. Registering does not share the session: viewers who cannot open it do not see\nit, so share it too.",
+ "operationId": "register_agent_session_work",
+ "parameters": [
+ {
+ "name": "session_id",
+ "in": "path",
+ "description": "ID of the agent session",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/WorkRegistrationResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "409": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ },
+ "delete": {
+ "tags": ["agent-sessions"],
+ "summary": "End the caller's own registration of a session. Repeating does nothing. It touches only the\ncaller's own row, so it needs no access to the session: losing access must not strand it.",
+ "operationId": "unregister_agent_session_work",
+ "parameters": [
+ {
+ "name": "session_id",
+ "in": "path",
+ "description": "ID of the agent session",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "responses": {
+ "204": {
+ "description": "The caller has no active registration of the session"
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/agent-work-registrations": {
+ "get": {
+ "tags": ["agent-sessions"],
+ "summary": "List the caller's active registrations of sessions they can still view, newest first.",
+ "operationId": "list_agent_work_registrations",
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/WorkRegistrationResponse"
+ }
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/universal_input/classify": {
"post": {
"tags": ["universal_input::inbound::axum_router"],
@@ -7347,6 +7502,32 @@
"description": "The session id."
}
}
+ },
+ "WorkRegistrationResponse": {
+ "type": "object",
+ "description": "One account's active registration of one session as its work.",
+ "required": ["id", "accountId", "agentSessionId", "registeredAt"],
+ "properties": {
+ "accountId": {
+ "type": "string",
+ "description": "The account whose work this is."
+ },
+ "agentSessionId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The session registered."
+ },
+ "id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The registration."
+ },
+ "registeredAt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "When the account registered it."
+ }
+ }
}
},
"securitySchemes": {
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts b/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts
index 554de381b5..04b7075517 100644
--- a/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts
+++ b/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts
@@ -15521,6 +15521,26 @@ export type PropertyAssignmentParentFragment =
| PropertyAssignmentParent_GraphqlSoupReminder_Fragment
;
+export type RegisteredWorkEntryFieldsFragment = { id: string, accountId: string, registeredAt: string, session: { id: string, turnState: string | null, pullRequestUrl: string | null, sessionName: string } };
+
+export type RegisteredWorkQueryVariables = Exact<{
+ accountIds: Array<string | number> | string | number;
+}>;
+
+
+export type RegisteredWorkQuery = { user: { id: string, registeredWork: Array<{ id: string, accountId: string, registeredAt: string, session: { id: string, turnState: string | null, pullRequestUrl: string | null, sessionName: string } }> } };
+
+export type RegisteredWorkUpdatesSubscriptionVariables = Exact<{
+ accountIds: Array<string | number> | string | number;
+}>;
+
+
+export type RegisteredWorkUpdatesSubscription = { registeredWorkUpdates: Array<
+ | { __typename: 'GraphqlRegisteredWorkInvalidate', refresh: boolean }
+ | { __typename: 'GraphqlRegisteredWorkRemove', registrationId: string }
+ | { __typename: 'GraphqlRegisteredWorkUpsert', entry: { id: string, accountId: string, registeredAt: string, session: { id: string, turnState: string | null, pullRequestUrl: string | null, sessionName: string } } }
+ > };
+
export type SavedViewFieldsFragment = { id: string, ownerId: string, name: string, config: unknown, sharedTeamId: string | null, revision: number, createdAt: string, updatedAt: string };
export type SavedViewsQueryVariables = Exact<{
@@ -24118,6 +24138,7 @@ export const NotificationInboxPatchFieldsFragmentDoc = {"kind":"Document","defin
export const ItemPreviewFieldsFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"ItemPreviewFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupEntity"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupDocument"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"documentName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"fileType"}},{"kind":"Field","name":{"kind":"Name","value":"subType"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlTaskSubType"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"isCompleted"}}]}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChat"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"chatName"},"name":{"kind":"Name","value":"name"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupProject"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"projectName"},"name":{"kind":"Name","value":"name"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupEmailThread"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"emailName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"senderEmail"}},{"kind":"Field","name":{"kind":"Name","value":"senderName"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChannel"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"channelDisplayName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"channelType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupCall"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"customName"}},{"kind":"Field","name":{"kind":"Name","value":"channelName"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupCrmCompany"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"companyName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"domains"}}]}}]}}]} as unknown as DocumentNode<ItemPreviewFieldsFragment, unknown>;
export const ItemPreviewDetailsFieldsFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"ItemPreviewDetailsFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupEntity"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"ItemPreviewFields"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupDocument"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"viewerPermission"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlAccessLevelPermission"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"accessLevel"}}]}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupPropertyValueFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlBooleanPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"boolValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlNumberPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"numberValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlStringPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"stringValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlDatePropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"dateValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlDateRangePropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"rangeStart"},"name":{"kind":"Name","value":"start"}},{"kind":"Field","alias":{"kind":"Name","value":"rangeEnd"},"name":{"kind":"Name","value":"end"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSelectOptionPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"optionIds"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlEntityReferencePropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"references"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"entityId"}},{"kind":"Field","name":{"kind":"Name","value":"entityType"}},{"kind":"Field","name":{"kind":"Name","value":"specificMessageId"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlLinkPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"urls"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"ItemPreviewFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupEntity"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupDocument"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"documentName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"fileType"}},{"kind":"Field","name":{"kind":"Name","value":"subType"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlTaskSubType"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"isCompleted"}}]}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChat"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"chatName"},"name":{"kind":"Name","value":"name"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupProject"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"projectName"},"name":{"kind":"Name","value":"name"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupEmailThread"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"emailName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"senderEmail"}},{"kind":"Field","name":{"kind":"Name","value":"senderName"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChannel"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"channelDisplayName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"channelType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupCall"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"customName"}},{"kind":"Field","name":{"kind":"Name","value":"channelName"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupCrmCompany"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"companyName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"domains"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupPropertyFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlProperty"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"propertyDefinitionId"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"dataType"}},{"kind":"Field","name":{"kind":"Name","value":"isMultiSelect"}},{"kind":"Field","name":{"kind":"Name","value":"specificEntityType"}},{"kind":"Field","name":{"kind":"Name","value":"isSystem"}},{"kind":"Field","name":{"kind":"Name","value":"isMetadata"}},{"kind":"Field","name":{"kind":"Name","value":"value"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyValueFields"}}]}}]}}]} as unknown as DocumentNode<ItemPreviewDetailsFieldsFragment, unknown>;
export const PropertyAssignmentParentFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"PropertyAssignmentParent"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupEntity"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"propertyDefinitionId"}}]}}]}}]} as unknown as DocumentNode<PropertyAssignmentParentFragment, unknown>;
+export const RegisteredWorkEntryFieldsFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"RegisteredWorkEntryFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlRegisteredWork"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"accountId"}},{"kind":"Field","name":{"kind":"Name","value":"registeredAt"}},{"kind":"Field","name":{"kind":"Name","value":"session"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"sessionName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"turnState"}},{"kind":"Field","name":{"kind":"Name","value":"pullRequestUrl"}}]}}]}}]} as unknown as DocumentNode<RegisteredWorkEntryFieldsFragment, unknown>;
export const SavedViewFieldsFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SavedViewFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSavedView"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"config"}},{"kind":"Field","name":{"kind":"Name","value":"sharedTeamId"}},{"kind":"Field","name":{"kind":"Name","value":"revision"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]} as unknown as DocumentNode<SavedViewFieldsFragment, unknown>;
export const MailReadStateFieldsFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"MailReadStateFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupEmailThread"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"isRead"}}]}}]} as unknown as DocumentNode<MailReadStateFieldsFragment, unknown>;
export const MailInboxStateFieldsFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"MailInboxStateFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupEmailThread"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"inboxVisible"}}]}}]} as unknown as DocumentNode<MailInboxStateFieldsFragment, unknown>;
@@ -24210,6 +24231,8 @@ export const ItemPreviewNameCacheWriteDocument = {"kind":"Document","definitions
export const ItemPreviewFileTypeCacheWriteDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"ItemPreviewFileTypeCacheWrite"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"SoupInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"user"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"soup"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"items"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupDocument"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"fileType"}}]}}]}}]}}]}}]}}]} as unknown as DocumentNode<ItemPreviewFileTypeCacheWriteQuery, ItemPreviewFileTypeCacheWriteQueryVariables>;
export const ItemPreviewDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"ItemPreview"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"SoupInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"user"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"soup"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"items"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"ItemPreviewFields"}}]}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"ItemPreviewFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupEntity"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupDocument"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"documentName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"fileType"}},{"kind":"Field","name":{"kind":"Name","value":"subType"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlTaskSubType"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"isCompleted"}}]}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChat"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"chatName"},"name":{"kind":"Name","value":"name"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupProject"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"projectName"},"name":{"kind":"Name","value":"name"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupEmailThread"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"emailName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"senderEmail"}},{"kind":"Field","name":{"kind":"Name","value":"senderName"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChannel"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"channelDisplayName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"channelType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupCall"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"customName"}},{"kind":"Field","name":{"kind":"Name","value":"channelName"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupCrmCompany"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"companyName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"domains"}}]}}]}}]} as unknown as DocumentNode<ItemPreviewQuery, ItemPreviewQueryVariables>;
export const ItemPreviewsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"ItemPreviews"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"SoupInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"user"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"soup"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"items"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"ItemPreviewDetailsFields"}}]}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"ItemPreviewFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupEntity"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupDocument"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"documentName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"fileType"}},{"kind":"Field","name":{"kind":"Name","value":"subType"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlTaskSubType"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"isCompleted"}}]}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChat"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"chatName"},"name":{"kind":"Name","value":"name"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupProject"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"projectName"},"name":{"kind":"Name","value":"name"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupEmailThread"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"emailName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"senderEmail"}},{"kind":"Field","name":{"kind":"Name","value":"senderName"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChannel"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"channelDisplayName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"channelType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupCall"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"customName"}},{"kind":"Field","name":{"kind":"Name","value":"channelName"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupCrmCompany"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"companyName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"domains"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupPropertyValueFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlBooleanPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"boolValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlNumberPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"numberValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlStringPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"stringValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlDatePropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"dateValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlDateRangePropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"rangeStart"},"name":{"kind":"Name","value":"start"}},{"kind":"Field","alias":{"kind":"Name","value":"rangeEnd"},"name":{"kind":"Name","value":"end"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSelectOptionPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"optionIds"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlEntityReferencePropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"references"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"entityId"}},{"kind":"Field","name":{"kind":"Name","value":"entityType"}},{"kind":"Field","name":{"kind":"Name","value":"specificMessageId"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlLinkPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"urls"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupPropertyFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlProperty"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"propertyDefinitionId"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"dataType"}},{"kind":"Field","name":{"kind":"Name","value":"isMultiSelect"}},{"kind":"Field","name":{"kind":"Name","value":"specificEntityType"}},{"kind":"Field","name":{"kind":"Name","value":"isSystem"}},{"kind":"Field","name":{"kind":"Name","value":"isMetadata"}},{"kind":"Field","name":{"kind":"Name","value":"value"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyValueFields"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"ItemPreviewDetailsFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupEntity"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"ItemPreviewFields"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupDocument"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"viewerPermission"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlAccessLevelPermission"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"accessLevel"}}]}}]}}]}}]}}]} as unknown as DocumentNode<ItemPreviewsQuery, ItemPreviewsQueryVariables>;
+export const RegisteredWorkDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"RegisteredWork"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"accountIds"}},"type":{"kind":"NonNullType","type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"ID"}}}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"user"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"registeredWork"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"accountIds"},"value":{"kind":"Variable","name":{"kind":"Name","value":"accountIds"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"RegisteredWorkEntryFields"}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"RegisteredWorkEntryFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlRegisteredWork"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"accountId"}},{"kind":"Field","name":{"kind":"Name","value":"registeredAt"}},{"kind":"Field","name":{"kind":"Name","value":"session"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"sessionName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"turnState"}},{"kind":"Field","name":{"kind":"Name","value":"pullRequestUrl"}}]}}]}}]} as unknown as DocumentNode<RegisteredWorkQuery, RegisteredWorkQueryVariables>;
+export const RegisteredWorkUpdatesDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"subscription","name":{"kind":"Name","value":"RegisteredWorkUpdates"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"accountIds"}},"type":{"kind":"NonNullType","type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"ID"}}}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"registeredWorkUpdates"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"accountIds"},"value":{"kind":"Variable","name":{"kind":"Name","value":"accountIds"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlRegisteredWorkUpsert"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"entry"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"RegisteredWorkEntryFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlRegisteredWorkRemove"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"registrationId"},"name":{"kind":"Name","value":"id"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlRegisteredWorkInvalidate"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"refresh"}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"RegisteredWorkEntryFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlRegisteredWork"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"accountId"}},{"kind":"Field","name":{"kind":"Name","value":"registeredAt"}},{"kind":"Field","name":{"kind":"Name","value":"session"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"sessionName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"turnState"}},{"kind":"Field","name":{"kind":"Name","value":"pullRequestUrl"}}]}}]}}]} as unknown as DocumentNode<RegisteredWorkUpdatesSubscription, RegisteredWorkUpdatesSubscriptionVariables>;
export const SavedViewsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"SavedViews"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"kind"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"first"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"after"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"user"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"savedViews"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"kind"},"value":{"kind":"Variable","name":{"kind":"Name","value":"kind"}}},{"kind":"Argument","name":{"kind":"Name","value":"first"},"value":{"kind":"Variable","name":{"kind":"Name","value":"first"}}},{"kind":"Argument","name":{"kind":"Name","value":"after"},"value":{"kind":"Variable","name":{"kind":"Name","value":"after"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"nodes"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SavedViewFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"nextCursor"}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SavedViewFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSavedView"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"config"}},{"kind":"Field","name":{"kind":"Name","value":"sharedTeamId"}},{"kind":"Field","name":{"kind":"Name","value":"revision"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]} as unknown as DocumentNode<SavedViewsQuery, SavedViewsQueryVariables>;
export const SavedViewDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"SavedView"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"id"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"ID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"user"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"savedView"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"id"},"value":{"kind":"Variable","name":{"kind":"Name","value":"id"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SavedViewFields"}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SavedViewFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSavedView"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"config"}},{"kind":"Field","name":{"kind":"Name","value":"sharedTeamId"}},{"kind":"Field","name":{"kind":"Name","value":"revision"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]} as unknown as DocumentNode<SavedViewQuery, SavedViewQueryVariables>;
export const CreateSavedViewDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"CreateSavedView"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"CreateSavedViewInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"createSavedView"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SavedViewFields"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SavedViewFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSavedView"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"config"}},{"kind":"Field","name":{"kind":"Name","value":"sharedTeamId"}},{"kind":"Field","name":{"kind":"Name","value":"revision"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]} as unknown as DocumentNode<CreateSavedViewMutation, CreateSavedViewMutationVariables>;
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql/registered-work.graphql b/apps/web/src/lib/service-clients/service-storage/graphql/registered-work.graphql
new file mode 100644
index 0000000000..99cd121776
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/graphql/registered-work.graphql
@@ -0,0 +1,38 @@
+fragment RegisteredWorkEntryFields on GraphqlRegisteredWork {
+ id
+ accountId
+ registeredAt
+ session {
+ id
+ sessionName: name
+ turnState
+ pullRequestUrl
+ }
+}
+
+query RegisteredWork($accountIds: [ID!]!) {
+ user {
+ id
+ registeredWork(accountIds: $accountIds) {
+ ...RegisteredWorkEntryFields
+ }
+ }
+}
+
+# Start this before fetching, and fetch again after an invalidation.
+subscription RegisteredWorkUpdates($accountIds: [ID!]!) {
+ registeredWorkUpdates(accountIds: $accountIds) {
+ __typename
+ ... on GraphqlRegisteredWorkUpsert {
+ entry {
+ ...RegisteredWorkEntryFields
+ }
+ }
+ ... on GraphqlRegisteredWorkRemove {
+ registrationId: id
+ }
+ ... on GraphqlRegisteredWorkInvalidate {
+ refresh
+ }
+ }
+}
diff --git a/crates/agent_session/AGENTS.md b/crates/agent_session/AGENTS.md
index 448a0b34b5..9bca45cd1c 100644
--- a/crates/agent_session/AGENTS.md
+++ b/crates/agent_session/AGENTS.md
@@ -39,7 +39,8 @@ consumer talks to.
`macro_authorization`.
- Used by: `agent_harness`, `agent_inmem`, `agent_egress`, `agent_trigger`,
`agent_changes`, `agent_session_realtime`, `ai_tools` (coding-agent
- toolset), `complete_graph`, `webhook`, `search_service`, `soup_realtime`,
+ toolset), `complete_graph`, `graphql_registered_work`, `webhook`,
+ `search_service`, `soup_realtime`,
and the cloud-agent crates (`cursor_cloud_agents`, `codex_cloud_agents`).
## Recipes
@@ -95,6 +96,19 @@ restore, so a session auto-archives at most once. A session archives for pull
requests once every linked pull request is closed and at least one merged;
links with no `github_pull_request` row count as open.
+Registered work (`domain/work_registration.rs`, `outbound/postgres/work_registration.rs`,
+`inbound/axum_router/work_registration.rs`, `inbound/work_registration_sweep.rs`): any account
+registers a session it can edit as its work; registering shares nothing, and readers see only
+sessions they can view. Rows in `work_registration` end, never delete, and a later turn does
+not bring one back. Finished pull requests end them from the pull request consumer regardless
+of auto-archive preferences; every archive path ends them in its own transaction, so a new
+archive path must call `end_work_registrations_on_archive`; the sweep ends idle and blocked
+sessions and catches up on the rest, in one guarded statement that is safe across replicas.
+`WorkRegistrationRealtime` wraps a session service's realtime so turn, rename, and archive
+changes reach viewers of registered sessions as Soup patches
+(`soup_realtime::outbound::agent_sessions::SoupWorkRegistrationSignal`); wrap any new
+publisher of list-field changes. GraphQL is `graphql_registered_work`.
+
Followers: a session started from a thread (`SessionPurpose::visibility`, any
agent) is `hidden`. The harness calls `add_follower` beside `set_turn_prompter`
for a prompt typed into the session itself (`QueuedEntry::direct_prompter`: a
diff --git a/crates/agent_session/Cargo.toml b/crates/agent_session/Cargo.toml
index 9f63c19f84..4e62e1bf4e 100644
--- a/crates/agent_session/Cargo.toml
+++ b/crates/agent_session/Cargo.toml
@@ -89,6 +89,7 @@ macro_authorization = { path = "../macro_authorization", default-features = fals
macro_user_id = { path = "../macro_user_id" }
utoipa = { workspace = true, optional = true }
rootcause = { workspace = true }
+futures = { workspace = true }
reqwest = { workspace = true, optional = true }
macro_tower_layers = { path = "../macro_tower_layers", optional = true }
uuid = { workspace = true }
diff --git a/crates/agent_session/src/domain/auto_archive.rs b/crates/agent_session/src/domain/auto_archive.rs
index 9168576a9d..94ffc5e8ea 100644
--- a/crates/agent_session/src/domain/auto_archive.rs
+++ b/crates/agent_session/src/domain/auto_archive.rs
@@ -269,7 +269,9 @@ where
}
}
-fn session_id<T: RequiredPermission>(access: &EntityAccessReceipt<T>) -> Result<AgentSessionId> {
+pub(super) fn session_id<T: RequiredPermission>(
+ access: &EntityAccessReceipt<T>,
+) -> Result<AgentSessionId> {
if access.entity().entity_type != EntityType::AgentSession {
return Err(AgentSessionError::Forbidden);
}
diff --git a/crates/agent_session/src/domain/mod.rs b/crates/agent_session/src/domain/mod.rs
index 9034c6bcce..dc74d9bd1b 100644
--- a/crates/agent_session/src/domain/mod.rs
+++ b/crates/agent_session/src/domain/mod.rs
@@ -56,3 +56,6 @@ pub mod tool_actions;
/// Durable system notifications.
pub mod notifications;
+
+/// Sessions registered as an account's work.
+pub mod work_registration;
diff --git a/crates/agent_session/src/domain/work_registration.rs b/crates/agent_session/src/domain/work_registration.rs
new file mode 100644
index 0000000000..88515db253
--- /dev/null
+++ b/crates/agent_session/src/domain/work_registration.rs
@@ -0,0 +1,602 @@
+//! An account registering an agent session as its work, so viewers of that account see it.
+//!
+//! Any account may register a session it can edit. Registering shares nothing: a viewer sees a
+//! registration only while the viewer can view its session, and registrations of archived
+//! sessions are never read. Registrations end on their own (see [`WorkEndReason`]); ending keeps
+//! the row, and a later turn does not bring it back.
+
+use std::collections::HashSet;
+use std::sync::Arc;
+use std::time::Duration;
+
+use chrono::{DateTime, Utc};
+use entity_access::domain::models::{EditAccessLevel, EntityAccessReceipt};
+use futures::{StreamExt as _, stream};
+use macro_user_id::user_id::MacroUserIdStr;
+use macro_uuid::Uuid;
+use rootcause::Report;
+use tokio_util::task::TaskTracker;
+use tracing::Instrument as _;
+
+use super::auto_archive::session_id;
+use super::error::Result;
+use super::model::{AgentSessionId, AgentSessionRenamed, LogAppended};
+use super::ports::{AgentSessionQueueChanged, AgentSessionRealtime, SessionViewAccess};
+
+#[cfg(test)]
+mod test;
+
+/// How long a session sits without work, on a turn that is not blocked, before its registrations
+/// end. A failed turn counts: nothing more will happen until someone acts.
+const IDLE_AFTER: Duration = Duration::from_secs(24 * 60 * 60);
+
+/// How long a session waits on a blocked turn before its registrations end.
+const BLOCKED_AFTER: Duration = Duration::from_secs(7 * 24 * 60 * 60);
+
+/// Registrations one sweep ends. A full batch sweeps again right away.
+pub const SWEEP_BATCH: u32 = 500;
+
+/// Most registrations one read returns, newest first.
+const MAX_REGISTRATIONS_READ: u32 = 200;
+
+/// Access checks one read runs at a time.
+const ACCESS_CHECK_CONCURRENCY: usize = 16;
+
+/// How long after a registration ends a change to its session still reports it. Covers a change
+/// signal travelling behind the write that ended the registration.
+pub const ENDED_REPORT_WINDOW: chrono::Duration = chrono::Duration::minutes(5);
+
+/// Identifies one registration, active or ended.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub struct WorkRegistrationId(Uuid);
+
+impl WorkRegistrationId {
+ /// A new id, sorting by creation time.
+ #[must_use]
+ pub fn generate() -> Self {
+ Self(macro_uuid::generate_uuid_v7())
+ }
+
+ /// The id of a stored registration.
+ #[must_use]
+ pub fn new_from_uuid(id: Uuid) -> Self {
+ Self(id)
+ }
+
+ /// The id's uuid.
+ #[must_use]
+ pub fn as_uuid(&self) -> Uuid {
+ self.0
+ }
+}
+
+impl std::fmt::Display for WorkRegistrationId {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ self.0.fmt(f)
+ }
+}
+
+/// Why a registration ended.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, strum::AsRefStr, strum::EnumString)]
+#[strum(serialize_all = "snake_case")]
+pub enum WorkEndReason {
+ /// The account unregistered it.
+ Unregistered,
+ /// Every pull request linked to the session is merged or closed, and at least one exists.
+ PullRequestFinished,
+ /// The session was archived, whatever archived it.
+ SessionArchived,
+ /// The session has not worked for [`IDLE_AFTER`] and its turn is not blocked.
+ Idle,
+ /// The session's turn has been blocked for [`BLOCKED_AFTER`].
+ BlockedTimeout,
+}
+
+/// One account's registration of one session as its work.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct WorkRegistration {
+ /// The registration.
+ pub id: WorkRegistrationId,
+ /// The account whose work this is.
+ pub account_id: MacroUserIdStr<'static>,
+ /// The session registered.
+ pub session: AgentSessionId,
+ /// When the account registered it.
+ pub registered_at: DateTime<Utc>,
+}
+
+/// The outcome of asking to register a session.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Registered {
+ /// The account's active registration of the session.
+ pub registration: WorkRegistration,
+ /// Whether this call created it, rather than finding it active.
+ pub created: bool,
+}
+
+/// What a registration's row says about it, for reporting a change to its session.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct WorkRegistrationState {
+ /// The registration.
+ pub registration: WorkRegistration,
+ /// Whether it has ended.
+ pub ended: bool,
+ /// Whether its session is archived.
+ pub session_archived: bool,
+}
+
+/// A registration ended by a sweep.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct EndedRegistration {
+ /// The session it registered.
+ pub session: AgentSessionId,
+ /// Why it ended.
+ pub reason: WorkEndReason,
+}
+
+/// What a sweep did, by reason.
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct WorkRegistrationSweepReport {
+ /// Ended because the session's pull requests finished.
+ pub pull_request_finished: u32,
+ /// Ended because the session was archived.
+ pub session_archived: u32,
+ /// Ended because the session went idle.
+ pub idle: u32,
+ /// Ended because the session stayed blocked.
+ pub blocked_timeout: u32,
+}
+
+impl WorkRegistrationSweepReport {
+ /// How many registrations the sweep ended.
+ #[must_use]
+ pub fn total(&self) -> u32 {
+ self.pull_request_finished + self.session_archived + self.idle + self.blocked_timeout
+ }
+}
+
+/// What changed for a viewer watching some accounts, after some sessions changed.
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+pub struct WorkRegistrationChanges {
+ /// Registrations the viewer sees, with their sessions possibly changed.
+ pub active: Vec<WorkRegistration>,
+ /// Registrations the viewer saw that ended or whose session was archived.
+ pub removed: Vec<WorkRegistrationId>,
+ /// The viewer cannot view a session with registrations: it may hold entries it should not
+ /// see any more, and nothing about them may be named to it. It must refetch.
+ pub refetch: bool,
+}
+
+/// Storage for registrations. Every write is safe to repeat and across replicas.
+pub trait WorkRegistrationRepo: Clone + Send + Sync + 'static {
+ /// Register `session` for `account`, or find its active registration. Refuses a session that
+ /// is missing or archived, atomically with an archive ending the session's registrations.
+ fn register(
+ &self,
+ account: &MacroUserIdStr<'static>,
+ session: AgentSessionId,
+ ) -> impl Future<Output = Result<Registered>> + Send;
+
+ /// End `account`'s active registration of `session`. Whether there was one.
+ fn unregister(
+ &self,
+ account: &MacroUserIdStr<'static>,
+ session: AgentSessionId,
+ ) -> impl Future<Output = Result<bool>> + Send;
+
+ /// Active registrations of `accounts` on unarchived sessions, newest first, at most `limit`.
+ fn active_registrations(
+ &self,
+ accounts: &[MacroUserIdStr<'static>],
+ limit: u32,
+ ) -> impl Future<Output = Result<Vec<WorkRegistration>>> + Send;
+
+ /// Registrations of `accounts` on `sessions` that are active or ended after `ended_after`.
+ fn registration_states(
+ &self,
+ accounts: &[MacroUserIdStr<'static>],
+ sessions: &[AgentSessionId],
+ ended_after: DateTime<Utc>,
+ ) -> impl Future<Output = Result<Vec<WorkRegistrationState>>> + Send;
+
+ /// Whether `session` has a registration that is active or ended after `ended_after`.
+ fn has_current_registrations(
+ &self,
+ session: AgentSessionId,
+ ended_after: DateTime<Utc>,
+ ) -> impl Future<Output = Result<bool>> + Send;
+
+ /// End active registrations of the sessions linked to `github_key` whose linked pull requests
+ /// are now all merged or closed. The sessions whose registrations ended.
+ fn end_for_finished_pull_requests(
+ &self,
+ github_key: &str,
+ ) -> impl Future<Output = Result<Vec<AgentSessionId>>> + Send;
+
+ /// End up to `limit` active registrations that are due, each for the first reason that
+ /// applies: finished pull requests, an archived session, then a blocked turn not worked on
+ /// since `blocked_before` or any other turn not worked on since `idle_before`.
+ fn end_due_registrations(
+ &self,
+ idle_before: DateTime<Utc>,
+ blocked_before: DateTime<Utc>,
+ limit: u32,
+ ) -> impl Future<Output = Result<Vec<EndedRegistration>>> + Send;
+}
+
+/// Tells viewers of a session that its registrations or its list fields changed.
+pub trait WorkRegistrationSignal: Clone + Send + Sync + 'static {
+ /// Best effort: a viewer that misses a signal catches up when it next refetches.
+ fn session_changed(
+ &self,
+ session: AgentSessionId,
+ ) -> impl Future<Output = std::result::Result<(), Report>> + Send;
+}
+
+/// For a process that only reads registrations and so changes nothing to tell viewers about.
+#[derive(Debug, Clone, Copy, Default)]
+pub struct NoWorkRegistrationSignal;
+
+impl WorkRegistrationSignal for NoWorkRegistrationSignal {
+ async fn session_changed(&self, _session: AgentSessionId) -> std::result::Result<(), Report> {
+ Ok(())
+ }
+}
+
+/// Registering work, reading it, and ending it.
+pub trait WorkRegistrations: Send + Sync + 'static {
+ /// Register the session `access` covers as `account`'s work. Repeating returns the active
+ /// registration.
+ fn register(
+ &self,
+ access: &EntityAccessReceipt<EditAccessLevel>,
+ account: &MacroUserIdStr<'static>,
+ ) -> impl Future<Output = Result<WorkRegistration>> + Send;
+
+ /// End `account`'s own registration of `session`. Repeating does nothing.
+ fn unregister(
+ &self,
+ account: &MacroUserIdStr<'static>,
+ session: AgentSessionId,
+ ) -> impl Future<Output = Result<()>> + Send;
+
+ /// Active registrations of `accounts` that `viewer` can see, newest first.
+ fn visible_registrations(
+ &self,
+ viewer: &MacroUserIdStr<'static>,
+ accounts: &[MacroUserIdStr<'static>],
+ ) -> impl Future<Output = Result<Vec<WorkRegistration>>> + Send;
+
+ /// What `sessions` changing means for `viewer` watching `accounts`, reporting registrations
+ /// that ended after `ended_after`.
+ fn changes(
+ &self,
+ viewer: &MacroUserIdStr<'static>,
+ accounts: &[MacroUserIdStr<'static>],
+ sessions: &[AgentSessionId],
+ ended_after: DateTime<Utc>,
+ ) -> impl Future<Output = Result<WorkRegistrationChanges>> + Send;
+
+ /// The pull request `github_key` changed: end registrations of sessions whose pull requests
+ /// are now all finished. Safe to repeat.
+ fn pull_request_changed(&self, github_key: &str) -> impl Future<Output = Result<()>> + Send;
+
+ /// End one batch of registrations that are due. Safe to repeat and across replicas.
+ fn sweep(&self) -> impl Future<Output = Result<WorkRegistrationSweepReport>> + Send;
+}
+
+/// Work registrations over the session store.
+#[derive(Clone)]
+pub struct WorkRegistrationService<R, S> {
+ repo: R,
+ view_access: Arc<dyn SessionViewAccess>,
+ signal: S,
+}
+
+impl<R, S> WorkRegistrationService<R, S> {
+ /// Build the service over the store, current view access, and the viewer signal.
+ pub fn new(repo: R, view_access: Arc<dyn SessionViewAccess>, signal: S) -> Self {
+ Self {
+ repo,
+ view_access,
+ signal,
+ }
+ }
+}
+
+impl<R, S> WorkRegistrationService<R, S>
+where
+ R: WorkRegistrationRepo,
+ S: WorkRegistrationSignal,
+{
+ async fn tell_viewers(&self, session: AgentSessionId) {
+ self.signal
+ .session_changed(session)
+ .await
+ .inspect_err(|error| {
+ tracing::warn!(error = ?error, %session, "failed to signal a work registration change");
+ })
+ .ok();
+ }
+
+ /// The sessions among `sessions` that `viewer` can view. A failed check hides the session:
+ /// one bad lookup must not fail the read or show what may not be visible.
+ async fn viewable_sessions(
+ &self,
+ viewer: &MacroUserIdStr<'static>,
+ sessions: HashSet<AgentSessionId>,
+ ) -> HashSet<AgentSessionId> {
+ stream::iter(sessions)
+ .map(|session| async move {
+ let viewable = self
+ .view_access
+ .can_view(viewer, session)
+ .await
+ .inspect_err(|error| {
+ tracing::warn!(error = ?error, %session, "failed to check session view access");
+ })
+ .unwrap_or(false);
+ viewable.then_some(session)
+ })
+ .buffer_unordered(ACCESS_CHECK_CONCURRENCY)
+ .filter_map(std::future::ready)
+ .collect()
+ .await
+ }
+}
+
+impl<R, S> WorkRegistrations for WorkRegistrationService<R, S>
+where
+ R: WorkRegistrationRepo,
+ S: WorkRegistrationSignal,
+{
+ #[tracing::instrument(
+ name = "agent_session.work_registration.register",
+ err,
+ skip_all,
+ fields(agent.session.id, created)
+ )]
+ async fn register(
+ &self,
+ access: &EntityAccessReceipt<EditAccessLevel>,
+ account: &MacroUserIdStr<'static>,
+ ) -> Result<WorkRegistration> {
+ let session = session_id(access)?;
+ tracing::Span::current().record("agent.session.id", tracing::field::display(session));
+ let registered = self.repo.register(account, session).await?;
+ tracing::Span::current().record("created", registered.created);
+ if registered.created {
+ self.tell_viewers(session).await;
+ }
+ Ok(registered.registration)
+ }
+
+ #[tracing::instrument(
+ name = "agent_session.work_registration.unregister",
+ err,
+ skip(self, account),
+ fields(ended)
+ )]
+ async fn unregister(
+ &self,
+ account: &MacroUserIdStr<'static>,
+ session: AgentSessionId,
+ ) -> Result<()> {
+ let ended = self.repo.unregister(account, session).await?;
+ tracing::Span::current().record("ended", ended);
+ if ended {
+ self.tell_viewers(session).await;
+ }
+ Ok(())
+ }
+
+ async fn visible_registrations(
+ &self,
+ viewer: &MacroUserIdStr<'static>,
+ accounts: &[MacroUserIdStr<'static>],
+ ) -> Result<Vec<WorkRegistration>> {
+ let mut registrations = self
+ .repo
+ .active_registrations(accounts, MAX_REGISTRATIONS_READ)
+ .await?;
+ let sessions = registrations.iter().map(|row| row.session).collect();
+ let viewable = self.viewable_sessions(viewer, sessions).await;
+ registrations.retain(|registration| viewable.contains(&registration.session));
+ Ok(registrations)
+ }
+
+ async fn changes(
+ &self,
+ viewer: &MacroUserIdStr<'static>,
+ accounts: &[MacroUserIdStr<'static>],
+ sessions: &[AgentSessionId],
+ ended_after: DateTime<Utc>,
+ ) -> Result<WorkRegistrationChanges> {
+ let states = self
+ .repo
+ .registration_states(accounts, sessions, ended_after)
+ .await?;
+ let touched = states.iter().map(|state| state.registration.session);
+ let viewable = self.viewable_sessions(viewer, touched.collect()).await;
+
+ let mut changes = WorkRegistrationChanges::default();
+ for state in states {
+ if !viewable.contains(&state.registration.session) {
+ changes.refetch = true;
+ } else if state.ended || state.session_archived {
+ changes.removed.push(state.registration.id);
+ } else {
+ changes.active.push(state.registration);
+ }
+ }
+ Ok(changes)
+ }
+
+ #[tracing::instrument(
+ name = "agent_session.work_registration.pull_request",
+ err,
+ skip_all,
+ fields(ended)
+ )]
+ async fn pull_request_changed(&self, github_key: &str) -> Result<()> {
+ let sessions = self.repo.end_for_finished_pull_requests(github_key).await?;
+ tracing::Span::current().record("ended", sessions.len());
+ let distinct: HashSet<_> = sessions.into_iter().collect();
+ for session in distinct {
+ self.tell_viewers(session).await;
+ }
+ Ok(())
+ }
+
+ #[tracing::instrument(
+ name = "agent_session.work_registration.sweep",
+ err,
+ skip_all,
+ fields(ended, pull_request_finished, session_archived, idle, blocked_timeout)
+ )]
+ async fn sweep(&self) -> Result<WorkRegistrationSweepReport> {
+ let now = Utc::now();
+ let idle_before = before(now, IDLE_AFTER)?;
+ let blocked_before = before(now, BLOCKED_AFTER)?;
+ let ended = self
+ .repo
+ .end_due_registrations(idle_before, blocked_before, SWEEP_BATCH)
+ .await?;
+
+ let report = report_of(&ended);
+ let span = tracing::Span::current();
+ span.record("ended", report.total());
+ span.record("pull_request_finished", report.pull_request_finished);
+ span.record("session_archived", report.session_archived);
+ span.record("idle", report.idle);
+ span.record("blocked_timeout", report.blocked_timeout);
+
+ let distinct: HashSet<_> = ended.iter().map(|row| row.session).collect();
+ for session in distinct {
+ self.tell_viewers(session).await;
+ }
+ Ok(report)
+ }
+}
+
+fn before(now: DateTime<Utc>, age: Duration) -> Result<DateTime<Utc>> {
+ let age = chrono::Duration::from_std(age)
+ .map_err(|error| anyhow::anyhow!("work registration age out of range: {error}"))?;
+ Ok(now - age)
+}
+
+fn report_of(ended: &[EndedRegistration]) -> WorkRegistrationSweepReport {
+ let mut report = WorkRegistrationSweepReport::default();
+ for row in ended {
+ match row.reason {
+ WorkEndReason::PullRequestFinished => report.pull_request_finished += 1,
+ WorkEndReason::SessionArchived => report.session_archived += 1,
+ WorkEndReason::Idle => report.idle += 1,
+ WorkEndReason::BlockedTimeout => report.blocked_timeout += 1,
+ // Only an account unregistering ends a registration for this reason; a sweep never does.
+ WorkEndReason::Unregistered => {}
+ }
+ }
+ report
+}
+
+/// [`AgentSessionRealtime`] that also tells viewers of registered work when a session's list
+/// fields change. Log frames change no list field and only pass through.
+///
+/// The signal runs off the caller's task on tasks tracked by `tasks`: session log writes publish
+/// through here, and a session with no registrations must cost them nothing.
+#[derive(Clone)]
+pub struct WorkRegistrationRealtime<Inner, R, S> {
+ inner: Inner,
+ repo: R,
+ signal: S,
+ tasks: TaskTracker,
+}
+
+impl<Inner, R, S> WorkRegistrationRealtime<Inner, R, S> {
+ /// Publish through `inner`, then signal through `signal` for sessions `repo` has
+ /// registrations of.
+ pub fn new(inner: Inner, repo: R, signal: S, tasks: TaskTracker) -> Self {
+ Self {
+ inner,
+ repo,
+ signal,
+ tasks,
+ }
+ }
+}
+
+impl<Inner, R, S> WorkRegistrationRealtime<Inner, R, S>
+where
+ R: WorkRegistrationRepo,
+ S: WorkRegistrationSignal,
+{
+ fn signal_registered(&self, session: AgentSessionId) {
+ let repo = self.repo.clone();
+ let signal = self.signal.clone();
+ self.tasks.spawn(
+ async move {
+ let ended_after = Utc::now() - ENDED_REPORT_WINDOW;
+ let registered = repo
+ .has_current_registrations(session, ended_after)
+ .await
+ .inspect_err(|error| {
+ tracing::warn!(error = ?error, %session, "failed to look up work registrations");
+ })
+ .unwrap_or(false);
+ if !registered {
+ return;
+ }
+ signal
+ .session_changed(session)
+ .await
+ .inspect_err(|error| {
+ tracing::warn!(error = ?error, %session, "failed to signal a work registration change");
+ })
+ .ok();
+ }
+ .in_current_span(),
+ );
+ }
+}
+
+impl<Inner, R, S> AgentSessionRealtime for WorkRegistrationRealtime<Inner, R, S>
+where
+ Inner: AgentSessionRealtime + Sync,
+ R: WorkRegistrationRepo,
+ S: WorkRegistrationSignal,
+{
+ fn publish(
+ &self,
+ event: LogAppended,
+ ) -> impl Future<Output = std::result::Result<(), Report>> + Send {
+ self.inner.publish(event)
+ }
+
+ async fn publish_updated(&self, session: AgentSessionId) -> std::result::Result<(), Report> {
+ let published = self.inner.publish_updated(session).await;
+ self.signal_registered(session);
+ published
+ }
+
+ async fn publish_renamed(&self, event: AgentSessionRenamed) -> std::result::Result<(), Report> {
+ let session = event.agent_session_id;
+ let published = self.inner.publish_renamed(event).await;
+ self.signal_registered(session);
+ published
+ }
+
+ fn publish_queue_changed(
+ &self,
+ event: AgentSessionQueueChanged,
+ ) -> impl Future<Output = std::result::Result<(), Report>> + Send {
+ self.inner.publish_queue_changed(event)
+ }
+
+ fn publish_changes_updated(
+ &self,
+ session: AgentSessionId,
+ ) -> impl Future<Output = std::result::Result<(), Report>> + Send {
+ self.inner.publish_changes_updated(session)
+ }
+}
diff --git a/crates/agent_session/src/domain/work_registration/test.rs b/crates/agent_session/src/domain/work_registration/test.rs
new file mode 100644
index 0000000000..cca6739139
--- /dev/null
+++ b/crates/agent_session/src/domain/work_registration/test.rs
@@ -0,0 +1,347 @@
+use std::sync::Mutex;
+
+use entity_access::domain::models::{Entity, EntityPermission, EntityType};
+use models_permissions::share_permission::access_level::AccessLevel;
+
+use super::*;
+use crate::domain::ports::SessionViewAccess;
+
+fn account(value: &str) -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from(value.to_string()).unwrap()
+}
+
+fn registration_of(session: AgentSessionId, owner: &str) -> WorkRegistration {
+ WorkRegistration {
+ id: WorkRegistrationId::generate(),
+ account_id: account(owner),
+ session,
+ registered_at: Utc::now(),
+ }
+}
+
+fn edit_access(session: AgentSessionId) -> EntityAccessReceipt<EditAccessLevel> {
+ EntityAccessReceipt::try_new_authenticated_user(
+ account("macro|[email protected]"),
+ Entity {
+ entity_id: session.to_string(),
+ entity_type: EntityType::AgentSession,
+ },
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::Edit,
+ },
+ )
+ .unwrap()
+}
+
+#[derive(Clone, Default)]
+struct FakeRepo {
+ created: bool,
+ unregistered: bool,
+ active: Vec<WorkRegistration>,
+ states: Vec<WorkRegistrationState>,
+ due: Vec<EndedRegistration>,
+ finished: Vec<AgentSessionId>,
+}
+
+impl WorkRegistrationRepo for FakeRepo {
+ async fn register(
+ &self,
+ account: &MacroUserIdStr<'static>,
+ session: AgentSessionId,
+ ) -> Result<Registered> {
+ Ok(Registered {
+ registration: registration_of(session, account.as_ref()),
+ created: self.created,
+ })
+ }
+
+ async fn unregister(
+ &self,
+ _account: &MacroUserIdStr<'static>,
+ _session: AgentSessionId,
+ ) -> Result<bool> {
+ Ok(self.unregistered)
+ }
+
+ async fn active_registrations(
+ &self,
+ _accounts: &[MacroUserIdStr<'static>],
+ _limit: u32,
+ ) -> Result<Vec<WorkRegistration>> {
+ Ok(self.active.clone())
+ }
+
+ async fn registration_states(
+ &self,
+ _accounts: &[MacroUserIdStr<'static>],
+ _sessions: &[AgentSessionId],
+ _ended_after: DateTime<Utc>,
+ ) -> Result<Vec<WorkRegistrationState>> {
+ Ok(self.states.clone())
+ }
+
+ async fn has_current_registrations(
+ &self,
+ _session: AgentSessionId,
+ _ended_after: DateTime<Utc>,
+ ) -> Result<bool> {
+ Ok(true)
+ }
+
+ async fn end_for_finished_pull_requests(
+ &self,
+ _github_key: &str,
+ ) -> Result<Vec<AgentSessionId>> {
+ Ok(self.finished.clone())
+ }
+
+ async fn end_due_registrations(
+ &self,
+ _idle_before: DateTime<Utc>,
+ _blocked_before: DateTime<Utc>,
+ _limit: u32,
+ ) -> Result<Vec<EndedRegistration>> {
+ Ok(self.due.clone())
+ }
+}
+
+#[derive(Clone, Default)]
+struct RecordingSignal(Arc<Mutex<Vec<AgentSessionId>>>);
+
+impl RecordingSignal {
+ fn signalled(&self) -> Vec<AgentSessionId> {
+ self.0.lock().unwrap().clone()
+ }
+}
+
+impl WorkRegistrationSignal for RecordingSignal {
+ async fn session_changed(&self, session: AgentSessionId) -> std::result::Result<(), Report> {
+ self.0.lock().unwrap().push(session);
+ Ok(())
+ }
+}
+
+/// Answers from a fixed set; a session in `failing` fails the lookup.
+struct ViewableSessions {
+ viewable: Vec<AgentSessionId>,
+ failing: Vec<AgentSessionId>,
+}
+
+impl SessionViewAccess for ViewableSessions {
+ fn can_view<'a>(
+ &'a self,
+ _viewer: &'a MacroUserIdStr<'static>,
+ session: AgentSessionId,
+ ) -> std::pin::Pin<Box<dyn Future<Output = Result<bool>> + Send + 'a>> {
+ Box::pin(async move {
+ if self.failing.contains(&session) {
+ return Err(anyhow::anyhow!("access service unavailable").into());
+ }
+ Ok(self.viewable.contains(&session))
+ })
+ }
+}
+
+fn service(
+ repo: FakeRepo,
+ viewable: Vec<AgentSessionId>,
+) -> (
+ WorkRegistrationService<FakeRepo, RecordingSignal>,
+ RecordingSignal,
+) {
+ let signal = RecordingSignal::default();
+ let access = Arc::new(ViewableSessions {
+ viewable,
+ failing: Vec::new(),
+ });
+ (
+ WorkRegistrationService::new(repo, access, signal.clone()),
+ signal,
+ )
+}
+
+#[tokio::test]
+async fn registering_tells_viewers_only_when_it_created_the_registration() {
+ let session = AgentSessionId::new();
+ let caller = account("macro|[email protected]");
+
+ let (created, signal) = service(
+ FakeRepo {
+ created: true,
+ ..FakeRepo::default()
+ },
+ Vec::new(),
+ );
+ created
+ .register(&edit_access(session), &caller)
+ .await
+ .unwrap();
+ assert_eq!(signal.signalled(), vec![session]);
+
+ let (repeated, signal) = service(FakeRepo::default(), Vec::new());
+ repeated
+ .register(&edit_access(session), &caller)
+ .await
+ .unwrap();
+ assert_eq!(signal.signalled(), Vec::new());
+}
+
+#[tokio::test]
+async fn unregistering_tells_viewers_only_when_it_ended_something() {
+ let session = AgentSessionId::new();
+ let caller = account("macro|[email protected]");
+
+ let (ended, signal) = service(
+ FakeRepo {
+ unregistered: true,
+ ..FakeRepo::default()
+ },
+ Vec::new(),
+ );
+ ended.unregister(&caller, session).await.unwrap();
+ assert_eq!(signal.signalled(), vec![session]);
+
+ let (repeated, signal) = service(FakeRepo::default(), Vec::new());
+ repeated.unregister(&caller, session).await.unwrap();
+ assert_eq!(signal.signalled(), Vec::new());
+}
+
+#[tokio::test]
+async fn a_viewer_reads_only_registrations_of_sessions_it_can_view() {
+ let viewable = AgentSessionId::new();
+ let hidden = AgentSessionId::new();
+ let failing = AgentSessionId::new();
+ let shown = registration_of(viewable, "macro|[email protected]");
+ let repo = FakeRepo {
+ active: vec![
+ registration_of(hidden, "macro|[email protected]"),
+ shown.clone(),
+ registration_of(failing, "macro|[email protected]"),
+ ],
+ ..FakeRepo::default()
+ };
+ let access = Arc::new(ViewableSessions {
+ viewable: vec![viewable],
+ failing: vec![failing],
+ });
+ let service = WorkRegistrationService::new(repo, access, RecordingSignal::default());
+
+ let visible = service
+ .visible_registrations(
+ &account("macro|[email protected]"),
+ &[account("macro|[email protected]")],
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(visible, vec![shown]);
+}
+
+#[tokio::test]
+async fn changes_name_only_what_the_viewer_can_view_and_refetch_for_the_rest() {
+ let viewable = AgentSessionId::new();
+ let hidden = AgentSessionId::new();
+ let active = registration_of(viewable, "macro|[email protected]");
+ let ended = registration_of(viewable, "macro|[email protected]");
+ let on_archived = registration_of(viewable, "macro|[email protected]");
+ let state = |registration: &WorkRegistration, ended: bool, session_archived: bool| {
+ WorkRegistrationState {
+ registration: registration.clone(),
+ ended,
+ session_archived,
+ }
+ };
+ let repo = FakeRepo {
+ states: vec![
+ state(&ended, true, false),
+ state(&active, false, false),
+ state(&on_archived, false, true),
+ ],
+ ..FakeRepo::default()
+ };
+ let (service, _) = service(repo, vec![viewable]);
+ let viewer = account("macro|[email protected]");
+ let accounts = [account("macro|[email protected]")];
+
+ let changes = service
+ .changes(&viewer, &accounts, &[viewable], Utc::now())
+ .await
+ .unwrap();
+ assert_eq!(
+ changes,
+ WorkRegistrationChanges {
+ active: vec![active],
+ removed: vec![ended.id, on_archived.id],
+ refetch: false,
+ }
+ );
+
+ let revoked = registration_of(hidden, "macro|[email protected]");
+ let repo = FakeRepo {
+ states: vec![state(&revoked, false, false), state(&revoked, true, false)],
+ ..FakeRepo::default()
+ };
+ let (service, _) = self::service(repo, vec![viewable]);
+ let changes = service
+ .changes(&viewer, &accounts, &[hidden], Utc::now())
+ .await
+ .unwrap();
+ assert_eq!(
+ changes,
+ WorkRegistrationChanges {
+ active: Vec::new(),
+ removed: Vec::new(),
+ refetch: true,
+ }
+ );
+}
+
+#[tokio::test]
+async fn a_sweep_counts_by_reason_and_tells_each_session_once() {
+ let first = AgentSessionId::new();
+ let second = AgentSessionId::new();
+ let ended = |session, reason| EndedRegistration { session, reason };
+ let repo = FakeRepo {
+ due: vec![
+ ended(first, WorkEndReason::Idle),
+ ended(first, WorkEndReason::Idle),
+ ended(second, WorkEndReason::BlockedTimeout),
+ ended(second, WorkEndReason::PullRequestFinished),
+ ended(second, WorkEndReason::SessionArchived),
+ ],
+ ..FakeRepo::default()
+ };
+ let (service, signal) = service(repo, Vec::new());
+
+ let report = service.sweep().await.unwrap();
+
+ assert_eq!(
+ report,
+ WorkRegistrationSweepReport {
+ pull_request_finished: 1,
+ session_archived: 1,
+ idle: 2,
+ blocked_timeout: 1,
+ }
+ );
+ let signalled = signal.signalled();
+ assert_eq!(signalled.len(), 2);
+ assert!(signalled.contains(&first) && signalled.contains(&second));
+}
+
+#[tokio::test]
+async fn a_finished_pull_request_tells_each_session_once() {
+ let session = AgentSessionId::new();
+ let repo = FakeRepo {
+ finished: vec![session, session],
+ ..FakeRepo::default()
+ };
+ let (service, signal) = service(repo, Vec::new());
+
+ service
+ .pull_request_changed("example/repo/pull/7")
+ .await
+ .unwrap();
+
+ assert_eq!(signal.signalled(), vec![session]);
+}
diff --git a/crates/agent_session/src/inbound/axum_router.rs b/crates/agent_session/src/inbound/axum_router.rs
index 45588e00e5..ead257156b 100644
--- a/crates/agent_session/src/inbound/axum_router.rs
+++ b/crates/agent_session/src/inbound/axum_router.rs
@@ -75,6 +75,9 @@ pub mod pull_requests;
/// Auto-archive defaults and per-session choices.
pub mod auto_archive;
+/// Registering sessions as an account's work.
+pub mod work_registration;
+
mod owned_purge;
/// Shared state for the agent session router: the agent session service plus
diff --git a/crates/agent_session/src/inbound/axum_router/work_registration.rs b/crates/agent_session/src/inbound/axum_router/work_registration.rs
new file mode 100644
index 0000000000..b0353b134e
--- /dev/null
+++ b/crates/agent_session/src/inbound/axum_router/work_registration.rs
@@ -0,0 +1,167 @@
+//! Thin transport adapters for registering sessions as an account's work.
+
+use axum::{
+ Json, Router,
+ extract::{Path, State},
+ http::StatusCode,
+ routing::{get, put},
+};
+use chrono::{DateTime, Utc};
+use entity_access::{
+ domain::{models::EditAccessLevel, ports::EntityAccessService},
+ inbound::axum_extractors::AgentSessionAccessLevelExtractor,
+};
+use macro_authorization::{ActingUser, MacroAuthorizationExtractor, MacroAuthorizationService};
+use serde::Serialize;
+use utoipa::ToSchema;
+
+use super::{AgentSessionApiError, AgentSessionRouterState};
+use crate::domain::model::AgentSessionId;
+use crate::domain::work_registration::{WorkRegistration, WorkRegistrations};
+
+/// The register, unregister, and list-own routes. Mount at the root.
+pub fn work_registration_router<T, Access, Auth, S>(
+ state: AgentSessionRouterState<T, Access, Auth>,
+) -> Router<S>
+where
+ T: WorkRegistrations,
+ Access: EntityAccessService,
+ Auth: MacroAuthorizationService,
+ S: Clone + Send + Sync + 'static,
+{
+ Router::new()
+ .route(
+ "/agent-sessions/{session_id}/work-registration",
+ put(register_work::<T, Access, Auth>).delete(unregister_work::<T, Access, Auth>),
+ )
+ .route(
+ "/agent-work-registrations",
+ get(list_own_work::<T, Access, Auth>),
+ )
+ .with_state(state)
+}
+
+/// One account's active registration of one session as its work.
+#[derive(Debug, Clone, Serialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct WorkRegistrationResponse {
+ /// The registration.
+ pub id: uuid::Uuid,
+ /// The account whose work this is.
+ pub account_id: String,
+ /// The session registered.
+ pub agent_session_id: uuid::Uuid,
+ /// When the account registered it.
+ pub registered_at: DateTime<Utc>,
+}
+
+impl From<WorkRegistration> for WorkRegistrationResponse {
+ fn from(registration: WorkRegistration) -> Self {
+ Self {
+ id: registration.id.as_uuid(),
+ account_id: registration.account_id.as_ref().to_owned(),
+ agent_session_id: registration.session.as_uuid(),
+ registered_at: registration.registered_at,
+ }
+ }
+}
+
+#[utoipa::path(
+ put,
+ path = "/agent-sessions/{session_id}/work-registration",
+ tag = "agent-sessions",
+ operation_id = "register_agent_session_work",
+ params(("session_id" = uuid::Uuid, Path, description = "ID of the agent session")),
+ responses(
+ (status = 200, body = WorkRegistrationResponse),
+ (status = 401, body = String),
+ (status = 403, body = String),
+ (status = 409, body = String),
+ (status = 500, body = String),
+ )
+)]
+/// Register a session as the caller's work. Requires edit access. Repeating returns the active
+/// registration. Registering does not share the session: viewers who cannot open it do not see
+/// it, so share it too.
+#[tracing::instrument(skip_all, err(Debug))]
+pub async fn register_work<
+ T: WorkRegistrations,
+ Access: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ access: AgentSessionAccessLevelExtractor<EditAccessLevel, Access, Auth>,
+ State(state): State<AgentSessionRouterState<T, Access, Auth>>,
+ caller: MacroAuthorizationExtractor<Auth, ActingUser>,
+) -> Result<Json<WorkRegistrationResponse>, AgentSessionApiError> {
+ let registration = state
+ .service
+ .register(
+ &access.entity_access_receipt,
+ &caller.authorization.user.macro_user_id,
+ )
+ .await?;
+ Ok(Json(registration.into()))
+}
+
+#[utoipa::path(
+ delete,
+ path = "/agent-sessions/{session_id}/work-registration",
+ tag = "agent-sessions",
+ operation_id = "unregister_agent_session_work",
+ params(("session_id" = uuid::Uuid, Path, description = "ID of the agent session")),
+ responses(
+ (status = 204, description = "The caller has no active registration of the session"),
+ (status = 401, body = String),
+ (status = 500, body = String),
+ )
+)]
+/// End the caller's own registration of a session. Repeating does nothing. It touches only the
+/// caller's own row, so it needs no access to the session: losing access must not strand it.
+#[tracing::instrument(skip_all, err(Debug))]
+pub async fn unregister_work<
+ T: WorkRegistrations,
+ Access: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<AgentSessionRouterState<T, Access, Auth>>,
+ caller: MacroAuthorizationExtractor<Auth, ActingUser>,
+ Path(session_id): Path<uuid::Uuid>,
+) -> Result<StatusCode, AgentSessionApiError> {
+ state
+ .service
+ .unregister(
+ &caller.authorization.user.macro_user_id,
+ AgentSessionId::new_from_uuid(session_id),
+ )
+ .await?;
+ Ok(StatusCode::NO_CONTENT)
+}
+
+#[utoipa::path(
+ get,
+ path = "/agent-work-registrations",
+ tag = "agent-sessions",
+ operation_id = "list_agent_work_registrations",
+ responses(
+ (status = 200, body = Vec<WorkRegistrationResponse>),
+ (status = 401, body = String),
+ (status = 500, body = String),
+ )
+)]
+/// List the caller's active registrations of sessions they can still view, newest first.
+#[tracing::instrument(skip_all, err(Debug))]
+pub async fn list_own_work<
+ T: WorkRegistrations,
+ Access: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<AgentSessionRouterState<T, Access, Auth>>,
+ caller: MacroAuthorizationExtractor<Auth, ActingUser>,
+) -> Result<Json<Vec<WorkRegistrationResponse>>, AgentSessionApiError> {
+ let account = &caller.authorization.user.macro_user_id;
+ let registrations = state
+ .service
+ .visible_registrations(account, std::slice::from_ref(account))
+ .await?;
+ Ok(Json(registrations.into_iter().map(Into::into).collect()))
+}
diff --git a/crates/agent_session/src/inbound/mod.rs b/crates/agent_session/src/inbound/mod.rs
index 9a256e8170..ceb7711a71 100644
--- a/crates/agent_session/src/inbound/mod.rs
+++ b/crates/agent_session/src/inbound/mod.rs
@@ -14,3 +14,6 @@ pub mod toolset;
/// Internal system event ingress.
pub mod notifications;
+
+/// The schedule ending work registrations that are due.
+pub mod work_registration_sweep;
diff --git a/crates/agent_session/src/inbound/work_registration_sweep.rs b/crates/agent_session/src/inbound/work_registration_sweep.rs
new file mode 100644
index 0000000000..9559103136
--- /dev/null
+++ b/crates/agent_session/src/inbound/work_registration_sweep.rs
@@ -0,0 +1,41 @@
+//! Runs the work registration sweep on a schedule.
+
+use std::time::Duration;
+
+use crate::domain::work_registration::{SWEEP_BATCH, WorkRegistrations};
+
+#[cfg(test)]
+mod test;
+
+/// How long after boot the first sweep runs, so a deploy's rolling restart is past first.
+pub const WORK_REGISTRATION_SWEEP_INITIAL_DELAY: Duration = Duration::from_secs(60);
+
+/// How often the sweep runs after that. The time rules are hours apart, so minutes late costs
+/// nothing.
+pub const WORK_REGISTRATION_SWEEP_INTERVAL: Duration = Duration::from_secs(5 * 60);
+
+/// Sweeps once after `initial_delay`, then every `interval`, until `shutdown` resolves. A full
+/// batch sweeps again right away. Replicas may sweep concurrently: each row ends once.
+pub async fn run_work_registration_sweep(
+ registrations: &impl WorkRegistrations,
+ initial_delay: Duration,
+ interval: Duration,
+ shutdown: impl Future<Output = ()> + Send,
+) {
+ tokio::pin!(shutdown);
+ let mut wait = initial_delay;
+ loop {
+ tokio::select! {
+ () = &mut shutdown => return,
+ () = tokio::time::sleep(wait) => {}
+ }
+ wait = match registrations.sweep().await {
+ Ok(report) if report.total() >= SWEEP_BATCH => Duration::ZERO,
+ Ok(_) => interval,
+ Err(error) => {
+ tracing::warn!(error = ?error, "work registration sweep failed");
+ interval
+ }
+ };
+ }
+}
diff --git a/crates/agent_session/src/inbound/work_registration_sweep/test.rs b/crates/agent_session/src/inbound/work_registration_sweep/test.rs
new file mode 100644
index 0000000000..65e1331061
--- /dev/null
+++ b/crates/agent_session/src/inbound/work_registration_sweep/test.rs
@@ -0,0 +1,99 @@
+use std::sync::Mutex;
+
+use chrono::{DateTime, Utc};
+use entity_access::domain::models::{EditAccessLevel, EntityAccessReceipt};
+use macro_user_id::user_id::MacroUserIdStr;
+
+use super::*;
+use crate::domain::error::Result;
+use crate::domain::model::AgentSessionId;
+use crate::domain::work_registration::{
+ WorkRegistration, WorkRegistrationChanges, WorkRegistrationSweepReport,
+};
+
+/// Hands out one scripted count per sweep, then empty sweeps.
+struct ScriptedSweeps {
+ ended: Mutex<Vec<u32>>,
+ sweeps: Mutex<Vec<tokio::time::Instant>>,
+}
+
+impl WorkRegistrations for ScriptedSweeps {
+ async fn register(
+ &self,
+ _access: &EntityAccessReceipt<EditAccessLevel>,
+ _account: &MacroUserIdStr<'static>,
+ ) -> Result<WorkRegistration> {
+ Err(crate::domain::error::AgentSessionError::Forbidden)
+ }
+
+ async fn unregister(
+ &self,
+ _account: &MacroUserIdStr<'static>,
+ _session: AgentSessionId,
+ ) -> Result<()> {
+ Ok(())
+ }
+
+ async fn visible_registrations(
+ &self,
+ _viewer: &MacroUserIdStr<'static>,
+ _accounts: &[MacroUserIdStr<'static>],
+ ) -> Result<Vec<WorkRegistration>> {
+ Ok(Vec::new())
+ }
+
+ async fn changes(
+ &self,
+ _viewer: &MacroUserIdStr<'static>,
+ _accounts: &[MacroUserIdStr<'static>],
+ _sessions: &[AgentSessionId],
+ _ended_after: DateTime<Utc>,
+ ) -> Result<WorkRegistrationChanges> {
+ Ok(WorkRegistrationChanges::default())
+ }
+
+ async fn pull_request_changed(&self, _github_key: &str) -> Result<()> {
+ Ok(())
+ }
+
+ async fn sweep(&self) -> Result<WorkRegistrationSweepReport> {
+ self.sweeps
+ .lock()
+ .unwrap()
+ .push(tokio::time::Instant::now());
+ let mut ended = self.ended.lock().unwrap();
+ let idle = if ended.is_empty() { 0 } else { ended.remove(0) };
+ Ok(WorkRegistrationSweepReport {
+ idle,
+ ..WorkRegistrationSweepReport::default()
+ })
+ }
+}
+
+#[tokio::test(start_paused = true)]
+async fn a_full_batch_sweeps_again_at_once_and_a_short_one_waits_for_the_interval() {
+ let sweeps = ScriptedSweeps {
+ ended: Mutex::new(vec![SWEEP_BATCH, 1]),
+ sweeps: Mutex::new(Vec::new()),
+ };
+ let initial_delay = Duration::from_secs(60);
+ let interval = Duration::from_secs(300);
+ let started = tokio::time::Instant::now();
+
+ run_work_registration_sweep(
+ &sweeps,
+ initial_delay,
+ interval,
+ tokio::time::sleep(initial_delay + interval + Duration::from_secs(1)),
+ )
+ .await;
+
+ assert_eq!(
+ *sweeps.sweeps.lock().unwrap(),
+ vec![
+ started + initial_delay,
+ started + initial_delay,
+ started + initial_delay + interval,
+ ]
+ );
+}
diff --git a/crates/agent_session/src/outbound/postgres.rs b/crates/agent_session/src/outbound/postgres.rs
index e0856fc432..3464e575a5 100644
--- a/crates/agent_session/src/outbound/postgres.rs
+++ b/crates/agent_session/src/outbound/postgres.rs
@@ -17,6 +17,7 @@ mod recovery;
mod session_task;
mod sharing;
mod turn_state;
+mod work_registration;
mod working_branch;
use crate::domain::coding_preferences::CodingPreferences;
@@ -1128,6 +1129,9 @@ impl<B: BotFacts + 'static> AgentSessionRepo for PgAgentSessionRepo<B> {
return Err(anyhow::anyhow!("agent session not found").into());
};
touch_entity_updated(&mut transaction, id, Some(modified_at)).await?;
+ if archived {
+ work_registration::end_work_registrations_on_archive(&mut transaction, id).await?;
+ }
transaction
.commit()
.await
diff --git a/crates/agent_session/src/outbound/postgres/auto_archive.rs b/crates/agent_session/src/outbound/postgres/auto_archive.rs
index bd07e0315c..957c4620f6 100644
--- a/crates/agent_session/src/outbound/postgres/auto_archive.rs
+++ b/crates/agent_session/src/outbound/postgres/auto_archive.rs
@@ -225,6 +225,8 @@ impl<B: BotFacts + 'static> AutoArchiveRepo for PgAgentSessionRepo<B> {
.await
.context("archive agent session")?;
touch_entity_updated(&mut transaction, session, Some(modified_at)).await?;
+ super::work_registration::end_work_registrations_on_archive(&mut transaction, session)
+ .await?;
transaction
.commit()
.await
diff --git a/crates/agent_session/src/outbound/postgres/test.rs b/crates/agent_session/src/outbound/postgres/test.rs
index 0baba2c911..4c014a6ecd 100644
--- a/crates/agent_session/src/outbound/postgres/test.rs
+++ b/crates/agent_session/src/outbound/postgres/test.rs
@@ -7,6 +7,7 @@ mod recovery;
mod search;
mod session_task;
mod user_cleanup;
+mod work_registration;
mod working_branch;
use crate::domain::model::{
AgentMcpServer, DEFAULT_AGENT_SESSION_NAME, SessionSource, SessionVisibility,
diff --git a/crates/agent_session/src/outbound/postgres/test/work_registration.rs b/crates/agent_session/src/outbound/postgres/test/work_registration.rs
new file mode 100644
index 0000000000..bb52dd83fa
--- /dev/null
+++ b/crates/agent_session/src/outbound/postgres/test/work_registration.rs
@@ -0,0 +1,404 @@
+use chrono::Duration;
+
+use super::*;
+use crate::domain::auto_archive::{AutoArchiveOverrides, AutoArchiveReason, AutoArchiveRepo};
+use crate::domain::error::AgentSessionError;
+use crate::domain::pull_request_links::SessionPullRequestLinkRepo;
+use crate::domain::work_registration::{WorkEndReason, WorkRegistrationRepo};
+
+const AGENT: &str = "macro|[email protected]";
+
+async fn end_state(pool: &PgPool, session: AgentSessionId) -> Vec<Option<String>> {
+ sqlx::query_scalar!(
+ r#"
+ SELECT end_reason::text
+ FROM work_registration
+ WHERE agent_session_id = $1
+ ORDER BY registered_at
+ "#,
+ session.as_uuid(),
+ )
+ .fetch_all(pool)
+ .await
+ .unwrap()
+}
+
+async fn set_activity(pool: &PgPool, session: AgentSessionId, turn: &str, age: Duration) {
+ sqlx::query!(
+ "UPDATE agent_session SET turn_state = $2, modified_at = NOW() - make_interval(secs => $3) WHERE id = $1",
+ session.as_uuid(),
+ turn,
+ age.num_seconds() as f64,
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+}
+
+async fn add_pull_request(pool: &PgPool, number: i64, status: &str) -> String {
+ let key = format!("Example/Repo/pull/{number}");
+ sqlx::query!(
+ "INSERT INTO github_pull_request (github_key, number, owner, repo, status) VALUES ($1, $2, 'Example', 'Repo', $3)",
+ key,
+ number,
+ status,
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+ key
+}
+
+/// A repo, a session, and a registered account with a user row.
+async fn registered_session(
+ pool: &PgPool,
+) -> (
+ PgAgentSessionRepo<PgBotsRepo>,
+ AgentSessionId,
+ MacroUserIdStr<'static>,
+) {
+ let repo = test_repo(pool);
+ let bot = create_test_bot(pool).await;
+ insert_user(pool, AGENT).await;
+ let session = create_session(&repo, new_session(bot, None, None)).await.id;
+ let account = user_id(AGENT);
+ repo.register(&account, session).await.unwrap();
+ (repo, session, account)
+}
+
+async fn sweep(repo: &PgAgentSessionRepo<PgBotsRepo>) -> Vec<WorkEndReason> {
+ let now = Utc::now();
+ repo.end_due_registrations(now - Duration::hours(24), now - Duration::days(7), 100)
+ .await
+ .unwrap()
+ .into_iter()
+ .map(|ended| ended.reason)
+ .collect()
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn registering_twice_returns_the_active_registration(pool: PgPool) {
+ let (repo, session, account) = registered_session(&pool).await;
+ let active = repo
+ .active_registrations(std::slice::from_ref(&account), 10)
+ .await
+ .unwrap();
+
+ let repeated = repo.register(&account, session).await.unwrap();
+
+ assert!(!repeated.created);
+ assert_eq!(vec![repeated.registration], active);
+ assert_eq!(end_state(&pool, session).await, vec![None]);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn unregistering_twice_ends_once_and_keeps_the_row(pool: PgPool) {
+ let (repo, session, account) = registered_session(&pool).await;
+
+ assert!(repo.unregister(&account, session).await.unwrap());
+ assert!(!repo.unregister(&account, session).await.unwrap());
+
+ assert_eq!(
+ end_state(&pool, session).await,
+ vec![Some("unregistered".to_owned())]
+ );
+ let active = repo
+ .active_registrations(std::slice::from_ref(&account), 10)
+ .await
+ .unwrap();
+ assert!(active.is_empty());
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_later_registration_is_a_new_one(pool: PgPool) {
+ let (repo, session, account) = registered_session(&pool).await;
+ repo.unregister(&account, session).await.unwrap();
+
+ let again = repo.register(&account, session).await.unwrap();
+
+ assert!(again.created);
+ assert_eq!(
+ end_state(&pool, session).await,
+ vec![Some("unregistered".to_owned()), None]
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn an_archived_or_missing_session_refuses_registration(pool: PgPool) {
+ let (repo, session, account) = registered_session(&pool).await;
+ AgentSessionRepo::set_archived(&repo, session, true)
+ .await
+ .unwrap();
+
+ assert!(matches!(
+ repo.register(&account, session).await,
+ Err(AgentSessionError::Archived(_))
+ ));
+ assert!(matches!(
+ repo.register(&account, AgentSessionId::new()).await,
+ Err(AgentSessionError::NotFound(_))
+ ));
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn archiving_ends_registrations_at_once_and_restoring_does_not_bring_them_back(pool: PgPool) {
+ let (repo, session, account) = registered_session(&pool).await;
+
+ AgentSessionRepo::set_archived(&repo, session, true)
+ .await
+ .unwrap();
+
+ assert_eq!(
+ end_state(&pool, session).await,
+ vec![Some("session_archived".to_owned())]
+ );
+
+ AgentSessionRepo::set_archived(&repo, session, false)
+ .await
+ .unwrap();
+
+ assert!(
+ repo.active_registrations(&[account], 10)
+ .await
+ .unwrap()
+ .is_empty()
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn an_auto_archive_ends_registrations_whatever_triggered_it(pool: PgPool) {
+ let (repo, session, _account) = registered_session(&pool).await;
+ repo.set_session_auto_archive_overrides(
+ session,
+ AutoArchiveOverrides {
+ on_pull_request_merged: None,
+ on_runtime_closed: Some(true),
+ },
+ )
+ .await
+ .unwrap();
+
+ assert!(
+ repo.auto_archive(session, AutoArchiveReason::RuntimeClosed)
+ .await
+ .unwrap()
+ );
+
+ assert_eq!(
+ end_state(&pool, session).await,
+ vec![Some("session_archived".to_owned())]
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn finished_pull_requests_end_registrations_regardless_of_auto_archive_preference(
+ pool: PgPool,
+) {
+ let (repo, session, account) = registered_session(&pool).await;
+ let merged = add_pull_request(&pool, 1, "merged").await;
+ let open = add_pull_request(&pool, 2, "open").await;
+ repo.link_pull_request(session, &merged, &account)
+ .await
+ .unwrap();
+ repo.link_pull_request(session, &open, &account)
+ .await
+ .unwrap();
+
+ assert!(
+ repo.end_for_finished_pull_requests(&merged)
+ .await
+ .unwrap()
+ .is_empty()
+ );
+ assert_eq!(end_state(&pool, session).await, vec![None]);
+
+ sqlx::query!(
+ "UPDATE github_pull_request SET status = 'closed' WHERE github_key = $1",
+ open
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+
+ assert_eq!(
+ repo.end_for_finished_pull_requests(&open).await.unwrap(),
+ vec![session]
+ );
+ // Repeating the event ends nothing more.
+ assert!(
+ repo.end_for_finished_pull_requests(&open)
+ .await
+ .unwrap()
+ .is_empty()
+ );
+ assert_eq!(
+ end_state(&pool, session).await,
+ vec![Some("pull_request_finished".to_owned())]
+ );
+ // The auto-archive preference is off, so the session itself stays active.
+ assert!(
+ AgentSessionRepo::get(&repo, session)
+ .await
+ .unwrap()
+ .archived
+ .is_none()
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_link_with_no_stored_pull_request_is_not_finished(pool: PgPool) {
+ let (repo, session, account) = registered_session(&pool).await;
+ let unknown = "example/repo/pull/404";
+ repo.link_pull_request(session, unknown, &account)
+ .await
+ .unwrap();
+
+ assert!(
+ repo.end_for_finished_pull_requests(unknown)
+ .await
+ .unwrap()
+ .is_empty()
+ );
+ set_activity(&pool, session, "running", Duration::minutes(5)).await;
+ assert!(sweep(&repo).await.is_empty());
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_sweep_ends_an_idle_session_after_a_day_unless_blocked(pool: PgPool) {
+ let (repo, session, _account) = registered_session(&pool).await;
+
+ set_activity(&pool, session, "idle", Duration::hours(23)).await;
+ assert!(sweep(&repo).await.is_empty());
+ set_activity(&pool, session, "blocked", Duration::hours(25)).await;
+ assert!(sweep(&repo).await.is_empty());
+
+ set_activity(&pool, session, "idle", Duration::hours(25)).await;
+ assert_eq!(sweep(&repo).await, vec![WorkEndReason::Idle]);
+ assert_eq!(
+ end_state(&pool, session).await,
+ vec![Some("idle".to_owned())]
+ );
+ // Sweeping again ends nothing more.
+ assert!(sweep(&repo).await.is_empty());
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_sweep_counts_a_failed_turn_as_idle(pool: PgPool) {
+ let (repo, session, _account) = registered_session(&pool).await;
+
+ set_activity(&pool, session, "failed", Duration::hours(25)).await;
+
+ assert_eq!(sweep(&repo).await, vec![WorkEndReason::Idle]);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_sweep_ends_a_blocked_session_after_a_week(pool: PgPool) {
+ let (repo, session, _account) = registered_session(&pool).await;
+
+ set_activity(&pool, session, "blocked", Duration::days(6)).await;
+ assert!(sweep(&repo).await.is_empty());
+
+ set_activity(&pool, session, "blocked", Duration::days(8)).await;
+ assert_eq!(sweep(&repo).await, vec![WorkEndReason::BlockedTimeout]);
+ assert_eq!(
+ end_state(&pool, session).await,
+ vec![Some("blocked_timeout".to_owned())]
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_sweep_catches_up_on_finished_pull_requests_first(pool: PgPool) {
+ let (repo, session, account) = registered_session(&pool).await;
+ let closed = add_pull_request(&pool, 1, "closed").await;
+ repo.link_pull_request(session, &closed, &account)
+ .await
+ .unwrap();
+ // Idle too, but the first matching reason wins.
+ set_activity(&pool, session, "idle", Duration::hours(25)).await;
+
+ assert_eq!(sweep(&repo).await, vec![WorkEndReason::PullRequestFinished]);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_sweep_prefers_an_archived_session_over_the_time_rules(pool: PgPool) {
+ let (repo, session, _account) = registered_session(&pool).await;
+ set_activity(&pool, session, "idle", Duration::hours(25)).await;
+ sqlx::query!(
+ "UPDATE agent_session SET archived_by = 'user', archived_at = NOW() WHERE id = $1",
+ session.as_uuid(),
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+
+ assert_eq!(sweep(&repo).await, vec![WorkEndReason::SessionArchived]);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn concurrent_sweeps_end_each_registration_once(pool: PgPool) {
+ let (repo, session, _account) = registered_session(&pool).await;
+ set_activity(&pool, session, "idle", Duration::hours(25)).await;
+
+ let (first, second) = tokio::join!(sweep(&repo), sweep(&repo));
+
+ assert_eq!(first.len() + second.len(), 1);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn archived_sessions_are_never_read_and_states_report_recent_ends(pool: PgPool) {
+ let (repo, session, account) = registered_session(&pool).await;
+ let accounts = [account.clone()];
+ let long_ago = Utc::now() - Duration::hours(1);
+
+ let states = repo
+ .registration_states(&accounts, &[session], long_ago)
+ .await
+ .unwrap();
+ assert_eq!(states.len(), 1);
+ assert!(!states[0].ended && !states[0].session_archived);
+ assert!(
+ repo.has_current_registrations(session, long_ago)
+ .await
+ .unwrap()
+ );
+
+ // An archive racing the end of its registrations reads as archived, not active.
+ sqlx::query!(
+ "UPDATE agent_session SET archived_by = 'user', archived_at = NOW() WHERE id = $1",
+ session.as_uuid(),
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ assert!(
+ repo.active_registrations(&accounts, 10)
+ .await
+ .unwrap()
+ .is_empty()
+ );
+ let states = repo
+ .registration_states(&accounts, &[session], long_ago)
+ .await
+ .unwrap();
+ assert!(states[0].session_archived);
+
+ repo.unregister(&account, session).await.unwrap();
+ let states = repo
+ .registration_states(&accounts, &[session], long_ago)
+ .await
+ .unwrap();
+ assert!(states[0].ended);
+ let later = Utc::now() + Duration::hours(1);
+ assert!(
+ repo.registration_states(&accounts, &[session], later)
+ .await
+ .unwrap()
+ .is_empty()
+ );
+ assert!(
+ !repo
+ .has_current_registrations(session, later)
+ .await
+ .unwrap()
+ );
+}
diff --git a/crates/agent_session/src/outbound/postgres/work_registration.rs b/crates/agent_session/src/outbound/postgres/work_registration.rs
new file mode 100644
index 0000000000..c48d5bde00
--- /dev/null
+++ b/crates/agent_session/src/outbound/postgres/work_registration.rs
@@ -0,0 +1,347 @@
+//! Work registrations and the writes that end them.
+
+use super::*;
+use crate::domain::work_registration::{
+ EndedRegistration, Registered, WorkEndReason, WorkRegistration, WorkRegistrationId,
+ WorkRegistrationRepo, WorkRegistrationState,
+};
+
+/// End a session's active registrations in the transaction that archives it, whatever archived it.
+pub(super) async fn end_work_registrations_on_archive(
+ tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
+ session: AgentSessionId,
+) -> Result<()> {
+ sqlx::query!(
+ r#"
+ UPDATE work_registration
+ SET ended_at = NOW(), end_reason = 'session_archived'
+ WHERE agent_session_id = $1 AND ended_at IS NULL
+ "#,
+ session.as_uuid(),
+ )
+ .execute(&mut **tx)
+ .await
+ .context("end work registrations of an archived session")?;
+ Ok(())
+}
+
+fn registration(
+ id: Uuid,
+ account_id: String,
+ session: Uuid,
+ registered_at: DateTime<Utc>,
+) -> Result<WorkRegistration> {
+ let account_id =
+ MacroUserIdStr::try_from(account_id).context("stored work registration account id")?;
+ Ok(WorkRegistration {
+ id: WorkRegistrationId::new_from_uuid(id),
+ account_id,
+ session: AgentSessionId::new_from_uuid(session),
+ registered_at,
+ })
+}
+
+fn account_strings(accounts: &[MacroUserIdStr<'static>]) -> Vec<String> {
+ accounts
+ .iter()
+ .map(|account| account.as_ref().to_owned())
+ .collect()
+}
+
+impl<B: BotFacts + Clone + 'static> WorkRegistrationRepo for PgAgentSessionRepo<B> {
+ async fn register(
+ &self,
+ account: &MacroUserIdStr<'static>,
+ session: AgentSessionId,
+ ) -> Result<Registered> {
+ let mut transaction = self.pool.begin().await.context("begin work registration")?;
+ // Hold the row against an archive, which ends the session's registrations: it either
+ // finished and is refused below, or waits and ends this one too.
+ let archived = sqlx::query_scalar!(
+ r#"
+ SELECT archived_by IS NOT NULL AS "archived!"
+ FROM agent_session
+ WHERE id = $1
+ FOR SHARE
+ "#,
+ session.as_uuid(),
+ )
+ .fetch_optional(&mut *transaction)
+ .await
+ .context("check session for work registration")?;
+ match archived {
+ None => return Err(AgentSessionError::NotFound(session)),
+ Some(true) => return Err(AgentSessionError::Archived(session)),
+ Some(false) => {}
+ }
+
+ let inserted = sqlx::query!(
+ r#"
+ INSERT INTO work_registration (id, account_id, agent_session_id)
+ VALUES ($1, $2, $3)
+ ON CONFLICT (account_id, agent_session_id) WHERE ended_at IS NULL DO NOTHING
+ "#,
+ WorkRegistrationId::generate().as_uuid(),
+ account.as_ref(),
+ session.as_uuid(),
+ )
+ .execute(&mut *transaction)
+ .await
+ .context("insert work registration")?;
+
+ // A separate statement, so a registration a concurrent call just committed is visible.
+ let row = sqlx::query!(
+ r#"
+ SELECT id, account_id, agent_session_id, registered_at
+ FROM work_registration
+ WHERE account_id = $1 AND agent_session_id = $2 AND ended_at IS NULL
+ "#,
+ account.as_ref(),
+ session.as_uuid(),
+ )
+ .fetch_one(&mut *transaction)
+ .await
+ .context("read active work registration")?;
+ transaction
+ .commit()
+ .await
+ .context("commit work registration")?;
+ Ok(Registered {
+ registration: registration(
+ row.id,
+ row.account_id,
+ row.agent_session_id,
+ row.registered_at,
+ )?,
+ created: inserted.rows_affected() > 0,
+ })
+ }
+
+ async fn unregister(
+ &self,
+ account: &MacroUserIdStr<'static>,
+ session: AgentSessionId,
+ ) -> Result<bool> {
+ let ended = sqlx::query!(
+ r#"
+ UPDATE work_registration
+ SET ended_at = NOW(), end_reason = 'unregistered'
+ WHERE account_id = $1 AND agent_session_id = $2 AND ended_at IS NULL
+ "#,
+ account.as_ref(),
+ session.as_uuid(),
+ )
+ .execute(&self.pool)
+ .await
+ .context("end work registration")?;
+ Ok(ended.rows_affected() > 0)
+ }
+
+ async fn active_registrations(
+ &self,
+ accounts: &[MacroUserIdStr<'static>],
+ limit: u32,
+ ) -> Result<Vec<WorkRegistration>> {
+ let rows = sqlx::query!(
+ r#"
+ SELECT registration.id, registration.account_id, registration.agent_session_id,
+ registration.registered_at
+ FROM work_registration registration
+ JOIN agent_session session ON session.id = registration.agent_session_id
+ WHERE registration.account_id = ANY($1)
+ AND registration.ended_at IS NULL
+ AND session.archived_by IS NULL
+ ORDER BY registration.registered_at DESC, registration.id DESC
+ LIMIT $2
+ "#,
+ &account_strings(accounts),
+ i64::from(limit),
+ )
+ .fetch_all(&self.pool)
+ .await
+ .context("list active work registrations")?;
+ rows.into_iter()
+ .map(|row| {
+ registration(
+ row.id,
+ row.account_id,
+ row.agent_session_id,
+ row.registered_at,
+ )
+ })
+ .collect()
+ }
+
+ async fn registration_states(
+ &self,
+ accounts: &[MacroUserIdStr<'static>],
+ sessions: &[AgentSessionId],
+ ended_after: DateTime<Utc>,
+ ) -> Result<Vec<WorkRegistrationState>> {
+ let session_ids: Vec<Uuid> = sessions.iter().map(|session| session.as_uuid()).collect();
+ // Ended rows first, so a client applying them in order keeps the account's newer
+ // registration of the same session.
+ let rows = sqlx::query!(
+ r#"
+ SELECT registration.id, registration.account_id, registration.agent_session_id,
+ registration.registered_at,
+ registration.ended_at IS NOT NULL AS "ended!",
+ session.archived_by IS NOT NULL AS "session_archived!"
+ FROM work_registration registration
+ JOIN agent_session session ON session.id = registration.agent_session_id
+ WHERE registration.agent_session_id = ANY($1)
+ AND registration.account_id = ANY($2)
+ AND (registration.ended_at IS NULL OR registration.ended_at > $3)
+ ORDER BY (registration.ended_at IS NULL), registration.registered_at
+ "#,
+ &session_ids,
+ &account_strings(accounts),
+ ended_after,
+ )
+ .fetch_all(&self.pool)
+ .await
+ .context("read work registration states")?;
+ rows.into_iter()
+ .map(|row| {
+ Ok(WorkRegistrationState {
+ registration: registration(
+ row.id,
+ row.account_id,
+ row.agent_session_id,
+ row.registered_at,
+ )?,
+ ended: row.ended,
+ session_archived: row.session_archived,
+ })
+ })
+ .collect()
+ }
+
+ async fn has_current_registrations(
+ &self,
+ session: AgentSessionId,
+ ended_after: DateTime<Utc>,
+ ) -> Result<bool> {
+ let current = sqlx::query_scalar!(
+ r#"
+ SELECT EXISTS (
+ SELECT 1
+ FROM work_registration
+ WHERE agent_session_id = $1 AND (ended_at IS NULL OR ended_at > $2)
+ ) AS "current!"
+ "#,
+ session.as_uuid(),
+ ended_after,
+ )
+ .fetch_one(&self.pool)
+ .await
+ .context("check current work registrations")?;
+ Ok(current)
+ }
+
+ async fn end_for_finished_pull_requests(
+ &self,
+ github_key: &str,
+ ) -> Result<Vec<AgentSessionId>> {
+ // The guard on `ended_at` makes a concurrent replica's update of the same row end nothing.
+ let sessions = sqlx::query_scalar!(
+ r#"
+ UPDATE work_registration
+ SET ended_at = NOW(), end_reason = 'pull_request_finished'
+ WHERE ended_at IS NULL
+ AND agent_session_id IN (
+ SELECT link.agent_session_id
+ FROM agent_session_pull_request link
+ WHERE lower(link.github_key) = lower($1)
+ AND NOT EXISTS (
+ SELECT 1
+ FROM agent_session_pull_request other
+ LEFT JOIN github_pull_request pull_request
+ ON lower(pull_request.github_key) = lower(other.github_key)
+ WHERE other.agent_session_id = link.agent_session_id
+ AND pull_request.status IS DISTINCT FROM 'merged'
+ AND pull_request.status IS DISTINCT FROM 'closed'
+ )
+ )
+ RETURNING agent_session_id
+ "#,
+ github_key,
+ )
+ .fetch_all(&self.pool)
+ .await
+ .context("end work registrations for finished pull requests")?;
+ Ok(sessions
+ .into_iter()
+ .map(AgentSessionId::new_from_uuid)
+ .collect())
+ }
+
+ async fn end_due_registrations(
+ &self,
+ idle_before: DateTime<Utc>,
+ blocked_before: DateTime<Utc>,
+ limit: u32,
+ ) -> Result<Vec<EndedRegistration>> {
+ // One statement, guarded on `ended_at`: replicas sweeping together end each row once, and
+ // links with no stored pull request count as unfinished.
+ let rows = sqlx::query!(
+ r#"
+ WITH due AS (
+ SELECT registration.id,
+ CASE
+ WHEN pull_requests.finished THEN 'pull_request_finished'
+ WHEN session.archived_by IS NOT NULL THEN 'session_archived'
+ WHEN session.turn_state = 'blocked' THEN 'blocked_timeout'
+ ELSE 'idle'
+ END AS reason
+ FROM work_registration registration
+ JOIN agent_session session ON session.id = registration.agent_session_id
+ CROSS JOIN LATERAL (
+ SELECT COALESCE(
+ bool_and(COALESCE(pull_request.status IN ('merged', 'closed'), false)),
+ false
+ ) AS finished
+ FROM agent_session_pull_request link
+ LEFT JOIN github_pull_request pull_request
+ ON lower(pull_request.github_key) = lower(link.github_key)
+ WHERE link.agent_session_id = session.id
+ ) pull_requests
+ WHERE registration.ended_at IS NULL
+ AND (
+ pull_requests.finished
+ OR session.archived_by IS NOT NULL
+ OR (session.turn_state = 'blocked' AND session.modified_at < $2)
+ OR (session.turn_state IS DISTINCT FROM 'blocked'
+ AND session.modified_at < $1)
+ )
+ ORDER BY registration.registered_at
+ LIMIT $3
+ )
+ UPDATE work_registration registration
+ SET ended_at = NOW(),
+ end_reason = due.reason::work_registration_end_reason
+ FROM due
+ WHERE registration.id = due.id AND registration.ended_at IS NULL
+ RETURNING registration.agent_session_id, due.reason AS "reason!"
+ "#,
+ idle_before,
+ blocked_before,
+ i64::from(limit),
+ )
+ .fetch_all(&self.pool)
+ .await
+ .context("end due work registrations")?;
+ rows.into_iter()
+ .map(|row| {
+ let reason = row
+ .reason
+ .parse::<WorkEndReason>()
+ .context("stored work registration end reason")?;
+ Ok(EndedRegistration {
+ session: AgentSessionId::new_from_uuid(row.agent_session_id),
+ reason,
+ })
+ })
+ .collect()
+ }
+}
diff --git a/crates/complete_graph/AGENTS.md b/crates/complete_graph/AGENTS.md
index c201dfd4ed..e788353d13 100644
--- a/crates/complete_graph/AGENTS.md
+++ b/crates/complete_graph/AGENTS.md
@@ -5,7 +5,8 @@
Part of the web client's shared infrastructure: this crate composes the
domain GraphQL adapter crates (`graphql_soup`, `graphql_properties`,
`graphql_notification`, `graphql_email`, `graphql_entity_mutation`,
-`graphql_work_feed`, `graphql_notification_inbox`, with shared plumbing in
+`graphql_work_feed`, `graphql_notification_inbox`, `graphql_registered_work`,
+with shared plumbing in
`graphql_common`) into the complete GraphQL schema
consumed by the client's **normalized cache** (`crates/client`, design doc:
`apps/web/docs/graphql-normalized-cache-plan.md`). The conventions below are
diff --git a/crates/complete_graph/Cargo.toml b/crates/complete_graph/Cargo.toml
index fdb571eb88..2cfd9df6f3 100644
--- a/crates/complete_graph/Cargo.toml
+++ b/crates/complete_graph/Cargo.toml
@@ -38,6 +38,7 @@ graphql_notification = { path = "../graphql_notification" }
graphql_notification_inbox = { path = "../graphql_notification_inbox" }
graphql_permission = { path = "../graphql_permission" }
graphql_properties = { path = "../graphql_properties" }
+graphql_registered_work = { path = "../graphql_registered_work" }
graphql_scheduled_action = { path = "../graphql_scheduled_action" }
graphql_soup = { path = "../graphql_soup" }
graphql_work_feed = { path = "../graphql_work_feed" }
diff --git a/crates/complete_graph/src/lib.rs b/crates/complete_graph/src/lib.rs
index 274d57ce79..47c21e9a40 100644
--- a/crates/complete_graph/src/lib.rs
+++ b/crates/complete_graph/src/lib.rs
@@ -1,7 +1,7 @@
//! Composition of the domain GraphQL adapter crates (`graphql_soup`,
//! `graphql_channel`, `graphql_properties`, `graphql_notification`, `graphql_email`,
//! `graphql_favorite`, `graphql_entity_mutation`, `graphql_work_feed`,
-//! `graphql_notification_inbox`) into the
+//! `graphql_notification_inbox`, `graphql_registered_work`) into the
//! complete schema served by
//! `document_storage_service` and exported as SDL.
#![deny(missing_docs)]
@@ -78,6 +78,7 @@ pub use graphql_properties::{
PropertiesEntityPropertyReader, PropertiesEntityPropertyWriter, PropertiesMutationRoot,
entity_properties_loader,
};
+pub use graphql_registered_work::{RegisteredWorkGraphqlContext, RegisteredWorkGraphqlService};
pub use graphql_work_feed::{WorkFeedGraphqlContext, WorkFeedGraphqlService};
pub use mail_cache_profile::{MAIL_CACHE_PROFILE_HEADER, MailCacheProfile};
pub use realtime::{AgentSessionLogSubscriptions, agent_session_log_subscriptions};
diff --git a/crates/complete_graph/src/schema.rs b/crates/complete_graph/src/schema.rs
index 365ec2460b..a95d6300ed 100644
--- a/crates/complete_graph/src/schema.rs
+++ b/crates/complete_graph/src/schema.rs
@@ -58,6 +58,9 @@ use graphql_properties::{
NoOpEntityPropertyWriter, PropertiesMutationRoot, load_property_definitions,
load_property_options,
};
+use graphql_registered_work::{
+ GraphqlRegisteredWork, RegisteredWorkSubscriptionRoot, resolve_registered_work,
+};
use graphql_scheduled_action::{GraphqlScheduledAction, resolve_scheduled_actions};
use graphql_soup::{
GraphqlSoupAgentSession, GraphqlSoupEmailThread, GraphqlSoupEntity, GraphqlSoupInitiative,
@@ -154,6 +157,7 @@ pub struct CompleteSubscriptionRoot<R, NS, AS, Auth, St, NR, PR, ER, FR, AR, AcR
ActivitySubscriptionRoot<AS>,
WorkFeedSubscriptionRoot<SoupEdges<NR, PR, ER, FR, AR, AcR>>,
NotificationInboxSubscriptionRoot<SoupEdges<NR, PR, ER, FR, AR, AcR>>,
+ RegisteredWorkSubscriptionRoot<SoupEdges<NR, PR, ER, FR, AR, AcR>>,
)
where
R: SoupRealtimeSubscriptionService,
@@ -469,6 +473,7 @@ where
ActivitySubscriptionRoot::new(activity_subscription_service),
WorkFeedSubscriptionRoot::default(),
NotificationInboxSubscriptionRoot::default(),
+ RegisteredWorkSubscriptionRoot::default(),
),
)
.finish()
@@ -896,6 +901,22 @@ where
.await
}
+ /// The agent sessions `accountIds` registered as their work that the
+ /// authenticated user can view, newest first, at most 50 accounts.
+ /// Registrations of sessions the user cannot view are completely hidden.
+ async fn registered_work(
+ &self,
+ ctx: &Context<'_>,
+ account_ids: Vec<ID>,
+ ) -> async_graphql::Result<Vec<GraphqlRegisteredWork<SoupEdges<NR, PR, ER, FR, AR, AcR>>>> {
+ resolve_registered_work::<SoupEdges<NR, PR, ER, FR, AR, AcR>>(
+ ctx,
+ self.user_id.clone(),
+ account_ids,
+ )
+ .await
+ }
+
/// A page of the authenticated user's notifications inbox, newest group
/// first: their pending notifications grouped by the entity they are
/// filed under and cut into rows, one per conversation thread, channel
diff --git a/crates/complete_graph/src/schema/test.rs b/crates/complete_graph/src/schema/test.rs
index e21f9ac099..4a0ffcae7c 100644
--- a/crates/complete_graph/src/schema/test.rs
+++ b/crates/complete_graph/src/schema/test.rs
@@ -54,6 +54,7 @@ mod email_archive;
mod form_activity;
mod initiative;
mod notification_inbox;
+mod registered_work;
mod scheduled_actions;
mod soup_patches;
mod stale_client;
diff --git a/crates/complete_graph/src/schema/test/registered_work.rs b/crates/complete_graph/src/schema/test/registered_work.rs
new file mode 100644
index 0000000000..ca35e25940
--- /dev/null
+++ b/crates/complete_graph/src/schema/test/registered_work.rs
@@ -0,0 +1,376 @@
+use std::sync::{Arc, Mutex};
+
+use agent_session::domain::{
+ error::AgentSessionError,
+ model::AgentSessionId,
+ work_registration::{WorkRegistration, WorkRegistrationChanges, WorkRegistrationId},
+};
+use async_graphql::futures_util::{StreamExt as _, future::BoxFuture, pin_mut};
+use chrono::{DateTime, Utc};
+use model_entity::Entity;
+use soup_realtime::domain::models::Patch;
+
+use super::*;
+use crate::{RegisteredWorkGraphqlContext, RegisteredWorkGraphqlService};
+
+const SESSION_ID: Uuid = Uuid::from_u128(0x5E55);
+const REGISTRATION_ID: Uuid = Uuid::from_u128(0xBEEF);
+const ENDED_ID: Uuid = Uuid::from_u128(0xDEAD);
+const ACCOUNT: &str = "macro|[email protected]";
+
+fn session() -> AgentSessionId {
+ AgentSessionId::new_from_uuid(SESSION_ID)
+}
+
+fn registration() -> WorkRegistration {
+ WorkRegistration {
+ id: WorkRegistrationId::new_from_uuid(REGISTRATION_ID),
+ account_id: MacroUserIdStr::parse_from_str(ACCOUNT).unwrap(),
+ session: session(),
+ registered_at: Utc::now(),
+ }
+}
+
+/// Answers every read from fixed data, recording what it was asked.
+#[derive(Clone, Default)]
+struct FixedRegistrations {
+ visible: Vec<WorkRegistration>,
+ changes: WorkRegistrationChanges,
+ read_accounts: Arc<Mutex<Vec<Vec<String>>>>,
+ changed_sessions: Arc<Mutex<Vec<Vec<AgentSessionId>>>>,
+}
+
+impl RegisteredWorkGraphqlService for FixedRegistrations {
+ fn visible_registrations<'a>(
+ &'a self,
+ _viewer: &'a MacroUserIdStr<'static>,
+ accounts: &'a [MacroUserIdStr<'static>],
+ ) -> BoxFuture<'a, Result<Vec<WorkRegistration>, AgentSessionError>> {
+ self.read_accounts.lock().unwrap().push(
+ accounts
+ .iter()
+ .map(|account| account.as_ref().to_owned())
+ .collect(),
+ );
+ Box::pin(async { Ok(self.visible.clone()) })
+ }
+
+ fn changes<'a>(
+ &'a self,
+ _viewer: &'a MacroUserIdStr<'static>,
+ _accounts: &'a [MacroUserIdStr<'static>],
+ sessions: &'a [AgentSessionId],
+ _ended_after: DateTime<Utc>,
+ ) -> BoxFuture<'a, Result<WorkRegistrationChanges, AgentSessionError>> {
+ self.changed_sessions
+ .lock()
+ .unwrap()
+ .push(sessions.to_vec());
+ Box::pin(async { Ok(self.changes.clone()) })
+ }
+}
+
+/// Soup patches a test drives by hand.
+#[derive(Clone, Default)]
+struct ManualPatches(Arc<Mutex<Option<tokio::sync::mpsc::Sender<Patch<Entity<'static>>>>>>);
+
+impl ManualPatches {
+ async fn send(&self, patch: Patch<Entity<'static>>) {
+ let sender = self.0.lock().unwrap().clone().unwrap();
+ sender.send(patch).await.unwrap();
+ }
+
+ fn close(&self) {
+ self.0.lock().unwrap().take();
+ }
+}
+
+impl SoupRealtimeSubscriptionService for ManualPatches {
+ fn subscribe(
+ &self,
+ _user: MacroUserIdStr<'static>,
+ ) -> tokio::sync::mpsc::Receiver<Patch<Entity<'static>>> {
+ let (sender, receiver) = tokio::sync::mpsc::channel(8);
+ *self.0.lock().unwrap() = Some(sender);
+ receiver
+ }
+}
+
+fn session_patch() -> Patch<Entity<'static>> {
+ Patch::Updated(ModelEntityType::AgentSession.with_entity_string(SESSION_ID.to_string()))
+}
+
+const SUBSCRIPTION: &str = r#"subscription { registeredWorkUpdates(accountIds: ["macro|[email protected]"]) {
+ __typename
+ ... on GraphqlRegisteredWorkUpsert { entry { id accountId session { id name } } }
+ ... on GraphqlRegisteredWorkRemove { id }
+ ... on GraphqlRegisteredWorkInvalidate { refresh }
+} }"#;
+
+fn viewer_id() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::parse_from_str(VALID_USER_ID).unwrap()
+}
+
+fn loader(items: Vec<SoupItem<()>>) -> graphql_soup::AgentSessionEntityLoader {
+ let soup_service = CountingSoupService::default();
+ soup_service.set_raw_response(items);
+ graphql_soup::AgentSessionEntityLoader::new(
+ soup_service,
+ Arc::new(NoOpEmailService),
+ NoOpEntityAccessService,
+ )
+}
+
+fn subscription(
+ service: FixedRegistrations,
+ patches: &ManualPatches,
+ items: Vec<SoupItem<()>>,
+) -> async_graphql::Request {
+ async_graphql::Request::new(SUBSCRIPTION)
+ .data(viewer_id())
+ .data(loader(items))
+ .data(RegisteredWorkGraphqlContext::new(
+ service,
+ Arc::new(patches.clone()),
+ ))
+}
+
+#[tokio::test]
+async fn registered_work_lists_entries_hydrated_for_the_viewer() {
+ let harness = harness();
+ harness
+ .primary_soup_service
+ .set_raw_response(vec![soup_agent_session(SESSION_ID)]);
+ let service = FixedRegistrations {
+ visible: vec![
+ registration(),
+ // A session Soup does not return to this viewer is dropped, not an error.
+ WorkRegistration {
+ id: WorkRegistrationId::new_from_uuid(ENDED_ID),
+ session: AgentSessionId::new_from_uuid(Uuid::from_u128(0x0DD)),
+ ..registration()
+ },
+ ],
+ ..FixedRegistrations::default()
+ };
+ let read_accounts = Arc::clone(&service.read_accounts);
+
+ let response = harness
+ .schema
+ .execute(
+ harness
+ .request(
+ r#"{ user { registeredWork(accountIds: [
+ ]) { id accountId session { id } } } }"#,
+ authenticated_parts(),
+ )
+ .data(RegisteredWorkGraphqlContext::new(
+ service,
+ Arc::new(ManualPatches::default()),
+ )),
+ )
+ .await;
+
+ assert!(response.errors.is_empty(), "{:?}", response.errors);
+ let data = response.data.into_json().unwrap();
+ assert_eq!(
+ data["user"]["registeredWork"],
+ serde_json::json!([{
+ "id": REGISTRATION_ID.to_string(),
+ "accountId": ACCOUNT,
+ "session": { "id": SESSION_ID.to_string() },
+ }])
+ );
+ assert_eq!(
+ *read_accounts.lock().unwrap(),
+ vec![vec![ACCOUNT.to_owned()]]
+ );
+}
+
+#[tokio::test]
+async fn registered_work_caps_the_accounts_one_request_may_name() {
+ let harness = harness();
+ let service = FixedRegistrations::default();
+ let read_accounts = Arc::clone(&service.read_accounts);
+ let accounts = (0..51)
+ .map(|index| format!("\"macro|account-{index}@example.com\""))
+ .collect::<Vec<_>>()
+ .join(",");
+
+ let response = harness
+ .schema
+ .execute(
+ harness
+ .request(
+ &format!("{{ user {{ registeredWork(accountIds: [{accounts}]) {{ id }} }} }}"),
+ authenticated_parts(),
+ )
+ .data(RegisteredWorkGraphqlContext::new(
+ service,
+ Arc::new(ManualPatches::default()),
+ )),
+ )
+ .await;
+
+ assert_eq!(response.errors.len(), 1);
+ assert!(read_accounts.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn updates_batch_upserts_and_removes_for_changed_sessions_only() {
+ let harness = harness();
+ let patches = ManualPatches::default();
+ let service = FixedRegistrations {
+ changes: WorkRegistrationChanges {
+ active: vec![registration()],
+ removed: vec![WorkRegistrationId::new_from_uuid(ENDED_ID)],
+ refetch: false,
+ },
+ ..FixedRegistrations::default()
+ };
+ let changed_sessions = Arc::clone(&service.changed_sessions);
+ let responses = harness.schema.execute_stream(subscription(
+ service,
+ &patches,
+ vec![soup_agent_session(SESSION_ID)],
+ ));
+ pin_mut!(responses);
+ let first = responses.next();
+ pin_mut!(first);
+ assert!(futures_poll_pending(first.as_mut()).await);
+
+ // A change to anything but a session is not this stream's business.
+ patches
+ .send(Patch::Updated(
+ ModelEntityType::Document.with_entity_string(Uuid::from_u128(1).to_string()),
+ ))
+ .await;
+ patches.send(session_patch()).await;
+ patches.send(session_patch()).await;
+
+ let response = first.await.unwrap();
+ assert!(response.errors.is_empty(), "{:?}", response.errors);
+ assert_eq!(
+ response.data.into_json().unwrap()["registeredWorkUpdates"],
+ serde_json::json!([
+ { "__typename": "GraphqlRegisteredWorkRemove", "id": ENDED_ID.to_string() },
+ {
+ "__typename": "GraphqlRegisteredWorkUpsert",
+ "entry": {
+ "id": REGISTRATION_ID.to_string(),
+ "accountId": ACCOUNT,
+ "session": { "id": SESSION_ID.to_string(), "name": "A session" },
+ },
+ },
+ ])
+ );
+ assert_eq!(*changed_sessions.lock().unwrap(), vec![vec![session()]]);
+}
+
+#[tokio::test]
+async fn updates_ask_for_a_refetch_rather_than_name_what_the_viewer_cannot_view() {
+ let harness = harness();
+ let patches = ManualPatches::default();
+ let service = FixedRegistrations {
+ changes: WorkRegistrationChanges {
+ refetch: true,
+ ..WorkRegistrationChanges::default()
+ },
+ ..FixedRegistrations::default()
+ };
+ let responses = harness
+ .schema
+ .execute_stream(subscription(service, &patches, Vec::new()));
+ pin_mut!(responses);
+ let first = responses.next();
+ pin_mut!(first);
+ assert!(futures_poll_pending(first.as_mut()).await);
+
+ patches.send(session_patch()).await;
+
+ let response = first.await.unwrap();
+ assert_eq!(
+ response.data.into_json().unwrap()["registeredWorkUpdates"],
+ serde_json::json!([{ "__typename": "GraphqlRegisteredWorkInvalidate", "refresh": true }])
+ );
+}
+
+#[tokio::test]
+async fn updates_ask_for_a_refetch_when_soup_hides_a_session_the_domain_allowed() {
+ let harness = harness();
+ let patches = ManualPatches::default();
+ let service = FixedRegistrations {
+ changes: WorkRegistrationChanges {
+ active: vec![registration()],
+ ..WorkRegistrationChanges::default()
+ },
+ ..FixedRegistrations::default()
+ };
+ let responses = harness
+ .schema
+ .execute_stream(subscription(service, &patches, Vec::new()));
+ pin_mut!(responses);
+ let first = responses.next();
+ pin_mut!(first);
+ assert!(futures_poll_pending(first.as_mut()).await);
+
+ patches.send(session_patch()).await;
+
+ let response = first.await.unwrap();
+ assert_eq!(
+ response.data.into_json().unwrap()["registeredWorkUpdates"],
+ serde_json::json!([{ "__typename": "GraphqlRegisteredWorkInvalidate", "refresh": true }])
+ );
+}
+
+#[tokio::test]
+async fn updates_invalidate_then_end_when_the_source_ends() {
+ let harness = harness();
+ let patches = ManualPatches::default();
+ let responses = harness.schema.execute_stream(subscription(
+ FixedRegistrations::default(),
+ &patches,
+ Vec::new(),
+ ));
+ pin_mut!(responses);
+ let first = responses.next();
+ pin_mut!(first);
+ assert!(futures_poll_pending(first.as_mut()).await);
+
+ patches.close();
+
+ let response = first.await.unwrap();
+ assert_eq!(
+ response.data.into_json().unwrap()["registeredWorkUpdates"],
+ serde_json::json!([{ "__typename": "GraphqlRegisteredWorkInvalidate", "refresh": true }])
+ );
+ let ended = responses.next().await.unwrap();
+ assert!(!ended.errors.is_empty());
+}
+
+#[tokio::test(start_paused = true)]
+async fn updates_refetch_on_a_schedule_to_catch_revoked_access() {
+ let harness = harness();
+ let patches = ManualPatches::default();
+ let responses = harness.schema.execute_stream(subscription(
+ FixedRegistrations::default(),
+ &patches,
+ Vec::new(),
+ ));
+ pin_mut!(responses);
+
+ let response = responses.next().await.unwrap();
+
+ assert_eq!(
+ response.data.into_json().unwrap()["registeredWorkUpdates"],
+ serde_json::json!([{ "__typename": "GraphqlRegisteredWorkInvalidate", "refresh": true }])
+ );
+}
+
+/// Poll once, so the stream has subscribed before the test sends anything. Whether it is still
+/// waiting, which it always is before anything was sent.
+async fn futures_poll_pending<F: Future + Unpin>(future: F) -> bool {
+ async_graphql::futures_util::poll!(future).is_pending()
+}
diff --git a/crates/graphql_registered_work/AGENTS.md b/crates/graphql_registered_work/AGENTS.md
new file mode 100644
index 0000000000..dc06241f12
--- /dev/null
+++ b/crates/graphql_registered_work/AGENTS.md
@@ -0,0 +1,55 @@
+# graphql_registered_work
+
+## What it is
+
+Part of agent sessions: the GraphQL inbound adapter for registered work, the
+sessions an account registered as its work. Exposes `registeredWork` under the
+viewer and the `registeredWorkUpdates` subscription. Not Home's work feed
+(`graphql_work_feed`), which is a different feature.
+
+## Start here
+
+- `src/query.rs`: `resolve_registered_work` and `load_entry`, hydrating a
+ registration with its Soup agent session.
+- `src/subscriptions.rs`: `RegisteredWorkSubscriptionRoot`, batching the
+ viewer's session Soup patches with `attention_feed`'s `live::coalesce`.
+- `src/objects.rs`: `GraphqlRegisteredWork` and the patch union.
+- `src/context.rs`: `RegisteredWorkGraphqlContext`, built by the composition
+ root.
+
+## Scope
+
+- Owns: GraphQL types, resolvers, and the subscription for registered work.
+- Not here: registering, ending, and viewer filtering →
+ `agent_session::domain::work_registration`; HTTP routes →
+ `agent_session::inbound::axum_router::work_registration`; publishing session
+ changes → `soup_realtime::outbound::agent_sessions`.
+
+## Boundaries
+
+- Depends on: `agent_session` (domain only), `attention_feed` (coalescing),
+ `graphql_soup`, `graphql_common`, `soup_realtime` (ports only).
+- Used by: `complete_graph` (schema composition).
+
+## Recipes
+
+- Add a field: `src/objects.rs`, then regenerate `static_assets/schema.graphql`
+ (see `crates/complete_graph/AGENTS.md`).
+
+## Checks
+
+- `cargo nextest run --all-features -p complete_graph registered_work`
+ (`SQLX_OFFLINE` unset); the schema tests live with the composition.
+
+## Gotchas
+
+- A viewer who loses access hears nothing, because session changes go to current
+ accessors. The stream invalidates every `REFRESH_INTERVAL` to bound how long a
+ revoked entry stays shown, and it covers channel and team membership changes
+ no event reports.
+- Never name a registration the viewer cannot view, even to remove it: such a
+ session yields `Invalidate`, and the client's refetch drops it.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`, `.agents/rules/observability.md`
diff --git a/crates/graphql_registered_work/CLAUDE.md b/crates/graphql_registered_work/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/graphql_registered_work/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/graphql_registered_work/Cargo.toml b/crates/graphql_registered_work/Cargo.toml
new file mode 100644
index 0000000000..1ab495c09c
--- /dev/null
+++ b/crates/graphql_registered_work/Cargo.toml
@@ -0,0 +1,22 @@
+[package]
+edition = "2024"
+name = "graphql_registered_work"
+publish = false
+version = "0.1.0"
+
+[dependencies]
+agent_session = { path = "../agent_session", default-features = false }
+async-graphql = { workspace = true }
+async-stream = { workspace = true }
+attention_feed = { path = "../attention_feed" }
+chrono = { workspace = true }
+futures = { workspace = true }
+graphql_common = { path = "../graphql_common" }
+graphql_soup = { path = "../graphql_soup" }
+macro_user_id = { path = "../macro_user_id" }
+model-entity = { path = "../model-entity" }
+soup_realtime = { path = "../soup_realtime", default-features = false, features = ["ports"] }
+tokio = { workspace = true, features = ["macros", "sync", "time"] }
+tracing = { workspace = true }
+uuid = { workspace = true }
+workspace-hack = { version = "0.1", path = "../workspace-hack" }
diff --git a/crates/graphql_registered_work/src/context.rs b/crates/graphql_registered_work/src/context.rs
new file mode 100644
index 0000000000..3d845a1dd3
--- /dev/null
+++ b/crates/graphql_registered_work/src/context.rs
@@ -0,0 +1,99 @@
+use std::sync::Arc;
+
+use agent_session::domain::{
+ error::AgentSessionError,
+ model::AgentSessionId,
+ work_registration::{WorkRegistration, WorkRegistrationChanges, WorkRegistrations},
+};
+use chrono::{DateTime, Utc};
+use futures::future::BoxFuture;
+use macro_user_id::user_id::MacroUserIdStr;
+use model_entity::Entity;
+use soup_realtime::domain::{models::Patch, ports::SoupRealtimeSubscriptionService};
+use tokio::sync::mpsc::Receiver;
+
+/// Reads of work registrations, object-safe so request data can carry them
+/// without a schema type parameter.
+pub trait RegisteredWorkGraphqlService: Send + Sync + 'static {
+ /// See [`WorkRegistrations::visible_registrations`].
+ fn visible_registrations<'a>(
+ &'a self,
+ viewer: &'a MacroUserIdStr<'static>,
+ accounts: &'a [MacroUserIdStr<'static>],
+ ) -> BoxFuture<'a, Result<Vec<WorkRegistration>, AgentSessionError>>;
+
+ /// See [`WorkRegistrations::changes`].
+ fn changes<'a>(
+ &'a self,
+ viewer: &'a MacroUserIdStr<'static>,
+ accounts: &'a [MacroUserIdStr<'static>],
+ sessions: &'a [AgentSessionId],
+ ended_after: DateTime<Utc>,
+ ) -> BoxFuture<'a, Result<WorkRegistrationChanges, AgentSessionError>>;
+}
+
+impl<T: WorkRegistrations> RegisteredWorkGraphqlService for T {
+ fn visible_registrations<'a>(
+ &'a self,
+ viewer: &'a MacroUserIdStr<'static>,
+ accounts: &'a [MacroUserIdStr<'static>],
+ ) -> BoxFuture<'a, Result<Vec<WorkRegistration>, AgentSessionError>> {
+ Box::pin(WorkRegistrations::visible_registrations(
+ self, viewer, accounts,
+ ))
+ }
+
+ fn changes<'a>(
+ &'a self,
+ viewer: &'a MacroUserIdStr<'static>,
+ accounts: &'a [MacroUserIdStr<'static>],
+ sessions: &'a [AgentSessionId],
+ ended_after: DateTime<Utc>,
+ ) -> BoxFuture<'a, Result<WorkRegistrationChanges, AgentSessionError>> {
+ Box::pin(WorkRegistrations::changes(
+ self,
+ viewer,
+ accounts,
+ sessions,
+ ended_after,
+ ))
+ }
+}
+
+/// Request data for the registered work fields, inserted by the composition
+/// root for HTTP requests and subscription connections alike.
+#[derive(Clone)]
+pub struct RegisteredWorkGraphqlContext {
+ /// Reads of registrations.
+ pub(crate) service: Arc<dyn RegisteredWorkGraphqlService>,
+ /// The Soup patches addressed to a viewer, which announce session changes.
+ soup: Arc<dyn SoupRealtimeSubscriptionService>,
+}
+
+impl RegisteredWorkGraphqlContext {
+ /// Bundle the registered work capabilities for request data.
+ pub fn new(
+ service: impl RegisteredWorkGraphqlService,
+ soup: Arc<dyn SoupRealtimeSubscriptionService>,
+ ) -> Self {
+ Self {
+ service: Arc::new(service),
+ soup,
+ }
+ }
+
+ /// The Soup patches addressed to `viewer` from now on.
+ pub(crate) fn patches(
+ &self,
+ viewer: MacroUserIdStr<'static>,
+ ) -> Receiver<Patch<Entity<'static>>> {
+ self.soup.subscribe(viewer)
+ }
+}
+
+/// Map a service error to a client-facing GraphQL error; details are logged,
+/// never exposed.
+pub(crate) fn to_graphql_error(error: AgentSessionError) -> async_graphql::Error {
+ tracing::error!(error = ?error, "registered work request failed");
+ async_graphql::Error::new("registered work is unavailable")
+}
diff --git a/crates/graphql_registered_work/src/inputs.rs b/crates/graphql_registered_work/src/inputs.rs
new file mode 100644
index 0000000000..818d9ed510
--- /dev/null
+++ b/crates/graphql_registered_work/src/inputs.rs
@@ -0,0 +1,28 @@
+use std::collections::HashSet;
+
+use async_graphql::ID;
+use graphql_common::parse_macro_user_id;
+use macro_user_id::user_id::MacroUserIdStr;
+
+/// Most accounts one request may name.
+const MAX_ACCOUNT_IDS: usize = 50;
+
+/// Validate requested account ids, each once, in the order given.
+pub(crate) fn parse_account_ids(
+ account_ids: Vec<ID>,
+) -> async_graphql::Result<Vec<MacroUserIdStr<'static>>> {
+ if account_ids.len() > MAX_ACCOUNT_IDS {
+ return Err(async_graphql::Error::new(format!(
+ "accountIds is limited to {MAX_ACCOUNT_IDS} accounts"
+ )));
+ }
+
+ let mut seen = HashSet::new();
+ let mut accounts = Vec::with_capacity(account_ids.len());
+ for id in account_ids {
+ if seen.insert(id.0.clone()) {
+ accounts.push(parse_macro_user_id(id.0, "accountIds")?);
+ }
+ }
+ Ok(accounts)
+}
diff --git a/crates/graphql_registered_work/src/lib.rs b/crates/graphql_registered_work/src/lib.rs
new file mode 100644
index 0000000000..6a065cf5d9
--- /dev/null
+++ b/crates/graphql_registered_work/src/lib.rs
@@ -0,0 +1,24 @@
+//! GraphQL inbound adapter for registered work: the `registeredWork` list
+//! under the viewer and the `registeredWorkUpdates` subscription. The schema
+//! itself is composed by `complete_graph`.
+#![deny(missing_docs)]
+#![deny(clippy::missing_docs_in_private_items)]
+
+/// Request data carrying registrations and the viewer's session changes.
+mod context;
+/// Account id input validation.
+mod inputs;
+/// Registration and patch objects.
+mod objects;
+/// The `registeredWork` resolver.
+mod query;
+/// The `registeredWorkUpdates` subscription.
+mod subscriptions;
+
+pub use context::{RegisteredWorkGraphqlContext, RegisteredWorkGraphqlService};
+pub use objects::{
+ GraphqlRegisteredWork, GraphqlRegisteredWorkInvalidate, GraphqlRegisteredWorkPatch,
+ GraphqlRegisteredWorkRemove, GraphqlRegisteredWorkUpsert,
+};
+pub use query::resolve_registered_work;
+pub use subscriptions::RegisteredWorkSubscriptionRoot;
diff --git a/crates/graphql_registered_work/src/objects.rs b/crates/graphql_registered_work/src/objects.rs
new file mode 100644
index 0000000000..a4d91e44fe
--- /dev/null
+++ b/crates/graphql_registered_work/src/objects.rs
@@ -0,0 +1,88 @@
+use agent_session::domain::work_registration::{WorkRegistration, WorkRegistrationId};
+use async_graphql::{ID, SimpleObject, Union};
+use graphql_soup::{GraphqlSoupAgentSession, SoupEntityEdges};
+
+/// An agent session an account registered as its work.
+#[derive(SimpleObject)]
+#[graphql(name = "GraphqlRegisteredWork")]
+pub struct GraphqlRegisteredWork<E: SoupEntityEdges> {
+ /// The registration.
+ id: ID,
+ /// The account whose work this is.
+ account_id: ID,
+ /// When the account registered it, in RFC 3339.
+ registered_at: String,
+ /// The session registered.
+ session: GraphqlSoupAgentSession<E>,
+}
+
+impl<E: SoupEntityEdges> GraphqlRegisteredWork<E> {
+ /// Pair a registration with its session as the viewer sees it.
+ pub(crate) fn new(registration: WorkRegistration, session: GraphqlSoupAgentSession<E>) -> Self {
+ Self {
+ id: ID(registration.id.to_string()),
+ account_id: ID(registration.account_id.as_ref().to_owned()),
+ registered_at: registration.registered_at.to_rfc3339(),
+ session,
+ }
+ }
+}
+
+/// A registration to show, new or with its session's list fields changed.
+#[derive(SimpleObject)]
+#[graphql(name = "GraphqlRegisteredWorkUpsert")]
+pub struct GraphqlRegisteredWorkUpsert<E: SoupEntityEdges> {
+ /// The registration.
+ entry: GraphqlRegisteredWork<E>,
+}
+
+/// A registration that ended or whose session was archived.
+#[derive(SimpleObject)]
+#[graphql(name = "GraphqlRegisteredWorkRemove")]
+pub struct GraphqlRegisteredWorkRemove {
+ /// The registration to stop showing.
+ id: ID,
+}
+
+/// Changes may have been missed or sharing changed: refetch the list.
+#[derive(SimpleObject)]
+#[graphql(name = "GraphqlRegisteredWorkInvalidate")]
+pub struct GraphqlRegisteredWorkInvalidate {
+ /// Always true.
+ refresh: bool,
+}
+
+/// One change to the registered work of the subscribed accounts.
+#[expect(
+ clippy::large_enum_variant,
+ reason = "upserts dominate and carry hydrated sessions"
+)]
+#[derive(Union)]
+#[graphql(name = "GraphqlRegisteredWorkPatch")]
+pub enum GraphqlRegisteredWorkPatch<E: SoupEntityEdges> {
+ /// A registration to show.
+ Upsert(GraphqlRegisteredWorkUpsert<E>),
+ /// A registration to stop showing.
+ Remove(GraphqlRegisteredWorkRemove),
+ /// The list must be refetched.
+ Invalidate(GraphqlRegisteredWorkInvalidate),
+}
+
+impl<E: SoupEntityEdges> GraphqlRegisteredWorkPatch<E> {
+ /// The patch showing `entry`.
+ pub(crate) fn upsert(entry: GraphqlRegisteredWork<E>) -> Self {
+ Self::Upsert(GraphqlRegisteredWorkUpsert { entry })
+ }
+
+ /// The patch that stops showing `id`.
+ pub(crate) fn remove(id: WorkRegistrationId) -> Self {
+ Self::Remove(GraphqlRegisteredWorkRemove {
+ id: ID(id.to_string()),
+ })
+ }
+
+ /// The patch asking for a refetch.
+ pub(crate) fn invalidate() -> Self {
+ Self::Invalidate(GraphqlRegisteredWorkInvalidate { refresh: true })
+ }
+}
diff --git a/crates/graphql_registered_work/src/query.rs b/crates/graphql_registered_work/src/query.rs
new file mode 100644
index 0000000000..5c855a5cd9
--- /dev/null
+++ b/crates/graphql_registered_work/src/query.rs
@@ -0,0 +1,56 @@
+use agent_session::domain::work_registration::WorkRegistration;
+use async_graphql::{Context, ID};
+use futures::future::join_all;
+use graphql_soup::{AgentSessionEntityLoader, SoupEntityEdges, load_soup_agent_session};
+use macro_user_id::user_id::MacroUserIdStr;
+
+use crate::{
+ context::{RegisteredWorkGraphqlContext, to_graphql_error},
+ inputs::parse_account_ids,
+ objects::GraphqlRegisteredWork,
+};
+
+/// Hydrate a registration with its session as `viewer` sees it. `None` when the viewer cannot
+/// see the session, it is archived, or it failed to load: one bad row never fails a read.
+pub(crate) async fn load_entry<E: SoupEntityEdges>(
+ loader: &AgentSessionEntityLoader,
+ viewer: &MacroUserIdStr<'static>,
+ registration: WorkRegistration,
+) -> Option<GraphqlRegisteredWork<E>> {
+ let session =
+ load_soup_agent_session::<E>(loader, viewer.clone(), registration.session.as_uuid())
+ .await
+ .inspect_err(|error| {
+ tracing::warn!(
+ error = ?error.message,
+ agent.session.id = %registration.session,
+ "failed to load a registered work session"
+ );
+ })
+ .ok()
+ .flatten()?;
+ if session.archived() {
+ return None;
+ }
+ Some(GraphqlRegisteredWork::new(registration, session))
+}
+
+/// Resolve the registered work of `account_ids` that `viewer` can see, newest first.
+pub async fn resolve_registered_work<E: SoupEntityEdges>(
+ ctx: &Context<'_>,
+ viewer: MacroUserIdStr<'static>,
+ account_ids: Vec<ID>,
+) -> async_graphql::Result<Vec<GraphqlRegisteredWork<E>>> {
+ let context = ctx.data::<RegisteredWorkGraphqlContext>()?;
+ let loader = ctx.data::<AgentSessionEntityLoader>()?;
+ let accounts = parse_account_ids(account_ids)?;
+ let registrations = context
+ .service
+ .visible_registrations(&viewer, &accounts)
+ .await
+ .map_err(to_graphql_error)?;
+ let entries = registrations
+ .into_iter()
+ .map(|registration| load_entry::<E>(loader, &viewer, registration));
+ Ok(join_all(entries).await.into_iter().flatten().collect())
+}
diff --git a/crates/graphql_registered_work/src/subscriptions.rs b/crates/graphql_registered_work/src/subscriptions.rs
new file mode 100644
index 0000000000..0584d20266
--- /dev/null
+++ b/crates/graphql_registered_work/src/subscriptions.rs
@@ -0,0 +1,192 @@
+use std::{marker::PhantomData, time::Duration};
+
+use agent_session::domain::{
+ error::AgentSessionError, model::AgentSessionId, work_registration::ENDED_REPORT_WINDOW,
+};
+use async_graphql::{Context, ID, Subscription};
+use attention_feed::domain::{
+ live::{COALESCE_WINDOW, coalesce},
+ models::{FeedKey, FeedTrigger},
+};
+use chrono::{DateTime, Utc};
+use futures::{Stream, StreamExt, future::join_all};
+use graphql_common::require_authenticated_user;
+use graphql_soup::{AgentSessionEntityLoader, SoupEntityEdges};
+use macro_user_id::user_id::MacroUserIdStr;
+use model_entity::{Entity, EntityType};
+use soup_realtime::domain::models::Patch;
+use tokio::sync::mpsc::{self, Receiver};
+use uuid::Uuid;
+
+use crate::{
+ context::RegisteredWorkGraphqlContext, inputs::parse_account_ids,
+ objects::GraphqlRegisteredWorkPatch, query::load_entry,
+};
+
+/// Session changes buffered per subscriber before the source waits.
+const TRIGGER_BUFFER: usize = 64;
+
+/// How often a subscriber refetches regardless. A viewer who loses access hears nothing, since
+/// session changes go to current accessors, so this bounds how long a revoked entry stays shown.
+const REFRESH_INTERVAL: Duration = Duration::from_secs(2 * 60);
+
+/// Root GraphQL adapter for the registered work subscription.
+pub struct RegisteredWorkSubscriptionRoot<E>(PhantomData<fn() -> E>);
+
+impl<E> Default for RegisteredWorkSubscriptionRoot<E> {
+ fn default() -> Self {
+ Self(PhantomData)
+ }
+}
+
+#[Subscription]
+impl<E: SoupEntityEdges> RegisteredWorkSubscriptionRoot<E> {
+ /// Changes to the registered work of `accountIds` that the authenticated
+ /// user can see: entries to show, entries to stop showing, and an
+ /// invalidation when changes may have been missed or sharing changed.
+ /// Each payload is one batch to apply together. Start it before fetching
+ /// `registeredWork` and refetch after an invalidation; the stream ends
+ /// with an error when its source ends, after which the client resubscribes
+ /// and refetches.
+ async fn registered_work_updates(
+ &self,
+ ctx: &Context<'_>,
+ account_ids: Vec<ID>,
+ ) -> async_graphql::Result<
+ impl Stream<Item = async_graphql::Result<Vec<GraphqlRegisteredWorkPatch<E>>>> + 'static,
+ > {
+ let viewer = require_authenticated_user(ctx)?;
+ let context = ctx.data::<RegisteredWorkGraphqlContext>()?.clone();
+ let loader = ctx.data::<AgentSessionEntityLoader>()?.clone();
+ let accounts = parse_account_ids(account_ids)?;
+ let ended_after = Utc::now() - ENDED_REPORT_WINDOW;
+ let triggers = session_triggers(context.patches(viewer.clone()));
+
+ Ok(async_stream::stream! {
+ let batches = coalesce(triggers, COALESCE_WINDOW);
+ futures::pin_mut!(batches);
+ let mut refresh = tokio::time::interval_at(
+ tokio::time::Instant::now() + REFRESH_INTERVAL,
+ REFRESH_INTERVAL,
+ );
+ loop {
+ let batch = tokio::select! {
+ _ = refresh.tick() => {
+ yield Ok(vec![GraphqlRegisteredWorkPatch::invalidate()]);
+ continue;
+ }
+ batch = batches.next() => batch,
+ };
+ let Some(batch) = batch else {
+ break;
+ };
+ if batch.invalidated {
+ yield Ok(vec![GraphqlRegisteredWorkPatch::invalidate()]);
+ continue;
+ }
+ let sessions = session_ids(&batch.keys);
+ match session_patches::<E>(
+ &context,
+ &loader,
+ &viewer,
+ &accounts,
+ &sessions,
+ ended_after,
+ )
+ .await
+ {
+ Ok(patches) if patches.is_empty() => {}
+ Ok(patches) => yield Ok(patches),
+ Err(error) => {
+ tracing::error!(error = ?error, "registered work recompute failed");
+ yield Ok(vec![GraphqlRegisteredWorkPatch::invalidate()]);
+ }
+ }
+ }
+ yield Err(async_graphql::Error::new(
+ "registered work subscription ended; resubscribe and refetch",
+ ));
+ })
+ }
+}
+
+/// The session changes among a viewer's Soup patches. When the patches end, normally or after
+/// falling behind, changes may have been missed, so subscribers must refetch.
+fn session_triggers(mut patches: Receiver<Patch<Entity<'static>>>) -> Receiver<FeedTrigger> {
+ let (sender, receiver) = mpsc::channel(TRIGGER_BUFFER);
+ tokio::spawn(async move {
+ loop {
+ let patch = tokio::select! {
+ () = sender.closed() => return,
+ patch = patches.recv() => patch,
+ };
+ let Some(patch) = patch else {
+ break;
+ };
+ let entity = patch.value();
+ if entity.entity_type != EntityType::AgentSession {
+ continue;
+ }
+ let trigger = FeedTrigger::Changed(vec![entity.clone()]);
+ if sender.send(trigger).await.is_err() {
+ return;
+ }
+ }
+ let _ = sender.send(FeedTrigger::Invalidated).await;
+ });
+ receiver
+}
+
+/// The sessions a batch names. Only well-formed session ids reach here; any other is skipped.
+fn session_ids(keys: &[FeedKey]) -> Vec<AgentSessionId> {
+ keys.iter()
+ .filter_map(|key| Uuid::parse_str(key.entity().entity_id.as_ref()).ok())
+ .map(AgentSessionId::new_from_uuid)
+ .collect()
+}
+
+/// What `sessions` changing means for `viewer`. Every entry passes the domain's view check and
+/// the Soup access filter; a session failing either asks for a refetch rather than naming it.
+#[tracing::instrument(
+ name = "registered_work.stream.batch",
+ err,
+ skip_all,
+ fields(sessions = sessions.len(), upserts, removes, refetch)
+)]
+async fn session_patches<E: SoupEntityEdges>(
+ context: &RegisteredWorkGraphqlContext,
+ loader: &AgentSessionEntityLoader,
+ viewer: &MacroUserIdStr<'static>,
+ accounts: &[MacroUserIdStr<'static>],
+ sessions: &[AgentSessionId],
+ ended_after: DateTime<Utc>,
+) -> Result<Vec<GraphqlRegisteredWorkPatch<E>>, AgentSessionError> {
+ let changes = context
+ .service
+ .changes(viewer, accounts, sessions, ended_after)
+ .await?;
+
+ let active = changes.active.len();
+ let entries = changes
+ .active
+ .into_iter()
+ .map(|registration| load_entry::<E>(loader, viewer, registration));
+ let entries: Vec<_> = join_all(entries).await.into_iter().flatten().collect();
+ let refetch = changes.refetch || entries.len() < active;
+
+ let span = tracing::Span::current();
+ span.record("upserts", entries.len());
+ span.record("removes", changes.removed.len());
+ span.record("refetch", refetch);
+
+ let mut patches: Vec<_> = changes
+ .removed
+ .into_iter()
+ .map(GraphqlRegisteredWorkPatch::remove)
+ .collect();
+ patches.extend(entries.into_iter().map(GraphqlRegisteredWorkPatch::upsert));
+ if refetch {
+ patches.push(GraphqlRegisteredWorkPatch::invalidate());
+ }
+ Ok(patches)
+}
diff --git a/crates/graphql_soup/src/lib.rs b/crates/graphql_soup/src/lib.rs
index fc7771d0d5..154749bba8 100644
--- a/crates/graphql_soup/src/lib.rs
+++ b/crates/graphql_soup/src/lib.rs
@@ -42,7 +42,7 @@ pub use objects::{
SoupPatch, SoupUpdated,
};
pub use resolvers::{
- SoupEmailThreadMutationOutput, resolve_grouped_soup, resolve_soup, resolve_soup_agent_session,
- resolve_soup_email_thread, resolve_soup_email_threads, resolve_soup_entity,
- resolve_soup_updates,
+ SoupEmailThreadMutationOutput, load_soup_agent_session, resolve_grouped_soup, resolve_soup,
+ resolve_soup_agent_session, resolve_soup_email_thread, resolve_soup_email_threads,
+ resolve_soup_entity, resolve_soup_updates,
};
diff --git a/crates/graphql_soup/src/objects.rs b/crates/graphql_soup/src/objects.rs
index 82a824dcb6..a45bdc44e5 100644
--- a/crates/graphql_soup/src/objects.rs
+++ b/crates/graphql_soup/src/objects.rs
@@ -1171,6 +1171,13 @@ impl<E: SoupEntityEdges> GraphqlSoupDatabaseRow<E> {
/// GraphQL agent session entity.
pub struct GraphqlSoupAgentSession<E: SoupEntityEdges>(SoupAgentSession<()>, E, Option<f64>);
+impl<E: SoupEntityEdges> GraphqlSoupAgentSession<E> {
+ /// Whether the session is archived, for adapters that must not return archived sessions.
+ pub fn archived(&self) -> bool {
+ self.0.archived_by.is_some()
+ }
+}
+
/// Last synchronized state of a session's linked GitHub pull request.
#[derive(async_graphql::Enum, Copy, Clone, Eq, PartialEq)]
pub enum GraphqlAgentPullRequestState {
diff --git a/crates/graphql_soup/src/resolvers.rs b/crates/graphql_soup/src/resolvers.rs
index 9606b77cbf..ebc23e01f5 100644
--- a/crates/graphql_soup/src/resolvers.rs
+++ b/crates/graphql_soup/src/resolvers.rs
@@ -195,9 +195,22 @@ pub async fn resolve_soup_agent_session<Edges>(
where
Edges: SoupEntityEdges,
{
- let loader = &ctx.data::<AgentSessionEntityLoader>()?.0;
+ let loader = ctx.data::<AgentSessionEntityLoader>()?;
+ load_soup_agent_session(loader, user_id, session_id).await
+}
+
+/// [`resolve_soup_agent_session`] for a caller holding the loader, such as a subscription stream,
+/// which outlives its request context.
+pub async fn load_soup_agent_session<Edges>(
+ loader: &AgentSessionEntityLoader,
+ user_id: MacroUserIdStr<'static>,
+ session_id: uuid::Uuid,
+) -> async_graphql::Result<Option<GraphqlSoupAgentSession<Edges>>>
+where
+ Edges: SoupEntityEdges,
+{
let entity = EntityType::AgentSession.with_entity_string(session_id.to_string());
- let Some(item) = loader.load_one((user_id, entity)).await? else {
+ let Some(item) = loader.0.load_one((user_id, entity)).await? else {
return Ok(None);
};
diff --git a/crates/macro_db_client/migrations/20261105164414_create_work_registration.sql b/crates/macro_db_client/migrations/20261105164414_create_work_registration.sql
new file mode 100644
index 0000000000..84d7696be4
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261105164414_create_work_registration.sql
@@ -0,0 +1,26 @@
+-- An account registering an agent session as its work. Ending a registration keeps the row, so
+-- history survives and a later turn cannot bring it back.
+CREATE TYPE work_registration_end_reason AS ENUM (
+ 'unregistered',
+ 'pull_request_finished',
+ 'session_archived',
+ 'idle',
+ 'blocked_timeout'
+);
+
+CREATE TABLE work_registration (
+ id UUID PRIMARY KEY,
+ account_id TEXT NOT NULL REFERENCES "User" (id) ON DELETE CASCADE,
+ agent_session_id UUID NOT NULL REFERENCES agent_session (id) ON DELETE CASCADE,
+ registered_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ ended_at TIMESTAMPTZ,
+ end_reason work_registration_end_reason,
+ CONSTRAINT work_registration_ended_with_reason
+ CHECK ((ended_at IS NULL) = (end_reason IS NULL))
+);
+
+CREATE UNIQUE INDEX work_registration_active_account_session
+ ON work_registration (account_id, agent_session_id)
+ WHERE ended_at IS NULL;
+
+CREATE INDEX work_registration_session ON work_registration (agent_session_id);
diff --git a/crates/soup_realtime/AGENTS.md b/crates/soup_realtime/AGENTS.md
index 8ea8c4f8e2..fba66cb29c 100644
--- a/crates/soup_realtime/AGENTS.md
+++ b/crates/soup_realtime/AGENTS.md
@@ -55,6 +55,9 @@ tasks itself.
- Property definition/option lifecycle events are intentionally ignored; they
don't identify every affected entity.
- Channel threads use their containing channel as the access source.
+- Agent sessions have no source event here: their patches come from channel
+ references, linked pull requests, and the harness publishing through
+ `outbound/agent_sessions.rs`' `SoupWorkRegistrationSignal` for registered work.
- Only `call.record_imported` patches calls; native call lifecycle events on
`macro.calls` are ignored. The web cache has no local call projection, so a
call patch makes mounted lists that can contain calls refetch
diff --git a/crates/soup_realtime/src/outbound/agent_sessions.rs b/crates/soup_realtime/src/outbound/agent_sessions.rs
index 591f4fd2aa..1cb581defa 100644
--- a/crates/soup_realtime/src/outbound/agent_sessions.rs
+++ b/crates/soup_realtime/src/outbound/agent_sessions.rs
@@ -1,6 +1,12 @@
-//! Resolve PR dependencies through the agent-session domain's existing link port.
-use crate::domain::ports::PullRequestSessions;
+//! Resolve PR dependencies through the agent-session domain's existing link port, and carry
+//! work registration changes to a session's viewers.
+use std::sync::Arc;
+
+use crate::domain::models::{Patch, SoupRealtimePatch};
+use crate::domain::ports::{PullRequestSessions, SoupRealtimeService};
+use agent_session::domain::model::AgentSessionId;
use agent_session::domain::pull_request_links::SessionPullRequestLinkRepo;
+use agent_session::domain::work_registration::WorkRegistrationSignal;
use model_entity::{Entity, EntityType};
use rootcause::prelude::{Report, ResultExt as _};
@@ -18,3 +24,23 @@ impl<R: SessionPullRequestLinkRepo> PullRequestSessions for AgentSessionPullRequ
.collect())
}
}
+
+/// Tells a session's current accessors it changed, as a Soup patch on the session. Their
+/// `registeredWorkUpdates` streams recompute from it, and their Soup lists refresh the row.
+pub struct SoupWorkRegistrationSignal<S>(pub Arc<S>);
+
+impl<S> Clone for SoupWorkRegistrationSignal<S> {
+ fn clone(&self) -> Self {
+ Self(Arc::clone(&self.0))
+ }
+}
+
+impl<S: SoupRealtimeService> WorkRegistrationSignal for SoupWorkRegistrationSignal<S> {
+ async fn session_changed(&self, session: AgentSessionId) -> Result<(), Report> {
+ self.0
+ .notify_users(SoupRealtimePatch::for_entity(Patch::Updated(
+ EntityType::AgentSession.with_entity_string(session.to_string()),
+ )))
+ .await
+ }
+}
diff --git a/docs/agent-guide/calls.md b/docs/agent-guide/calls.md
index 52d1f86f6f..2742042b5d 100644
--- a/docs/agent-guide/calls.md
+++ b/docs/agent-guide/calls.md
@@ -315,6 +315,20 @@ or failed capture shows its reason under the call controls. Browsers
and older desktop builds keep the browser's own picker. Verify on a Mac by
sharing a display and a window, stopping, and cancelling the picker.
+### Work in a call
+
+Behind `enable-agent-work`, the call panel gains a **Work** tab, after Chat and
+Participants, while any other participant has registered work you can open.
+Chat stays the default tab. Each participant with work gets a section; rows keep
+their order, and clicking one opens the session in a new split so the call stays
+live. Registering is SDK-only (`session.registerAsWork()`).
+
+A dot marks the Work tab while you're elsewhere and the panel button while the
+panel is closed. A **View active work** prompt with the participants' pictures
+appears above your video tile when someone's work first shows, for eight seconds
+or until dismissed; clicking it opens the tab. It belongs to the call rather than
+the toast system.
+
### Browser call diagnostics
Browser OpenTelemetry requires `enable-browser-otel` (or
diff --git a/docs/agent-guide/channels.md b/docs/agent-guide/channels.md
index 639f220403..08df74becf 100644
--- a/docs/agent-guide/channels.md
+++ b/docs/agent-guide/channels.md
@@ -1788,3 +1788,21 @@ For tab performance QA, switch Attachments → Calls → Participants → Messag
in both the routed channel and a block split. Each actual selection should
produce one `channel.tab` interaction with its `channel.*.view` child; repeat
the current selection and confirm it does not create a new interaction.
+
+## Work in a DM with an agent account
+
+Behind `enable-agent-work`, a 1:1 DM shows the other account's registered work
+when that account is an agent (`isAgentAccount`) and has work you can open. The
+rule lives in `features/agent-work/core/work-visibility.ts`. DMs with people,
+group DMs, and channels show nothing.
+
+The side panel toggle appears in the top bar only while there's work, using the
+floating `SidePanel` the agent session uses. When the agent goes from no work to
+some, a "<name> started working" label appears beside the toggle for six
+seconds without opening the panel; clicking it opens the panel. Clicking a row
+opens the session in a new split. Rows keep their order as state changes.
+
+To exercise it, register a session as the agent account through the SDK
+(`session.registerAsWork()`), share it with the viewer, and watch the DM update
+live. `session.unregisterAsWork()` removes it. A registered session the viewer
+can't open stays hidden.
diff --git a/packages/sdk/generated/agent-harness/index.ts b/packages/sdk/generated/agent-harness/index.ts
index b1e4e4244a..7b6058b270 100644
--- a/packages/sdk/generated/agent-harness/index.ts
+++ b/packages/sdk/generated/agent-harness/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 { AccessLevel, AddConnectedMcpServerData, AddConnectedMcpServerErrors, AddConnectedMcpServerResponse, AddConnectedMcpServerResponses, AgentAction, AgentActionId, AgentConfigKindDto, AgentConfigOptionDto, AgentConfigSelectOptionDto, AgentConversationDto, AgentConversationsDto, AgentConversationSessionDto, AgentConversationTurnDto, AgentMode, AgentModeChoiceRequest, AgentModeChoiceResponse, AgentModelDto, AgentModelsStatusDto, AgentPermissionAction, AgentPromptAction, AgentRepositoriesResponse, AgentRepositoryBranchesResponse, AgentRepositoryDto, AgentRespondElicitationAction, AgentSessionChangesPatchResponse, AgentSessionChangesResponse, AgentSessionFoldedLogResponse, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionPreviewData, AgentSessionPreviewDto, AgentSessionQueueResponse, AgentSessionResponse, AgentSessionsForPullRequestData, AgentSessionsForPullRequestError, AgentSessionsForPullRequestErrors, AgentSessionsForPullRequestResponse, AgentSessionsForPullRequestResponses, AgentSessionsForPullRequestsData, AgentSessionsForPullRequestsError, AgentSessionsForPullRequestsErrors, AgentSessionsForPullRequestsResponse, AgentSessionsForPullRequestsResponses, AgentSetConfigOptionAction, AgentSetModelAction, AiAdmissionErrorBody, AiSuggestions, AnswerAgentSessionToolApprovalData, AnswerAgentSessionToolApprovalError, AnswerAgentSessionToolApprovalErrors, AnswerAgentSessionToolApprovalResponse, AnswerAgentSessionToolApprovalResponses, AnswerToolApprovalRequest, AnswerToolApprovalResponse, AppConnectedRequest, ArchiveCause, AutoArchiveOverridesBody, AutoArchivePreferencesBody, BotId, CalendarSuggestions, CallConnectedAppToolData, CallConnectedAppToolErrors, CallConnectedAppToolResponse, CallConnectedAppToolResponses, CallConnectedTool, CallSearchSuggestions, CapabilityHarnessDto, CaptureAttemptDto, CaptureOutcomeDto, ChangedFileDto, ChangesetDto, ChangesetSourceDto, ChannelSearchSuggestions, ChannelSharePermission, ChooseAgentModeData, ChooseAgentModeErrors, ChooseAgentModeResponse, ChooseAgentModeResponses, ClassifyData, ClassifyErrors, ClassifyInputRequest, ClassifyInputResponse, ClassifyResponse, ClassifyResponses, ClientOptions, CodingPreferencesBody, ConnectedApp, ConnectedAppKind, ConnectedTool, ConnectedToolMatch, ConnectedToolResult, ConnectedToolSearch, ConnectMcpServer, ConnectMcpServerResponse, ConnectorTool, ControlAgentSessionData, ControlAgentSessionError, ControlAgentSessionErrors, ControlAgentSessionResponse, ControlAgentSessionResponses, ControlRequest, ControlResponse, ControlStatusDto, ConversationTurnState, CreateAgentSessionData, CreateAgentSessionError, CreateAgentSessionErrors, CreateAgentSessionRequest, CreateAgentSessionResponse, CreateAgentSessionResponse2, CreateAgentSessionResponses, CreateReview, CreateSessionReviewData, CreateSessionReviewErrors, CreateSessionReviewResponse, CreateSessionReviewResponses, CreateSessionThread, DecideSessionReviewData, DecideSessionReviewErrors, DecideSessionReviewResponse, DecideSessionReviewResponses, DecisionVia, DeleteAgentSessionData, DeleteAgentSessionError, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DiscoverAgentCapabilitiesHandlerData, DiscoverAgentCapabilitiesHandlerErrors, DiscoverAgentCapabilitiesHandlerResponse, DiscoverAgentCapabilitiesHandlerResponses, DiscoverAgentCapabilitiesRequest, DiscoverAgentCapabilitiesResponse, DiscoverConnectedAppsData, DiscoverConnectedAppsErrors, DiscoverConnectedAppsResponse, DiscoverConnectedAppsResponses, DiscoverConnectorsResponse, DiscoveredApp, DiscoveryRequest, DiscoveryResult, DocumentId, EditQueuedActionData, EditQueuedActionError, EditQueuedActionErrors, EditQueuedActionRequest, EditQueuedActionResponse, EditQueuedActionResponses, ElicitationAnswer, ElicitationContentValue, ElicitationRequestId, EmailSearchSuggestions, EmailSuggestions, ExecutionActivity, ExecutionId, ExecutionRecord, ExecutionStatus, ExternalSessionResponse, ExtractData, ExtractErrors, ExtractInputRequest, ExtractInputResponse, ExtractResponse, ExtractResponses, FileChangeKindDto, GetAgentAutoArchivePreferencesData, GetAgentAutoArchivePreferencesError, GetAgentAutoArchivePreferencesErrors, GetAgentAutoArchivePreferencesResponse, GetAgentAutoArchivePreferencesResponses, GetAgentCodingPreferencesData, GetAgentCodingPreferencesError, GetAgentCodingPreferencesErrors, GetAgentCodingPreferencesResponse, GetAgentCodingPreferencesResponses, GetAgentSandboxSizeData, GetAgentSandboxSizeError, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponse, GetAgentSandboxSizeResponses, GetAgentSessionAutoArchiveData, GetAgentSessionAutoArchiveError, GetAgentSessionAutoArchiveErrors, GetAgentSessionAutoArchiveResponse, GetAgentSessionAutoArchiveResponses, GetAgentSessionChangesData, GetAgentSessionChangesError, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchError, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponse, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponse, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionError, GetAgentSessionErrors, GetAgentSessionFoldedLogData, GetAgentSessionFoldedLogError, GetAgentSessionFoldedLogErrors, GetAgentSessionFoldedLogResponse, GetAgentSessionFoldedLogResponses, GetAgentSessionLogData, GetAgentSessionLogError, GetAgentSessionLogErrors, GetAgentSessionLogResponse, GetAgentSessionLogResponses, GetAgentSessionPermissionsData, GetAgentSessionPermissionsError, GetAgentSessionPermissionsErrors, GetAgentSessionPermissionsResponse, GetAgentSessionPermissionsResponses, GetAgentSessionQueueData, GetAgentSessionQueueError, GetAgentSessionQueueErrors, GetAgentSessionQueueResponse, GetAgentSessionQueueResponses, GetAgentSessionResponse, GetAgentSessionResponses, GetCodeExecutionData, GetCodeExecutionErrors, GetCodeExecutionResponse, GetCodeExecutionResponses, GetSessionReviewData, GetSessionReviewErrors, GetSessionReviewResponse, GetSessionReviewResponses, GitRefDto, InputIntent, InputPropertyDefinition, InputPropertySuggestion, InputSuggestions, IntentScore, LinkAgentSessionPullRequestData, LinkAgentSessionPullRequestError, LinkAgentSessionPullRequestErrors, LinkAgentSessionPullRequestResponse, LinkAgentSessionPullRequestResponses, LinkShare, ListAgentConversationsData, ListAgentConversationsErrors, ListAgentConversationsResponse, ListAgentConversationsResponses, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponse, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponse, ListAgentRepositoryBranchesResponses, ListAgentSessionPullRequestsData, ListAgentSessionPullRequestsError, ListAgentSessionPullRequestsErrors, ListAgentSessionPullRequestsResponse, ListAgentSessionPullRequestsResponses, ListConnectedAppToolsData, ListConnectedAppToolsErrors, ListConnectedAppToolsResponse, ListConnectedAppToolsResponses, ListExecutionConnectedAppsData, ListExecutionConnectedAppsErrors, ListExecutionConnectedAppsResponse, ListExecutionConnectedAppsResponses, ListExecutionReviewsData, ListExecutionReviewsErrors, ListExecutionReviewsResponse, ListExecutionReviewsResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponse, LoadAgentModelsHandlerResponses, LoadAgentModelsRequest, LoadAgentModelsResponse, LogDirectionDto, LogFrameDto, MessageParent, MessageSuggestions, ModelHarnessDto, MonthlyWeekday, NoteSuggestions, PermissionAnswer, PresentSessionViewData, PresentSessionViewErrors, PresentSessionViewResponse, PresentSessionViewResponses, PresentView, PreviewAgentSessionsData, PreviewAgentSessionsError, PreviewAgentSessionsErrors, PreviewAgentSessionsRequest, PreviewAgentSessionsResponse, PreviewAgentSessionsResponse2, PreviewAgentSessionsResponses, PromptAttachment, PullRequestLinkedSession, PullRequestLinkSource, PullRequestSessions, PullRequestSessionsResponse, PullRequestsSessionsResponse, PullRequestUrl, PullRequestUrls, PutAgentAutoArchivePreferencesData, PutAgentAutoArchivePreferencesError, PutAgentAutoArchivePreferencesErrors, PutAgentAutoArchivePreferencesResponse, PutAgentAutoArchivePreferencesResponses, PutAgentCodingPreferencesData, PutAgentCodingPreferencesError, PutAgentCodingPreferencesErrors, PutAgentCodingPreferencesResponse, PutAgentCodingPreferencesResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeError, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponse, PutAgentSandboxSizeResponses, PutAgentSessionAutoArchiveData, PutAgentSessionAutoArchiveError, PutAgentSessionAutoArchiveErrors, PutAgentSessionAutoArchiveResponse, PutAgentSessionAutoArchiveResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeError, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponse, PutAgentSessionSandboxSizeResponses, QuerySearchSuggestions, QueuedActionDto, RecordedCallStatus, RecordedToolCall, RecurrenceEnd, RecurrenceFrequency, RecurrenceSuggestion, RefreshAgentSessionChangesData, RefreshAgentSessionChangesError, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponse, RefreshAgentSessionChangesResponses, RemoveQueuedActionData, RemoveQueuedActionError, RemoveQueuedActionErrors, RemoveQueuedActionResponse, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionError, RenameAgentSessionErrors, RenameAgentSessionRequest, RenameAgentSessionResponse, RenameAgentSessionResponses, ReportAgentSessionAppConnectedData, ReportAgentSessionAppConnectedError, ReportAgentSessionAppConnectedErrors, ReportAgentSessionAppConnectedResponses, RetryAgentConversationTurnData, RetryAgentConversationTurnErrors, RetryAgentConversationTurnRequest, RetryAgentConversationTurnResponse, RetryAgentConversationTurnResponses, ReviewDecision, ReviewDecisionContext, ReviewId, ReviewRecord, SandboxSize, SandboxSizeBody, SearchConnectedAppToolsData, SearchConnectedAppToolsErrors, SearchConnectedAppToolsResponse, SearchConnectedAppToolsResponses, SearchSuggestions, SearchType, SessionAutoArchiveResponse, SessionBot, SessionPullRequestLink, SessionPullRequestsResponse, SessionStatusDto, SetAgentSessionArchivedData, SetAgentSessionArchivedError, SetAgentSessionArchivedErrors, SetAgentSessionArchivedRequest, SetAgentSessionArchivedResponse, SetAgentSessionArchivedResponses, SharePermissionV2, StartFreshAgentConversationData, StartFreshAgentConversationErrors, StartFreshAgentConversationRequest, StartFreshAgentConversationResponse, StartFreshAgentConversationResponses, SteerQueuedActionData, SteerQueuedActionError, SteerQueuedActionErrors, SteerQueuedActionResponse, SteerQueuedActionResponses, TaskSearchSuggestions, TaskSuggestions, ToolActor, ToolApprovalAnswerDto, ToolApprovalStatusDto, UnlinkAgentSessionPullRequestData, UnlinkAgentSessionPullRequestError, UnlinkAgentSessionPullRequestErrors, UnlinkAgentSessionPullRequestResponse, UnlinkAgentSessionPullRequestResponses, UpdateAgentSessionPermissionsData, UpdateAgentSessionPermissionsError, UpdateAgentSessionPermissionsErrors, UpdateAgentSessionPermissionsResponse, UpdateAgentSessionPermissionsResponses, UpdateChannelSharePermission, UpdateOperation, UpdateSharePermissionRequestV2, WarmAgentSessionHandlerData, WarmAgentSessionHandlerResponse, WarmAgentSessionHandlerResponses, WarmAgentSessionRequest, WarmAgentSessionResponse, WeekdayCode, WithAgentSessionId } from './types.gen';
+export type { AccessLevel, AddConnectedMcpServerData, AddConnectedMcpServerErrors, AddConnectedMcpServerResponse, AddConnectedMcpServerResponses, AgentAction, AgentActionId, AgentConfigKindDto, AgentConfigOptionDto, AgentConfigSelectOptionDto, AgentConversationDto, AgentConversationsDto, AgentConversationSessionDto, AgentConversationTurnDto, AgentMode, AgentModeChoiceRequest, AgentModeChoiceResponse, AgentModelDto, AgentModelsStatusDto, AgentPermissionAction, AgentPromptAction, AgentRepositoriesResponse, AgentRepositoryBranchesResponse, AgentRepositoryDto, AgentRespondElicitationAction, AgentSessionChangesPatchResponse, AgentSessionChangesResponse, AgentSessionFoldedLogResponse, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionPreviewData, AgentSessionPreviewDto, AgentSessionQueueResponse, AgentSessionResponse, AgentSessionsForPullRequestData, AgentSessionsForPullRequestError, AgentSessionsForPullRequestErrors, AgentSessionsForPullRequestResponse, AgentSessionsForPullRequestResponses, AgentSessionsForPullRequestsData, AgentSessionsForPullRequestsError, AgentSessionsForPullRequestsErrors, AgentSessionsForPullRequestsResponse, AgentSessionsForPullRequestsResponses, AgentSetConfigOptionAction, AgentSetModelAction, AiAdmissionErrorBody, AiSuggestions, AnswerAgentSessionToolApprovalData, AnswerAgentSessionToolApprovalError, AnswerAgentSessionToolApprovalErrors, AnswerAgentSessionToolApprovalResponse, AnswerAgentSessionToolApprovalResponses, AnswerToolApprovalRequest, AnswerToolApprovalResponse, AppConnectedRequest, ArchiveCause, AutoArchiveOverridesBody, AutoArchivePreferencesBody, BotId, CalendarSuggestions, CallConnectedAppToolData, CallConnectedAppToolErrors, CallConnectedAppToolResponse, CallConnectedAppToolResponses, CallConnectedTool, CallSearchSuggestions, CapabilityHarnessDto, CaptureAttemptDto, CaptureOutcomeDto, ChangedFileDto, ChangesetDto, ChangesetSourceDto, ChannelSearchSuggestions, ChannelSharePermission, ChooseAgentModeData, ChooseAgentModeErrors, ChooseAgentModeResponse, ChooseAgentModeResponses, ClassifyData, ClassifyErrors, ClassifyInputRequest, ClassifyInputResponse, ClassifyResponse, ClassifyResponses, ClientOptions, CodingPreferencesBody, ConnectedApp, ConnectedAppKind, ConnectedTool, ConnectedToolMatch, ConnectedToolResult, ConnectedToolSearch, ConnectMcpServer, ConnectMcpServerResponse, ConnectorTool, ControlAgentSessionData, ControlAgentSessionError, ControlAgentSessionErrors, ControlAgentSessionResponse, ControlAgentSessionResponses, ControlRequest, ControlResponse, ControlStatusDto, ConversationTurnState, CreateAgentSessionData, CreateAgentSessionError, CreateAgentSessionErrors, CreateAgentSessionRequest, CreateAgentSessionResponse, CreateAgentSessionResponse2, CreateAgentSessionResponses, CreateReview, CreateSessionReviewData, CreateSessionReviewErrors, CreateSessionReviewResponse, CreateSessionReviewResponses, CreateSessionThread, DecideSessionReviewData, DecideSessionReviewErrors, DecideSessionReviewResponse, DecideSessionReviewResponses, DecisionVia, DeleteAgentSessionData, DeleteAgentSessionError, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DiscoverAgentCapabilitiesHandlerData, DiscoverAgentCapabilitiesHandlerErrors, DiscoverAgentCapabilitiesHandlerResponse, DiscoverAgentCapabilitiesHandlerResponses, DiscoverAgentCapabilitiesRequest, DiscoverAgentCapabilitiesResponse, DiscoverConnectedAppsData, DiscoverConnectedAppsErrors, DiscoverConnectedAppsResponse, DiscoverConnectedAppsResponses, DiscoverConnectorsResponse, DiscoveredApp, DiscoveryRequest, DiscoveryResult, DocumentId, EditQueuedActionData, EditQueuedActionError, EditQueuedActionErrors, EditQueuedActionRequest, EditQueuedActionResponse, EditQueuedActionResponses, ElicitationAnswer, ElicitationContentValue, ElicitationRequestId, EmailSearchSuggestions, EmailSuggestions, ExecutionActivity, ExecutionId, ExecutionRecord, ExecutionStatus, ExternalSessionResponse, ExtractData, ExtractErrors, ExtractInputRequest, ExtractInputResponse, ExtractResponse, ExtractResponses, FileChangeKindDto, GetAgentAutoArchivePreferencesData, GetAgentAutoArchivePreferencesError, GetAgentAutoArchivePreferencesErrors, GetAgentAutoArchivePreferencesResponse, GetAgentAutoArchivePreferencesResponses, GetAgentCodingPreferencesData, GetAgentCodingPreferencesError, GetAgentCodingPreferencesErrors, GetAgentCodingPreferencesResponse, GetAgentCodingPreferencesResponses, GetAgentSandboxSizeData, GetAgentSandboxSizeError, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponse, GetAgentSandboxSizeResponses, GetAgentSessionAutoArchiveData, GetAgentSessionAutoArchiveError, GetAgentSessionAutoArchiveErrors, GetAgentSessionAutoArchiveResponse, GetAgentSessionAutoArchiveResponses, GetAgentSessionChangesData, GetAgentSessionChangesError, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchError, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponse, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponse, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionError, GetAgentSessionErrors, GetAgentSessionFoldedLogData, GetAgentSessionFoldedLogError, GetAgentSessionFoldedLogErrors, GetAgentSessionFoldedLogResponse, GetAgentSessionFoldedLogResponses, GetAgentSessionLogData, GetAgentSessionLogError, GetAgentSessionLogErrors, GetAgentSessionLogResponse, GetAgentSessionLogResponses, GetAgentSessionPermissionsData, GetAgentSessionPermissionsError, GetAgentSessionPermissionsErrors, GetAgentSessionPermissionsResponse, GetAgentSessionPermissionsResponses, GetAgentSessionQueueData, GetAgentSessionQueueError, GetAgentSessionQueueErrors, GetAgentSessionQueueResponse, GetAgentSessionQueueResponses, GetAgentSessionResponse, GetAgentSessionResponses, GetCodeExecutionData, GetCodeExecutionErrors, GetCodeExecutionResponse, GetCodeExecutionResponses, GetSessionReviewData, GetSessionReviewErrors, GetSessionReviewResponse, GetSessionReviewResponses, GitRefDto, InputIntent, InputPropertyDefinition, InputPropertySuggestion, InputSuggestions, IntentScore, LinkAgentSessionPullRequestData, LinkAgentSessionPullRequestError, LinkAgentSessionPullRequestErrors, LinkAgentSessionPullRequestResponse, LinkAgentSessionPullRequestResponses, LinkShare, ListAgentConversationsData, ListAgentConversationsErrors, ListAgentConversationsResponse, ListAgentConversationsResponses, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponse, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponse, ListAgentRepositoryBranchesResponses, ListAgentSessionPullRequestsData, ListAgentSessionPullRequestsError, ListAgentSessionPullRequestsErrors, ListAgentSessionPullRequestsResponse, ListAgentSessionPullRequestsResponses, ListAgentWorkRegistrationsData, ListAgentWorkRegistrationsError, ListAgentWorkRegistrationsErrors, ListAgentWorkRegistrationsResponse, ListAgentWorkRegistrationsResponses, ListConnectedAppToolsData, ListConnectedAppToolsErrors, ListConnectedAppToolsResponse, ListConnectedAppToolsResponses, ListExecutionConnectedAppsData, ListExecutionConnectedAppsErrors, ListExecutionConnectedAppsResponse, ListExecutionConnectedAppsResponses, ListExecutionReviewsData, ListExecutionReviewsErrors, ListExecutionReviewsResponse, ListExecutionReviewsResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponse, LoadAgentModelsHandlerResponses, LoadAgentModelsRequest, LoadAgentModelsResponse, LogDirectionDto, LogFrameDto, MessageParent, MessageSuggestions, ModelHarnessDto, MonthlyWeekday, NoteSuggestions, PermissionAnswer, PresentSessionViewData, PresentSessionViewErrors, PresentSessionViewResponse, PresentSessionViewResponses, PresentView, PreviewAgentSessionsData, PreviewAgentSessionsError, PreviewAgentSessionsErrors, PreviewAgentSessionsRequest, PreviewAgentSessionsResponse, PreviewAgentSessionsResponse2, PreviewAgentSessionsResponses, PromptAttachment, PullRequestLinkedSession, PullRequestLinkSource, PullRequestSessions, PullRequestSessionsResponse, PullRequestsSessionsResponse, PullRequestUrl, PullRequestUrls, PutAgentAutoArchivePreferencesData, PutAgentAutoArchivePreferencesError, PutAgentAutoArchivePreferencesErrors, PutAgentAutoArchivePreferencesResponse, PutAgentAutoArchivePreferencesResponses, PutAgentCodingPreferencesData, PutAgentCodingPreferencesError, PutAgentCodingPreferencesErrors, PutAgentCodingPreferencesResponse, PutAgentCodingPreferencesResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeError, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponse, PutAgentSandboxSizeResponses, PutAgentSessionAutoArchiveData, PutAgentSessionAutoArchiveError, PutAgentSessionAutoArchiveErrors, PutAgentSessionAutoArchiveResponse, PutAgentSessionAutoArchiveResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeError, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponse, PutAgentSessionSandboxSizeResponses, QuerySearchSuggestions, QueuedActionDto, RecordedCallStatus, RecordedToolCall, RecurrenceEnd, RecurrenceFrequency, RecurrenceSuggestion, RefreshAgentSessionChangesData, RefreshAgentSessionChangesError, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponse, RefreshAgentSessionChangesResponses, RegisterAgentSessionWorkData, RegisterAgentSessionWorkError, RegisterAgentSessionWorkErrors, RegisterAgentSessionWorkResponse, RegisterAgentSessionWorkResponses, RemoveQueuedActionData, RemoveQueuedActionError, RemoveQueuedActionErrors, RemoveQueuedActionResponse, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionError, RenameAgentSessionErrors, RenameAgentSessionRequest, RenameAgentSessionResponse, RenameAgentSessionResponses, ReportAgentSessionAppConnectedData, ReportAgentSessionAppConnectedError, ReportAgentSessionAppConnectedErrors, ReportAgentSessionAppConnectedResponses, RetryAgentConversationTurnData, RetryAgentConversationTurnErrors, RetryAgentConversationTurnRequest, RetryAgentConversationTurnResponse, RetryAgentConversationTurnResponses, ReviewDecision, ReviewDecisionContext, ReviewId, ReviewRecord, SandboxSize, SandboxSizeBody, SearchConnectedAppToolsData, SearchConnectedAppToolsErrors, SearchConnectedAppToolsResponse, SearchConnectedAppToolsResponses, SearchSuggestions, SearchType, SessionAutoArchiveResponse, SessionBot, SessionPullRequestLink, SessionPullRequestsResponse, SessionStatusDto, SetAgentSessionArchivedData, SetAgentSessionArchivedError, SetAgentSessionArchivedErrors, SetAgentSessionArchivedRequest, SetAgentSessionArchivedResponse, SetAgentSessionArchivedResponses, SharePermissionV2, StartFreshAgentConversationData, StartFreshAgentConversationErrors, StartFreshAgentConversationRequest, StartFreshAgentConversationResponse, StartFreshAgentConversationResponses, SteerQueuedActionData, SteerQueuedActionError, SteerQueuedActionErrors, SteerQueuedActionResponse, SteerQueuedActionResponses, TaskSearchSuggestions, TaskSuggestions, ToolActor, ToolApprovalAnswerDto, ToolApprovalStatusDto, UnlinkAgentSessionPullRequestData, UnlinkAgentSessionPullRequestError, UnlinkAgentSessionPullRequestErrors, UnlinkAgentSessionPullRequestResponse, UnlinkAgentSessionPullRequestResponses, UnregisterAgentSessionWorkData, UnregisterAgentSessionWorkError, UnregisterAgentSessionWorkErrors, UnregisterAgentSessionWorkResponse, UnregisterAgentSessionWorkResponses, UpdateAgentSessionPermissionsData, UpdateAgentSessionPermissionsError, UpdateAgentSessionPermissionsErrors, UpdateAgentSessionPermissionsResponse, UpdateAgentSessionPermissionsResponses, UpdateChannelSharePermission, UpdateOperation, UpdateSharePermissionRequestV2, WarmAgentSessionHandlerData, WarmAgentSessionHandlerResponse, WarmAgentSessionHandlerResponses, WarmAgentSessionRequest, WarmAgentSessionResponse, WeekdayCode, WithAgentSessionId, WorkRegistrationResponse } from './types.gen';
diff --git a/packages/sdk/generated/agent-harness/sdk.gen.ts b/packages/sdk/generated/agent-harness/sdk.gen.ts
index e2e122e7ae..d0c0ece5c6 100644
--- a/packages/sdk/generated/agent-harness/sdk.gen.ts
+++ b/packages/sdk/generated/agent-harness/sdk.gen.ts
@@ -2,7 +2,7 @@
import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client';
import { client } from './client.gen';
-import type { AddConnectedMcpServerData, AddConnectedMcpServerErrors, AddConnectedMcpServerResponses, AgentSessionsForPullRequestData, AgentSessionsForPullRequestErrors, AgentSessionsForPullRequestResponses, AgentSessionsForPullRequestsData, AgentSessionsForPullRequestsErrors, AgentSessionsForPullRequestsResponses, AnswerAgentSessionToolApprovalData, AnswerAgentSessionToolApprovalErrors, AnswerAgentSessionToolApprovalResponses, CallConnectedAppToolData, CallConnectedAppToolErrors, CallConnectedAppToolResponses, ChooseAgentModeData, ChooseAgentModeErrors, ChooseAgentModeResponses, ClassifyData, ClassifyErrors, ClassifyResponses, ControlAgentSessionData, ControlAgentSessionErrors, ControlAgentSessionResponses, CreateAgentSessionData, CreateAgentSessionErrors, CreateAgentSessionResponses, CreateSessionReviewData, CreateSessionReviewErrors, CreateSessionReviewResponses, DecideSessionReviewData, DecideSessionReviewErrors, DecideSessionReviewResponses, DeleteAgentSessionData, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DiscoverAgentCapabilitiesHandlerData, DiscoverAgentCapabilitiesHandlerErrors, DiscoverAgentCapabilitiesHandlerResponses, DiscoverConnectedAppsData, DiscoverConnectedAppsErrors, DiscoverConnectedAppsResponses, EditQueuedActionData, EditQueuedActionErrors, EditQueuedActionResponses, ExtractData, ExtractErrors, ExtractResponses, GetAgentAutoArchivePreferencesData, GetAgentAutoArchivePreferencesErrors, GetAgentAutoArchivePreferencesResponses, GetAgentCodingPreferencesData, GetAgentCodingPreferencesErrors, GetAgentCodingPreferencesResponses, GetAgentSandboxSizeData, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponses, GetAgentSessionAutoArchiveData, GetAgentSessionAutoArchiveErrors, GetAgentSessionAutoArchiveResponses, GetAgentSessionChangesData, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionErrors, GetAgentSessionFoldedLogData, GetAgentSessionFoldedLogErrors, GetAgentSessionFoldedLogResponses, GetAgentSessionLogData, GetAgentSessionLogErrors, GetAgentSessionLogResponses, GetAgentSessionPermissionsData, GetAgentSessionPermissionsErrors, GetAgentSessionPermissionsResponses, GetAgentSessionQueueData, GetAgentSessionQueueErrors, GetAgentSessionQueueResponses, GetAgentSessionResponses, GetCodeExecutionData, GetCodeExecutionErrors, GetCodeExecutionResponses, GetSessionReviewData, GetSessionReviewErrors, GetSessionReviewResponses, LinkAgentSessionPullRequestData, LinkAgentSessionPullRequestErrors, LinkAgentSessionPullRequestResponses, ListAgentConversationsData, ListAgentConversationsErrors, ListAgentConversationsResponses, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponses, ListAgentSessionPullRequestsData, ListAgentSessionPullRequestsErrors, ListAgentSessionPullRequestsResponses, ListConnectedAppToolsData, ListConnectedAppToolsErrors, ListConnectedAppToolsResponses, ListExecutionConnectedAppsData, ListExecutionConnectedAppsErrors, ListExecutionConnectedAppsResponses, ListExecutionReviewsData, ListExecutionReviewsErrors, ListExecutionReviewsResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponses, PresentSessionViewData, PresentSessionViewErrors, PresentSessionViewResponses, PreviewAgentSessionsData, PreviewAgentSessionsErrors, PreviewAgentSessionsResponses, PutAgentAutoArchivePreferencesData, PutAgentAutoArchivePreferencesErrors, PutAgentAutoArchivePreferencesResponses, PutAgentCodingPreferencesData, PutAgentCodingPreferencesErrors, PutAgentCodingPreferencesResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponses, PutAgentSessionAutoArchiveData, PutAgentSessionAutoArchiveErrors, PutAgentSessionAutoArchiveResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponses, RefreshAgentSessionChangesData, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponses, RemoveQueuedActionData, RemoveQueuedActionErrors, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionErrors, RenameAgentSessionResponses, ReportAgentSessionAppConnectedData, ReportAgentSessionAppConnectedErrors, ReportAgentSessionAppConnectedResponses, RetryAgentConversationTurnData, RetryAgentConversationTurnErrors, RetryAgentConversationTurnResponses, SearchConnectedAppToolsData, SearchConnectedAppToolsErrors, SearchConnectedAppToolsResponses, SetAgentSessionArchivedData, SetAgentSessionArchivedErrors, SetAgentSessionArchivedResponses, StartFreshAgentConversationData, StartFreshAgentConversationErrors, StartFreshAgentConversationResponses, SteerQueuedActionData, SteerQueuedActionErrors, SteerQueuedActionResponses, UnlinkAgentSessionPullRequestData, UnlinkAgentSessionPullRequestErrors, UnlinkAgentSessionPullRequestResponses, UpdateAgentSessionPermissionsData, UpdateAgentSessionPermissionsErrors, UpdateAgentSessionPermissionsResponses, WarmAgentSessionHandlerData, WarmAgentSessionHandlerResponses } from './types.gen';
+import type { AddConnectedMcpServerData, AddConnectedMcpServerErrors, AddConnectedMcpServerResponses, AgentSessionsForPullRequestData, AgentSessionsForPullRequestErrors, AgentSessionsForPullRequestResponses, AgentSessionsForPullRequestsData, AgentSessionsForPullRequestsErrors, AgentSessionsForPullRequestsResponses, AnswerAgentSessionToolApprovalData, AnswerAgentSessionToolApprovalErrors, AnswerAgentSessionToolApprovalResponses, CallConnectedAppToolData, CallConnectedAppToolErrors, CallConnectedAppToolResponses, ChooseAgentModeData, ChooseAgentModeErrors, ChooseAgentModeResponses, ClassifyData, ClassifyErrors, ClassifyResponses, ControlAgentSessionData, ControlAgentSessionErrors, ControlAgentSessionResponses, CreateAgentSessionData, CreateAgentSessionErrors, CreateAgentSessionResponses, CreateSessionReviewData, CreateSessionReviewErrors, CreateSessionReviewResponses, DecideSessionReviewData, DecideSessionReviewErrors, DecideSessionReviewResponses, DeleteAgentSessionData, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DiscoverAgentCapabilitiesHandlerData, DiscoverAgentCapabilitiesHandlerErrors, DiscoverAgentCapabilitiesHandlerResponses, DiscoverConnectedAppsData, DiscoverConnectedAppsErrors, DiscoverConnectedAppsResponses, EditQueuedActionData, EditQueuedActionErrors, EditQueuedActionResponses, ExtractData, ExtractErrors, ExtractResponses, GetAgentAutoArchivePreferencesData, GetAgentAutoArchivePreferencesErrors, GetAgentAutoArchivePreferencesResponses, GetAgentCodingPreferencesData, GetAgentCodingPreferencesErrors, GetAgentCodingPreferencesResponses, GetAgentSandboxSizeData, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponses, GetAgentSessionAutoArchiveData, GetAgentSessionAutoArchiveErrors, GetAgentSessionAutoArchiveResponses, GetAgentSessionChangesData, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionErrors, GetAgentSessionFoldedLogData, GetAgentSessionFoldedLogErrors, GetAgentSessionFoldedLogResponses, GetAgentSessionLogData, GetAgentSessionLogErrors, GetAgentSessionLogResponses, GetAgentSessionPermissionsData, GetAgentSessionPermissionsErrors, GetAgentSessionPermissionsResponses, GetAgentSessionQueueData, GetAgentSessionQueueErrors, GetAgentSessionQueueResponses, GetAgentSessionResponses, GetCodeExecutionData, GetCodeExecutionErrors, GetCodeExecutionResponses, GetSessionReviewData, GetSessionReviewErrors, GetSessionReviewResponses, LinkAgentSessionPullRequestData, LinkAgentSessionPullRequestErrors, LinkAgentSessionPullRequestResponses, ListAgentConversationsData, ListAgentConversationsErrors, ListAgentConversationsResponses, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponses, ListAgentSessionPullRequestsData, ListAgentSessionPullRequestsErrors, ListAgentSessionPullRequestsResponses, ListAgentWorkRegistrationsData, ListAgentWorkRegistrationsErrors, ListAgentWorkRegistrationsResponses, ListConnectedAppToolsData, ListConnectedAppToolsErrors, ListConnectedAppToolsResponses, ListExecutionConnectedAppsData, ListExecutionConnectedAppsErrors, ListExecutionConnectedAppsResponses, ListExecutionReviewsData, ListExecutionReviewsErrors, ListExecutionReviewsResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponses, PresentSessionViewData, PresentSessionViewErrors, PresentSessionViewResponses, PreviewAgentSessionsData, PreviewAgentSessionsErrors, PreviewAgentSessionsResponses, PutAgentAutoArchivePreferencesData, PutAgentAutoArchivePreferencesErrors, PutAgentAutoArchivePreferencesResponses, PutAgentCodingPreferencesData, PutAgentCodingPreferencesErrors, PutAgentCodingPreferencesResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponses, PutAgentSessionAutoArchiveData, PutAgentSessionAutoArchiveErrors, PutAgentSessionAutoArchiveResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponses, RefreshAgentSessionChangesData, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponses, RegisterAgentSessionWorkData, RegisterAgentSessionWorkErrors, RegisterAgentSessionWorkResponses, RemoveQueuedActionData, RemoveQueuedActionErrors, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionErrors, RenameAgentSessionResponses, ReportAgentSessionAppConnectedData, ReportAgentSessionAppConnectedErrors, ReportAgentSessionAppConnectedResponses, RetryAgentConversationTurnData, RetryAgentConversationTurnErrors, RetryAgentConversationTurnResponses, SearchConnectedAppToolsData, SearchConnectedAppToolsErrors, SearchConnectedAppToolsResponses, SetAgentSessionArchivedData, SetAgentSessionArchivedErrors, SetAgentSessionArchivedResponses, StartFreshAgentConversationData, StartFreshAgentConversationErrors, StartFreshAgentConversationResponses, SteerQueuedActionData, SteerQueuedActionErrors, SteerQueuedActionResponses, UnlinkAgentSessionPullRequestData, UnlinkAgentSessionPullRequestErrors, UnlinkAgentSessionPullRequestResponses, UnregisterAgentSessionWorkData, UnregisterAgentSessionWorkErrors, UnregisterAgentSessionWorkResponses, UpdateAgentSessionPermissionsData, UpdateAgentSessionPermissionsErrors, UpdateAgentSessionPermissionsResponses, WarmAgentSessionHandlerData, WarmAgentSessionHandlerResponses } from './types.gen';
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {
/**
@@ -708,6 +708,30 @@ export class Sdk extends HeyApiClient {
});
}
+ /**
+ * End the caller's own registration of a session. Repeating does nothing. It touches only the
+ * caller's own row, so it needs no access to the session: losing access must not strand it.
+ */
+ public unregisterAgentSessionWork<ThrowOnError extends boolean = false>(options: Options<UnregisterAgentSessionWorkData, ThrowOnError>): RequestResult<UnregisterAgentSessionWorkResponses, UnregisterAgentSessionWorkErrors, ThrowOnError> {
+ return (options.client ?? this.client).delete<UnregisterAgentSessionWorkResponses, UnregisterAgentSessionWorkErrors, ThrowOnError>({ url: '/agent-sessions/{session_id}/work-registration', ...options });
+ }
+
+ /**
+ * Register a session as the caller's work. Requires edit access. Repeating returns the active
+ * registration. Registering does not share the session: viewers who cannot open it do not see
+ * it, so share it too.
+ */
+ public registerAgentSessionWork<ThrowOnError extends boolean = false>(options: Options<RegisterAgentSessionWorkData, ThrowOnError>): RequestResult<RegisterAgentSessionWorkResponses, RegisterAgentSessionWorkErrors, ThrowOnError> {
+ return (options.client ?? this.client).put<RegisterAgentSessionWorkResponses, RegisterAgentSessionWorkErrors, ThrowOnError>({ url: '/agent-sessions/{session_id}/work-registration', ...options });
+ }
+
+ /**
+ * List the caller's active registrations of sessions they can still view, newest first.
+ */
+ public listAgentWorkRegistrations<ThrowOnError extends boolean = false>(options?: Options<ListAgentWorkRegistrationsData, ThrowOnError>): RequestResult<ListAgentWorkRegistrationsResponses, ListAgentWorkRegistrationsErrors, ThrowOnError> {
+ return (options?.client ?? this.client).get<ListAgentWorkRegistrationsResponses, ListAgentWorkRegistrationsErrors, ThrowOnError>({ url: '/agent-work-registrations', ...options });
+ }
+
/**
* Classify a draft for the authenticated user.
*/
diff --git a/packages/sdk/generated/agent-harness/types.gen.ts b/packages/sdk/generated/agent-harness/types.gen.ts
index 705365920f..a713513783 100644
--- a/packages/sdk/generated/agent-harness/types.gen.ts
+++ b/packages/sdk/generated/agent-harness/types.gen.ts
@@ -2705,6 +2705,28 @@ export type WithAgentSessionId = {
id: string;
};
+/**
+ * One account's active registration of one session as its work.
+ */
+export type WorkRegistrationResponse = {
+ /**
+ * The account whose work this is.
+ */
+ accountId: string;
+ /**
+ * The session registered.
+ */
+ agentSessionId: string;
+ /**
+ * The registration.
+ */
+ id: string;
+ /**
+ * When the account registered it.
+ */
+ registeredAt: string;
+};
+
export type GetAgentAutoArchivePreferencesData = {
body?: never;
path?: never;
@@ -4222,6 +4244,81 @@ export type PresentSessionViewResponses = {
export type PresentSessionViewResponse = PresentSessionViewResponses[keyof PresentSessionViewResponses];
+export type UnregisterAgentSessionWorkData = {
+ body?: never;
+ path: {
+ /**
+ * ID of the agent session
+ */
+ session_id: string;
+ };
+ query?: never;
+ url: '/agent-sessions/{session_id}/work-registration';
+};
+
+export type UnregisterAgentSessionWorkErrors = {
+ 401: string;
+ 500: string;
+};
+
+export type UnregisterAgentSessionWorkError = UnregisterAgentSessionWorkErrors[keyof UnregisterAgentSessionWorkErrors];
+
+export type UnregisterAgentSessionWorkResponses = {
+ /**
+ * The caller has no active registration of the session
+ */
+ 204: void;
+};
+
+export type UnregisterAgentSessionWorkResponse = UnregisterAgentSessionWorkResponses[keyof UnregisterAgentSessionWorkResponses];
+
+export type RegisterAgentSessionWorkData = {
+ body?: never;
+ path: {
+ /**
+ * ID of the agent session
+ */
+ session_id: string;
+ };
+ query?: never;
+ url: '/agent-sessions/{session_id}/work-registration';
+};
+
+export type RegisterAgentSessionWorkErrors = {
+ 401: string;
+ 403: string;
+ 409: string;
+ 500: string;
+};
+
+export type RegisterAgentSessionWorkError = RegisterAgentSessionWorkErrors[keyof RegisterAgentSessionWorkErrors];
+
+export type RegisterAgentSessionWorkResponses = {
+ 200: WorkRegistrationResponse;
+};
+
+export type RegisterAgentSessionWorkResponse = RegisterAgentSessionWorkResponses[keyof RegisterAgentSessionWorkResponses];
+
+export type ListAgentWorkRegistrationsData = {
+ body?: never;
+ path?: never;
+ query?: never;
+ url: '/agent-work-registrations';
+};
+
+export type ListAgentWorkRegistrationsErrors = {
+ 401: string;
+ 500: string;
+};
+
+export type ListAgentWorkRegistrationsError = ListAgentWorkRegistrationsErrors[keyof ListAgentWorkRegistrationsErrors];
+
+export type ListAgentWorkRegistrationsResponses = {
+ 200: Array<WorkRegistrationResponse>;
+};
+
+export type ListAgentWorkRegistrationsResponse = ListAgentWorkRegistrationsResponses[keyof ListAgentWorkRegistrationsResponses];
+
export type ClassifyData = {
body: ClassifyInputRequest;
path?: never;
diff --git a/packages/sdk/specs/agent-harness.json b/packages/sdk/specs/agent-harness.json
index c707c9a5ff..1dddeb619c 100644
--- a/packages/sdk/specs/agent-harness.json
+++ b/packages/sdk/specs/agent-harness.json
@@ -3345,6 +3345,161 @@
}
}
},
+ "/agent-sessions/{session_id}/work-registration": {
+ "put": {
+ "tags": ["agent-sessions"],
+ "summary": "Register a session as the caller's work. Requires edit access. Repeating returns the active\nregistration. Registering does not share the session: viewers who cannot open it do not see\nit, so share it too.",
+ "operationId": "register_agent_session_work",
+ "parameters": [
+ {
+ "name": "session_id",
+ "in": "path",
+ "description": "ID of the agent session",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/WorkRegistrationResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "409": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ },
+ "delete": {
+ "tags": ["agent-sessions"],
+ "summary": "End the caller's own registration of a session. Repeating does nothing. It touches only the\ncaller's own row, so it needs no access to the session: losing access must not strand it.",
+ "operationId": "unregister_agent_session_work",
+ "parameters": [
+ {
+ "name": "session_id",
+ "in": "path",
+ "description": "ID of the agent session",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "responses": {
+ "204": {
+ "description": "The caller has no active registration of the session"
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/agent-work-registrations": {
+ "get": {
+ "tags": ["agent-sessions"],
+ "summary": "List the caller's active registrations of sessions they can still view, newest first.",
+ "operationId": "list_agent_work_registrations",
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/WorkRegistrationResponse"
+ }
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/universal_input/classify": {
"post": {
"tags": ["universal_input::inbound::axum_router"],
@@ -7347,6 +7502,32 @@
"description": "The session id."
}
}
+ },
+ "WorkRegistrationResponse": {
+ "type": "object",
+ "description": "One account's active registration of one session as its work.",
+ "required": ["id", "accountId", "agentSessionId", "registeredAt"],
+ "properties": {
+ "accountId": {
+ "type": "string",
+ "description": "The account whose work this is."
+ },
+ "agentSessionId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The session registered."
+ },
+ "id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The registration."
+ },
+ "registeredAt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "When the account registered it."
+ }
+ }
}
},
"securitySchemes": {
diff --git a/packages/sdk/src/entities/agent-sessions/agent-session.ts b/packages/sdk/src/entities/agent-sessions/agent-session.ts
index 699c00f04d..726e2d6582 100644
--- a/packages/sdk/src/entities/agent-sessions/agent-session.ts
+++ b/packages/sdk/src/entities/agent-sessions/agent-session.ts
@@ -13,6 +13,7 @@ import type {
PullRequestLinkSource,
SandboxSize,
SessionBot,
+ WorkRegistrationResponse,
} from '../../../generated/agent-harness/types.gen';
import { unwrap } from '../../utils';
import type { MacroClient } from '../../utils/client';
@@ -68,6 +69,16 @@ export type FoldedAgentSessionLog = {
};
/** A GitHub pull request linked to a session. */
+/** An agent session an account registered as its work. */
+export type RegisteredWork = {
+ /** The session registered. */
+ session: AgentSession;
+ /** The account whose work this is. */
+ account: User;
+ /** When the account registered it. */
+ registeredAt: string;
+};
+
export type SessionPullRequest = {
/** The pull request's `owner/repo/pull/number` key. */
githubKey: string;
@@ -406,6 +417,63 @@ export class AgentSession extends MacroEntity<AgentSessionResponse> {
);
}
+ /**
+ * Register this session as the caller's work, so it shows as what the caller
+ * is working on. Requires edit access. Registering again changes nothing.
+ *
+ * Registering does not share the session: a viewer who cannot open it does
+ * not see it, so share it too with {@link AgentSession.updateSharePermissions}.
+ *
+ * The registration ends on its own when the session's pull requests finish,
+ * when it is archived, after a day without work, or after a week blocked on
+ * input. A later turn does not register it again.
+ */
+ async registerAsWork(): Promise<RegisteredWork> {
+ return AgentSession.registeredWork(
+ this.client,
+ unwrap(
+ await this.client.agentHarness.registerAgentSessionWork({
+ path: { session_id: this.id },
+ }),
+ ),
+ );
+ }
+
+ /**
+ * End the caller's registration of this session as its work. Doing it again
+ * changes nothing. The session itself is untouched.
+ */
+ async unregisterAsWork(): Promise<void> {
+ unwrap(
+ await this.client.agentHarness.unregisterAgentSessionWork({
+ path: { session_id: this.id },
+ }),
+ );
+ }
+
+ /** The caller's active registrations, newest first. */
+ static async listRegisteredWork(
+ client: MacroClient,
+ ): Promise<RegisteredWork[]> {
+ const registrations = unwrap(
+ await client.agentHarness.listAgentWorkRegistrations(),
+ );
+ return registrations.map((registration) =>
+ AgentSession.registeredWork(client, registration),
+ );
+ }
+
+ private static registeredWork(
+ client: MacroClient,
+ registration: WorkRegistrationResponse,
+ ): RegisteredWork {
+ return {
+ session: AgentSession.byId(client, registration.agentSessionId),
+ account: User.byId(client, registration.accountId),
+ registeredAt: registration.registeredAt,
+ };
+ }
+
/** Archive this session, making it read-only until unarchived. */
async archive(): Promise<void> {
await this.setArchived(true);
diff --git a/packages/sdk/src/entities/agent-sessions/namespace.ts b/packages/sdk/src/entities/agent-sessions/namespace.ts
index 939b98388e..f145a5a5b5 100644
--- a/packages/sdk/src/entities/agent-sessions/namespace.ts
+++ b/packages/sdk/src/entities/agent-sessions/namespace.ts
@@ -8,6 +8,7 @@ import type { MacroClient } from '../../utils/client';
import {
AgentSession,
type CreateManagedSessionOptions,
+ type RegisteredWork,
type SelectableRepository,
} from './agent-session';
@@ -60,6 +61,15 @@ export class AgentSessionNamespace {
return AgentSession.createManaged(this.client, opts);
}
+ /**
+ * The sessions the caller registered as its work with
+ * {@link AgentSession.registerAsWork} and can still view, newest first.
+ * Ended registrations and archived sessions are left out.
+ */
+ registeredWork(): Promise<RegisteredWork[]> {
+ return AgentSession.listRegisteredWork(this.client);
+ }
+
/**
* Whether `prompt` needs a chat agent (`'chat'`) or a coding agent
* (`'code'`), as the app's Auto mode decides before starting a session.
diff --git a/packages/sdk/tests/agent-sessions.test.ts b/packages/sdk/tests/agent-sessions.test.ts
index 4412b0d965..2c4b443d60 100644
--- a/packages/sdk/tests/agent-sessions.test.ts
+++ b/packages/sdk/tests/agent-sessions.test.ts
@@ -220,6 +220,47 @@ describe('AgentSession', () => {
await expect(requests[1]?.json()).resolves.toEqual({ archived: false });
});
+ test('registers, unregisters, and lists work as entity handles', async () => {
+ const registration = {
+ id: '0198a4cc-e138-7670-a308-a6b766602702',
+ accountId: 'macro|[email protected]',
+ agentSessionId: sessionId,
+ registeredAt: '2026-08-24T12:00:00Z',
+ };
+ const requests: Request[] = [];
+ globalThis.fetch = (async (input) => {
+ const request = input instanceof Request ? input : new Request(input);
+ requests.push(request);
+ if (request.method === 'DELETE') {
+ return new Response(null, { status: 204 });
+ }
+ return Response.json(
+ request.method === 'PUT' ? registration : [registration],
+ );
+ }) as typeof fetch;
+ const macro = new Macro({
+ token: 'user-token',
+ hosts: { 'agent-harness': 'https://agent.example.test' },
+ });
+ const agentSession = macro.agentSessions.byId(sessionId);
+
+ const registered = await agentSession.registerAsWork();
+ await agentSession.unregisterAsWork();
+ const [listed] = await macro.agentSessions.registeredWork();
+
+ expect(registered.session.id).toBe(sessionId);
+ expect(registered.account.id).toBe('macro|[email protected]');
+ expect(registered.registeredAt).toBe('2026-08-24T12:00:00Z');
+ expect(listed?.session.id).toBe(sessionId);
+ expect(
+ requests.map((request) => `${request.method} ${request.url}`),
+ ).toEqual([
+ `PUT https://agent.example.test/agent-sessions/${sessionId}/work-registration`,
+ `DELETE https://agent.example.test/agent-sessions/${sessionId}/work-registration`,
+ 'GET https://agent.example.test/agent-work-registrations',
+ ]);
+ });
+
test('resizes a session sandbox through the agent-harness service', async () => {
let request: Request | undefined;
globalThis.fetch = (async (input) => {
diff --git a/services/agent_harness_service/AGENTS.md b/services/agent_harness_service/AGENTS.md
index 0267acfc46..2e75bea9b0 100644
--- a/services/agent_harness_service/AGENTS.md
+++ b/services/agent_harness_service/AGENTS.md
@@ -23,7 +23,9 @@ Pulumi stacks; they do not host extra agent processes.
- `src/trigger.rs`: turns channel/webhook triggers into sessions.
- `src/pull_request_archive.rs`: consumes `macro.github_pull_requests` (group
`agent-harness-pull-request-archive`) and auto-archives sessions whose
- linked pull requests finished (`agent_session::domain::auto_archive`).
+ linked pull requests finished (`agent_session::domain::auto_archive`), and
+ ends their work registrations first
+ (`agent_session::domain::work_registration`).
- `src/internal_mcp.rs`: the internal MCP server exposed to running sessions.
- `src/public_mcp.rs` + `src/public_mcp/`: public workspace MCP and OAuth;
reuses the harness tool context and retains bearer authentication. Users with
diff --git a/services/agent_harness_service/Cargo.toml b/services/agent_harness_service/Cargo.toml
index ee05ed4e75..a091b51068 100644
--- a/services/agent_harness_service/Cargo.toml
+++ b/services/agent_harness_service/Cargo.toml
@@ -134,6 +134,7 @@ macro_entrypoint = { path = "../../crates/macro_entrypoint" }
macro_env = { path = "../../crates/macro_env" }
macro_env_var = { path = "../../crates/macro_env_var" }
macro_event_broker = { path = "../../crates/macro_event_broker", features = ["outbound"] }
+soup_realtime = { path = "../../crates/soup_realtime", default-features = false, features = ["outbound"] }
macro_event_topics = { path = "../../crates/macro_event_topics" }
macro_middleware = { path = "../../crates/macro_middleware", default-features = false, features = ["cloud_storage"] }
macro_queues = { path = "../../crates/macro_queues" }
diff --git a/services/agent_harness_service/src/api.rs b/services/agent_harness_service/src/api.rs
index b4d47579e0..7aa73f09ef 100644
--- a/services/agent_harness_service/src/api.rs
+++ b/services/agent_harness_service/src/api.rs
@@ -83,6 +83,7 @@ pub struct ApiStates<T, R, Opener, Bots, Requests, Access, Auth, Models, Changes
conversations: Router,
pull_requests: Router,
auto_archive: Router,
+ work_registrations: Router,
tool_approvals: Router,
app_connections: Router,
code_executions: Router,
@@ -124,6 +125,7 @@ impl<T, R, Opener, Bots, Requests, Access, Auth, Models, Changes>
conversations: Router::new(),
pull_requests: Router::new(),
auto_archive: Router::new(),
+ work_registrations: Router::new(),
tool_approvals: Router::new(),
app_connections: Router::new(),
code_executions: Router::new(),
@@ -228,6 +230,12 @@ impl<T, R, Opener, Bots, Requests, Access, Auth, Models, Changes>
self
}
+ /// Attach the routes registering sessions as the caller's work.
+ pub fn with_work_registrations(mut self, router: Router) -> Self {
+ self.work_registrations = router;
+ self
+ }
+
/// Attach the routes answering tool calls held for the owner's approval.
pub fn with_tool_approvals(mut self, router: Router) -> Self {
self.tool_approvals = router;
@@ -367,6 +375,7 @@ where
.merge(agent_sandbox_size_router(states.read.clone()))
.merge(agent_coding_preferences_router(states.read))
.merge(states.auto_archive)
+ .merge(states.work_registrations)
.merge(agent_models_router(states.models))
.merge(agent_repositories_router(states.repositories))
.merge(states.routine_sessions)
diff --git a/services/agent_harness_service/src/api/swagger.rs b/services/agent_harness_service/src/api/swagger.rs
index 42ce0c8a36..ac895f4131 100644
--- a/services/agent_harness_service/src/api/swagger.rs
+++ b/services/agent_harness_service/src/api/swagger.rs
@@ -32,6 +32,7 @@ use agent_session::inbound::axum_router::pull_requests::{
PullRequestSessionsResponse, PullRequestUrl, PullRequestUrls, PullRequestsSessionsResponse,
SessionPullRequestsResponse,
};
+use agent_session::inbound::axum_router::work_registration::WorkRegistrationResponse;
use agent_session::inbound::axum_router::{
self, AgentSessionFoldedLogResponse, AgentSessionLogEntryDto, AgentSessionLogResponse,
AgentSessionPreviewData, AgentSessionPreviewDto, AgentSessionQueueResponse,
@@ -108,6 +109,9 @@ impl Modify for SecurityAddon {
axum_router::auto_archive::put_auto_archive_preferences,
axum_router::auto_archive::get_session_auto_archive,
axum_router::auto_archive::put_session_auto_archive,
+ axum_router::work_registration::register_work,
+ axum_router::work_registration::unregister_work,
+ axum_router::work_registration::list_own_work,
model_load::load_agent_models_handler,
capability_discovery::discover_agent_capabilities_handler,
agent_harness::inbound::conversations::list_agent_conversations,
@@ -166,6 +170,7 @@ impl Modify for SecurityAddon {
AutoArchiveOverridesBody,
ArchiveCause,
SessionAutoArchiveResponse,
+ WorkRegistrationResponse,
LoadAgentModelsRequest,
LoadAgentModelsResponse,
AgentModelDto,
diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rs
index 81aee2acba..c1cfe0e9bc 100644
--- a/services/agent_harness_service/src/main.rs
+++ b/services/agent_harness_service/src/main.rs
@@ -100,6 +100,7 @@ use agent_runtime_directory::PgAgentRuntimeDirectory;
use agent_session::domain::model::{AgentMcpServers, ReplicaId};
use agent_session::domain::ports::{NoOpRealtime, SessionOwnership as _};
use agent_session::domain::service::{AgentSessionService, AgentSessionServiceImpl};
+use agent_session::domain::work_registration::{WorkRegistrationRealtime, WorkRegistrationService};
use agent_session::inbound::axum_router::{
AgentSessionControlState, AgentSessionRouterState, CreateSessionState,
};
@@ -322,6 +323,20 @@ async fn run() -> anyhow::Result<()> {
.context("failed to create kafka event publisher")?,
macro_event_broker::GlobalSpawner,
);
+ // Registered work viewers hear session changes as Soup patches, which the GraphQL process
+ // already streams to each of them. Signals run off the publishing task.
+ let work_registration_signal =
+ soup_realtime::outbound::agent_sessions::SoupWorkRegistrationSignal(Arc::new(
+ soup_realtime::domain::service::SoupRealtimeServiceImpl::new(
+ soup_realtime::outbound::entity_access::EntityAccessExpander::new(
+ (*entity_access).clone(),
+ ),
+ soup_realtime::outbound::kafka_publisher::KafkaSoupRealtimePublisher::new(
+ broker.clone(),
+ ),
+ ),
+ ));
+ let work_registration_tasks = tokio_util::task::TaskTracker::new();
let notifications = Arc::new(notification::domain::service::SqsNotificationIngress {
queue: notification::outbound::queue::SqsQueue::new(
aws_sdk_sqs::Client::new(&aws_config),
@@ -386,12 +401,17 @@ async fn run() -> anyhow::Result<()> {
// Frames reach this process's viewers through the gateway and every
// other process's through the Redis log stream (the GraphQL log
// subscription).
- RedisLogStreamRealtime::new(
- ConnectionGatewayAgentSessionRealtime::new(
- connection_gateway.clone(),
- session_audience.clone(),
+ WorkRegistrationRealtime::new(
+ RedisLogStreamRealtime::new(
+ ConnectionGatewayAgentSessionRealtime::new(
+ connection_gateway.clone(),
+ session_audience.clone(),
+ ),
+ redis.clone(),
),
- redis.clone(),
+ session_repo.clone(),
+ work_registration_signal.clone(),
+ work_registration_tasks.clone(),
),
// After each finished turn Jev decides whether a generated name has
// stopped fitting; only then does Haiku propose a new one. Without a
@@ -834,9 +854,14 @@ async fn run() -> anyhow::Result<()> {
execution_store,
execution_turns,
));
- let session_metadata_realtime = ConnectionGatewayAgentSessionRealtime::new(
- connection_gateway.clone(),
- session_audience.clone(),
+ let session_metadata_realtime = WorkRegistrationRealtime::new(
+ ConnectionGatewayAgentSessionRealtime::new(
+ connection_gateway.clone(),
+ session_audience.clone(),
+ ),
+ session_repo.clone(),
+ work_registration_signal.clone(),
+ work_registration_tasks.clone(),
);
let auto_archive_settings = agent_session::domain::auto_archive::AutoArchiveService::new(
session_repo.clone(),
@@ -1602,9 +1627,14 @@ async fn run() -> anyhow::Result<()> {
AgentSessionServiceImpl::new(
session_repo.clone(),
FoldedMessageService::new(session_repo.clone()),
- ConnectionGatewayAgentSessionRealtime::new(
- connection_gateway.clone(),
- session_audience.clone(),
+ WorkRegistrationRealtime::new(
+ ConnectionGatewayAgentSessionRealtime::new(
+ connection_gateway.clone(),
+ session_audience.clone(),
+ ),
+ session_repo.clone(),
+ work_registration_signal.clone(),
+ work_registration_tasks.clone(),
),
NoOpAgentSessionNameGenerator,
Arc::new(NoOpTurnObserver),
@@ -1747,6 +1777,21 @@ async fn run() -> anyhow::Result<()> {
MacroAuthorizationState::new(Arc::new(authorization_service.clone())),
),
);
+ let work_registrations_service = WorkRegistrationService::new(
+ session_repo.clone(),
+ Arc::new(
+ agent_session::domain::audience::EntityAccessSessionView::new((*entity_access).clone()),
+ ),
+ work_registration_signal.clone(),
+ );
+ let work_registrations =
+ agent_session::inbound::axum_router::work_registration::work_registration_router(
+ AgentSessionRouterState::new(
+ work_registrations_service.clone(),
+ entity_access.clone(),
+ MacroAuthorizationState::new(Arc::new(authorization_service.clone())),
+ ),
+ );
let code_executions = agent_code_mode::inbound::axum_router::code_execution_router(
agent_code_mode::inbound::axum_router::CodeExecutionRouterState::new(
code_mode,
@@ -1825,6 +1870,7 @@ async fn run() -> anyhow::Result<()> {
.with_mode_choice(mode_choice)
.with_pull_requests(pull_requests)
.with_auto_archive(auto_archive)
+ .with_work_registrations(work_registrations)
.with_tool_approvals(tool_approval_answers)
.with_app_connections(app_connections)
.with_code_executions(code_executions)
@@ -1951,9 +1997,14 @@ async fn run() -> anyhow::Result<()> {
// A hard abort cannot emit a disconnect. Reconcile expired leases so
// viewers stop showing a turn as working without issuing another command.
let recovery_repo = session_repo.clone();
- let recovery_realtime = ConnectionGatewayAgentSessionRealtime::new(
- connection_gateway.clone(),
- session_audience.clone(),
+ let recovery_realtime = WorkRegistrationRealtime::new(
+ ConnectionGatewayAgentSessionRealtime::new(
+ connection_gateway.clone(),
+ session_audience.clone(),
+ ),
+ session_repo.clone(),
+ work_registration_signal.clone(),
+ work_registration_tasks.clone(),
);
let recovery = tokio::spawn(async move {
let mut ticker =
@@ -1996,12 +2047,26 @@ async fn run() -> anyhow::Result<()> {
},
));
+ let work_registration_sweep = work_registrations_service.clone();
+ let work_registration_sweep_shutdown = service_shutdown.clone();
+ tokio::spawn(async move {
+ agent_session::inbound::work_registration_sweep::run_work_registration_sweep(
+ &work_registration_sweep,
+ agent_session::inbound::work_registration_sweep::WORK_REGISTRATION_SWEEP_INITIAL_DELAY,
+ agent_session::inbound::work_registration_sweep::WORK_REGISTRATION_SWEEP_INTERVAL,
+ work_registration_sweep_shutdown.cancelled_owned(),
+ )
+ .await;
+ });
+
+ let pull_request_work_registrations = work_registrations_service;
let pull_request_archive_shutdown = service_shutdown.clone();
let pull_request_archive_brokers = config.kafka_brokers.as_ref().to_owned();
tokio::spawn(async move {
if let Err(error) = pull_request_archive::run(
&pull_request_archive_brokers,
&pull_request_archive,
+ &pull_request_work_registrations,
pull_request_archive_shutdown.clone(),
)
.await
@@ -2269,6 +2334,8 @@ async fn run() -> anyhow::Result<()> {
notification_tasks.wait().await;
auto_archive_tasks.close();
auto_archive_tasks.wait().await;
+ work_registration_tasks.close();
+ work_registration_tasks.wait().await;
http.abort();
trigger.abort();
egress_http.abort();
diff --git a/services/agent_harness_service/src/pull_request_archive.rs b/services/agent_harness_service/src/pull_request_archive.rs
index fbd2d0e068..a8556ec02c 100644
--- a/services/agent_harness_service/src/pull_request_archive.rs
+++ b/services/agent_harness_service/src/pull_request_archive.rs
@@ -1,4 +1,5 @@
-//! Archives sessions whose pull requests merged, from the pull request topic.
+//! Archives sessions whose pull requests merged and ends the work registrations of sessions whose
+//! pull requests finished, from the pull request topic.
//!
//! Every stored pull request change is published after it commits, so the status this reads is
//! at least as new as the event. Offsets are committed after each event; a lookup that keeps
@@ -7,6 +8,7 @@
use std::time::Duration;
use agent_session::domain::auto_archive::AutoArchive;
+use agent_session::domain::work_registration::WorkRegistrations;
use github_pull_requests::broker::{GithubPullRequestMacroEvent, GithubPullRequestTopicEvent};
use kafka_util::{GroupName, InitialOffset, KafkaEventConsumer, consumer_span, record_span_error};
use macro_event_broker::{
@@ -35,10 +37,12 @@ type ArchiveConsumer = MacroEventConsumerService<DeclaredMacroEvent, ArchiveKafk
const LOOKUP_ATTEMPTS: usize = 3;
-/// Consume pull request changes until `shutdown`, archiving the sessions they finish.
+/// Consume pull request changes until `shutdown`, archiving the sessions they finish and ending
+/// their work registrations.
pub async fn run(
brokers: &str,
auto_archive: &impl AutoArchive,
+ work_registrations: &impl WorkRegistrations,
shutdown: CancellationToken,
) -> anyhow::Result<()> {
let consumer = KafkaEventConsumer::<PullRequestArchiveConsumerGroup>::from_env(brokers)?;
@@ -72,6 +76,10 @@ pub async fn run(
tracing::Span::current()
.record("macro.event.id", tracing::field::display(event.event().event_id));
let GithubPullRequestTopicEvent::Updated(update) = &event.event().event;
+ // Before archiving, so these end for their pull requests rather than
+ // for the archive that follows from them.
+ end_finished_work_registrations(work_registrations, &update.github_key)
+ .await;
archive_finished_sessions(auto_archive, &update.github_key).await;
}
Err(error) => {
@@ -106,6 +114,30 @@ async fn archive_finished_sessions(auto_archive: &impl AutoArchive, github_key:
.ok();
}
+async fn end_finished_work_registrations(
+ work_registrations: &impl WorkRegistrations,
+ github_key: &str,
+) {
+ let retries = ExponentialBackoff::from_millis(2)
+ .factor(100)
+ .max_delay(Duration::from_secs(5))
+ .take(LOOKUP_ATTEMPTS - 1);
+ // The sweep catches up on anything skipped here.
+ Retry::start(retries, || {
+ work_registrations.pull_request_changed(github_key)
+ })
+ .await
+ .inspect_err(|error| {
+ tracing::error!(
+ error = ?error,
+ %github_key,
+ attempts = LOOKUP_ATTEMPTS,
+ "skipping work registrations for a pull request after lookup retries"
+ );
+ })
+ .ok();
+}
+
fn commit(consumer: &ArchiveConsumer, message: &BorrowedMessage<'_>) {
consumer
.inner()
diff --git a/services/document_storage_service/src/api/context.rs b/services/document_storage_service/src/api/context.rs
index 365c26761c..cf8e6e6632 100644
--- a/services/document_storage_service/src/api/context.rs
+++ b/services/document_storage_service/src/api/context.rs
@@ -948,6 +948,7 @@ pub(crate) struct ApiContext {
pub graphql_calendar_context: graphql_calendar::CalendarGraphqlContext,
pub graphql_calendar_mutation_context: graphql_calendar::CalendarGraphqlMutationContext,
pub graphql_work_feed_context: complete_graph::WorkFeedGraphqlContext,
+ pub graphql_registered_work_context: complete_graph::RegisteredWorkGraphqlContext,
pub graphql_notification_inbox_context: complete_graph::NotificationInboxGraphqlContext,
pub graphql_initiative_entity_loader: graphql_initiative::InitiativeEntityLoader,
pub graphql_agent_session_entity_loader: graphql_soup::AgentSessionEntityLoader,
diff --git a/services/document_storage_service/src/api/graphql_soup.rs b/services/document_storage_service/src/api/graphql_soup.rs
index af0c4c0953..06d7de936a 100644
--- a/services/document_storage_service/src/api/graphql_soup.rs
+++ b/services/document_storage_service/src/api/graphql_soup.rs
@@ -208,6 +208,7 @@ fn insert_graphql_context_data(
data.insert(state.graphql_calendar_context.clone());
data.insert(state.graphql_calendar_mutation_context.clone());
data.insert(state.graphql_work_feed_context.clone());
+ data.insert(state.graphql_registered_work_context.clone());
data.insert(state.graphql_notification_inbox_context.clone());
data.insert(state.graphql_initiative_entity_loader.clone());
data.insert(state.graphql_agent_session_entity_loader.clone());
diff --git a/services/document_storage_service/src/server.rs b/services/document_storage_service/src/server.rs
index 577edc4c22..cbbfc49b95 100644
--- a/services/document_storage_service/src/server.rs
+++ b/services/document_storage_service/src/server.rs
@@ -2161,6 +2161,22 @@ async fn run_server() -> anyhow::Result<()> {
let feed_viewers: Arc<dyn attention_feed::inbound::viewers::FeedViewerResolver> = Arc::new(
attention_feed::inbound::viewers::EntityAccessFeedViewers(entity_access_service.clone()),
);
+ // Reads the primary: a client refetches right after the change it heard about.
+ let graphql_registered_work_context = complete_graph::RegisteredWorkGraphqlContext::new(
+ agent_session::domain::work_registration::WorkRegistrationService::new(
+ agent_session::outbound::postgres::PgAgentSessionRepo::new(
+ db.clone(),
+ owned_entity_registrar.clone(),
+ ),
+ Arc::new(
+ agent_session::domain::audience::EntityAccessSessionView::new(
+ entity_access_service.as_ref().clone(),
+ ),
+ ),
+ agent_session::domain::work_registration::NoWorkRegistrationSignal,
+ ),
+ soup_realtime_service.clone(),
+ );
let graphql_work_feed_context = complete_graph::WorkFeedGraphqlContext::new(
work_feed::domain::service::WorkFeedServiceImpl::new(
attention_feed::outbound::soup::SoupCandidateSource::new(
@@ -2202,6 +2218,7 @@ async fn run_server() -> anyhow::Result<()> {
sync_sessions,
dictation_state,
graphql_work_feed_context,
+ graphql_registered_work_context,
graphql_notification_inbox_context,
contacts_ingress: contacts_ingress.clone(),
soup_router_state: SoupRouterState::from_arc(
diff --git a/static_assets/schema.graphql b/static_assets/schema.graphql
index 7f21317a13..92d51839d5 100644
--- a/static_assets/schema.graphql
+++ b/static_assets/schema.graphql
@@ -508,6 +508,16 @@ type CompleteSubscriptionRoot {
refetches.
"""
notificationInboxUpdates(scope: NotificationInboxScopeInput): [NotificationInboxPatch!]!
+ """
+ Changes to the registered work of `accountIds` that the authenticated
+ user can see: entries to show, entries to stop showing, and an
+ invalidation when changes may have been missed or sharing changed.
+ Each payload is one batch to apply together. Start it before fetching
+ `registeredWork` and refetch after an invalidation; the stream ends
+ with an error when its source ends, after which the client resubscribes
+ and refetches.
+ """
+ registeredWorkUpdates(accountIds: [ID!]!): [GraphqlRegisteredWorkPatch!]!
}
"""
@@ -7156,6 +7166,63 @@ A property value represented by a type-safe GraphQL union.
"""
union GraphqlPropertyValue = GraphqlBooleanPropertyValue | GraphqlNumberPropertyValue | GraphqlStringPropertyValue | GraphqlDatePropertyValue | GraphqlDateRangePropertyValue | GraphqlSelectOptionPropertyValue | GraphqlEntityReferencePropertyValue | GraphqlLinkPropertyValue
+"""
+An agent session an account registered as its work.
+"""
+type GraphqlRegisteredWork {
+ """
+ The registration.
+ """
+ id: ID!
+ """
+ The account whose work this is.
+ """
+ accountId: ID!
+ """
+ When the account registered it, in RFC 3339.
+ """
+ registeredAt: String!
+ """
+ The session registered.
+ """
+ session: GraphqlSoupAgentSession!
+}
+
+"""
+Changes may have been missed or sharing changed: refetch the list.
+"""
+type GraphqlRegisteredWorkInvalidate {
+ """
+ Always true.
+ """
+ refresh: Boolean!
+}
+
+"""
+One change to the registered work of the subscribed accounts.
+"""
+union GraphqlRegisteredWorkPatch = GraphqlRegisteredWorkUpsert | GraphqlRegisteredWorkRemove | GraphqlRegisteredWorkInvalidate
+
+"""
+A registration that ended or whose session was archived.
+"""
+type GraphqlRegisteredWorkRemove {
+ """
+ The registration to stop showing.
+ """
+ id: ID!
+}
+
+"""
+A registration to show, new or with its session's list fields changed.
+"""
+type GraphqlRegisteredWorkUpsert {
+ """
+ The registration.
+ """
+ entry: GraphqlRegisteredWork!
+}
+
"""
The two operands of a recursive reminder filter expression. Ignored.
Remove after 2026-11-30.
@@ -10337,6 +10404,12 @@ type GraphqlUser {
"""
workFeed(input: WorkFeedInput): WorkFeedPage!
"""
+ The agent sessions `accountIds` registered as their work that the
+ authenticated user can view, newest first, at most 50 accounts.
+ Registrations of sessions the user cannot view are completely hidden.
+ """
+ registeredWork(accountIds: [ID!]!): [GraphqlRegisteredWork!]!
+ """
A page of the authenticated user's notifications inbox, newest group
first: their pending notifications grouped by the entity they are
filed under and cut into rows, one per conversation thread, channel