# Agent App: Cross-device Sessions

## What it does

The server lists the same badge recordings for every phone signed in as the same
agent, and lets any of those phones assign an uploaded Unassigned recording to a
Lead. The Sales Agent App's Sessions tab is planned to read it on every phone.
Retry stays on the phone that holds the audio.

The wire contract is in the
[Agent API doc](/docs/agent-app/PROPERTYLAB-SALES-AGENT-API.md) (*Badge Sessions
across phones*). The upload lane that creates Unassigned captures is documented in
[Agent Upload](/docs/modules_handbook/manage/calls/agent-upload/readMe.md); the
per-recording report a Session opens is in
[Session reports](/docs/modules_handbook/agent-app/session-reports/readMe.md).

## How it works

**Listing.** `GET agent-badge-sessions` pages through two kinds of row, both
carrying the App's own interaction UUID:

- a Flutter call interaction (`agent_call_events`, `external_id = flutter:{uuid}`),
  listed as `kind: call`;
- a badge capture uploaded without a Lead
  (`call_recordings.metadata.unassigned_capture_uuid`), listed as
  `kind: unassigned`, with `status: unassigned`, or `matched` once the CRM or the
  App gave it a Lead.

Only a badge capture that carries `unassigned_capture_uuid` is a Session. Every
other recording is left out and stays on the web: WiFi badge, dowayai and manual
uploads, and legacy BLE uploads that came without an `interaction_uuid`, which
share `source = badge_ble` but have no such UUID. A start that expired or was
canceled before any audio is left out too. Every UUID is listed exactly once.

**Paging.** Keyset, 50 per page, newest first, ordered on `(sort_at, kind, id)`.
`meta.next_cursor` is an opaque base64url position and is `null` on the last
page; a malformed cursor is 422. A position rather than an offset, so a row that
leaves the list between two requests cannot shift the next page.

**Clocks.** `agent_call_events.started_at` is app-timezone wall time
(`config('app.timezone')`), `call_recordings.called_at` is UTC wall time. The
query shifts calls to UTC by the zone's offset and sorts both on that, and
`BadgeSessionTransformer` reads a capture's `called_at` as UTC. Every timestamp in
the response is ISO 8601 with the app offset.

**Ownership: one rule.** The phone that recorded a capture is the phone assigning
it when a non-deleted Flutter interaction with `external_id = flutter:{uuid}`
exists for the agent and is visible, meaning not `expired`/`canceled`, or already
linked to a recording (`AgentBadgeSessionQuery::listedCalls()`). While that holds,
the UUID is listed once, as the call, and assigning the capture is a 409.
Otherwise it is listed as the capture. A capture whose re-link interaction was
deleted, or expired or canceled without audio, is assignable from any phone again.

**Assigning.** `POST agent-badge-sessions/{uuid}/assign` takes `lead_uuid` and
`call_channel` (`pstn` or `whatsapp`, case-insensitive). The Lead is resolved with
the rule the App uses to open it (`AgentAppLeadSearchQuery::findOpenableByUuid`).
`CallRecordingRepository::assignUnassignedBadge` locks the Admin row and then the
capture row, so two phones at once get one winner and one 409; it writes the same
manual link `linkToLead()` writes, plus the channel.

- 200 returns the item, including a replay to the same Lead and channel.
- 404: not this agent's capture, or a Lead the agent cannot open in the App.
- 409 `badge_session_already_assigned`, with the message from
  `AgentBadgeSessionQuery::ALREADY_ASSIGNED_MESSAGE` (*This recording is already
  assigned, or the phone that recorded it is assigning it.*): the capture already
  has a Lead (another one, or the same Lead with another channel), or the
  ownership rule above holds.
- 422: validation failed.
- A capture whose Lead was hard-deleted counts as unassigned, in the list and in
  assign, so assigning it replaces the dangling `lead_id`.
- The action-plan draft sync runs after the commit. If it fails it is reported and
  the assign still succeeds; a replay does not run it again.

**Re-link from a stale phone.** `POST agent-call-interactions` answers 409
`badge_session_already_assigned` (same code and message) when the new interaction
UUID matches an unassigned capture that already carries another `lead_id`.
`AgentCallInteractionService::captureAssignedElsewhere()` compares the raw
`lead_id`, a deleted Lead's id included, because the upload linker compares it the
same way. It stops a phone that still shows the capture as unassigned from
re-linking it to a second Lead after another phone assigned it. The same Lead is
still accepted, and the check runs only for a UUID with no interaction yet. Released
App versions treat any 409 on create as permanent.

**App side.** The App is meant to merge this list with its local database: local
rows keep their upload progress and Retry, server rows fill in what other phones
recorded, and a local Unassigned row the server shows as assigned is adopted and
its retained audio released. The routes are new, so a backend that predates them
answers 404, and the App is meant to stay on its local list.

**Deploy.** No migration and no env change. The new routes need the standard
deploy's `route:cache` ([`scripts/deploy-update.sh`](../../production-setup/deploy.md)
runs `optimize:clear` then `route:cache`); on a box that caches routes they answer
404 until it runs. Deploy the backend before an App build that calls the new routes.

## Known limitations

- If the recording phone's own re-link interaction ends `failed_permanent` without
  linking, it keeps owning the capture. Other phones see a failed call, and the
  recording can then only be linked from the CRM web.
- **Same Lead, different channel.** A stale phone re-linking a capture that another
  phone already assigned to the same Lead, but with a different channel, is accepted
  (201). The linker then leaves `call_channel` alone because `lead_id` is already
  set, so the list shows the interaction's channel while the recording keeps the
  assigned one. Create deliberately compares the Lead only: refusing would
  permanently fail a released App's same-Lead re-link.
- **Abandoned preparing re-link.** A re-link abandoned in `preparing` keeps owning
  its capture until stale interactions are expired. That happens lazily, on the
  agent's next interaction create from any phone, so until then other phones get
  409 on assign.
- A CRM user who links the capture to a different Lead while a re-link is in flight
  makes the upload fail with `recording_lead_conflict`. The Sessions list then shows
  the phone's call rather than the capture; the CRM shows the truth.
- The list's `throttle:60,1` is keyed on the user, so it is shared by every phone of
  the account and by every other `/agent-api` request that account makes, including
  heartbeats and uploads (the `api` middleware group adds it to every route). The App
  should page on demand ("Load older sessions"), not sync all history at once. Assign
  also uses the per-user `agent-recordings` limiter on top of that shared limit.

## Related files

Backend

- [AgentBadgeSessionsController](/app/Http/Controllers/AgentApi/AgentBadgeSessionsController.php)
- [AssignBadgeSessionRequest](/app/Http/Requests/AgentApi/AssignBadgeSessionRequest.php)
- [BadgeSessionTransformer](/app/Http/Transformers/AgentApi/BadgeSessionTransformer.php)
- [AgentBadgeSessionQuery](/src/Call/Queries/AgentBadgeSessionQuery.php) (listing, the ownership rule, cursor, 409 constants)
- [CallRecordingRepository](/src/Call/Repositories/CallRecordingRepository.php) (`assignUnassignedBadge`, `linkToLead`)
- [AgentCallInteractionService](/src/Call/Services/AgentCallInteractionService.php) (`captureAssignedElsewhere`)
- [AgentCallInteractionsController](/app/Http/Controllers/AgentApi/AgentCallInteractionsController.php) (the create 409)
- [AgentAppLeadSearchQuery](/src/Lead/Queries/AgentAppLeadSearchQuery.php) (`findOpenableByUuid`, the Lead rule for assign)
- [AgentCallEvent](/src/Call/AgentCallEvent.php) (interaction statuses, `SOURCE_FLUTTER_APP`)
- [CallRecording](/src/Call/CallRecording.php) (`SOURCE_BADGE_BLE`, the not-ignored scope)

Routes

- [routes/agent-api.php](/routes/agent-api.php): `badge-sessions.index` and `badge-sessions.assign`, registered under `/agent-api` (`agent-api-direct.`) and `/api` (`agent-api.`)

Migrations / seeders: none.

Tests

- [AgentBadgeSessionsTest](/tests/Feature/AgentApi/AgentBadgeSessionsTest.php)

App (separate repository, planned, not part of this backend change)

- `lib/features/sessions/data/badge_session_api.dart`, `merged_session_store.dart`
