Files
hapi/web/src/lib/sharePendingState.test.ts
T
2643f17840 feat(web): Web Share Target -> Android system share sheet integration (#933)
* feat(web): Web Share Target -> composer attachment preload

PWA manifest now declares a `share_target` so Android Chrome surfaces
HAPI in the system share sheet for any app (Photos, Files, browser).

Pipeline on share:
  1. Service worker intercepts POST /share, parses the multipart payload
     (title/text/url + N files), persists it in IndexedDB under a
     transfer id, and 303-redirects to /share?id=<id>. The 303 forces
     Chrome to convert the POST into a GET so the SPA route mounts.
  2. New /share route loads the transfer, previews the content, and
     lets the user pick a recent active session (top 5 by activeAt) or
     a "+ New session". Tapping a session stashes the transfer id in
     sessionStorage and navigates to /sessions/:id.
  3. SessionChat mounts a ShareSeedConsumer once the AssistantRuntime
     is up; it consumes the pending transfer once per mount, seeds
     composer text + per-file attachments via the existing
     attachmentAdapter, then deletes the IDB row so a refresh of the
     session page does not replay the upload.

The whole feature reuses the existing /sessions/:id/upload endpoint;
no hub or shared changes.

Limitations (also disclosed in the PR body):
  - PWA must be installed; Android Chrome only registers share_target
    on install. iOS Safari ignores the manifest field entirely.
  - File MIME accept list is broad (`*/*` fallback); some Chrome
    versions still filter despite this.

Tests:
  - shareTransfer.test.ts (8) covers payload parse, multi-file order,
    type fallback, ingest redirect shape and error propagation.
  - sharePendingState.test.ts (3) covers atomic consume + overwrite.

Closes: pending upstream issue (filed before PR per intake doc).
Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web/share): freeze picker session list at mount, sort by updatedAt, drop top-5 cap

The /share picker was visually re-shuffling under the operator's finger
as SSE events rolled in: every session metadata patch refreshed the
React Query cache, the useMemo recomputed, and items reordered (often
within a second of opening the share sheet). Sort key was activeAt,
which heartbeats every few seconds while a session is connected,
making the noise floor even higher.

Three changes:
  - Snapshot the active-session list once when sessions finish loading
    via useState + a deferred useEffect. The picker is a one-shot
    interaction; closing the share sheet and re-sharing produces a
    fresh snapshot, so freezing for the duration of the picker view is
    the right trade.
  - Sort by updatedAt desc to match SessionList's canonical "most
    recent interaction first" order. updatedAt only moves on
    user-meaningful events, not heartbeats.
  - Drop the TOP_SESSIONS=5 cap. The picker is already inside an
    app-scroll-y container, so showing all active sessions and letting
    the operator scroll matches the operator's mental model better
    than an arbitrary truncation.

Per operator dogfood report: "list of recent sessions is constantly
updating; should be just a scrollable list, from most recent
interaction to not."

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web/share): base-aware share_target paths for subpath PWA deploys

Manifest share_target.action, SW POST matching, and ingest 303 redirects
were hard-coded to /share. Standalone builds with --base /<repo>/ put
scope/start_url under the subpath but left the share action at origin
root, so Chrome posted outside the SW scope and the handler never ran.

Extract shareTargetPathnameFromBase() (used at build time in
vite.config.ts and at runtime via import.meta.env.BASE_URL in sw.ts and
shareTransfer.ts). Normalizes base to a trailing slash before URL
resolution so /repo and /repo/ both resolve to /repo/share.

Addresses upstream PR #933 review (Major).

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web/share): defer sessionStorage arm until new session spawn succeeds

The "+ New session" picker path called setSharePendingTransfer before a
session existed. Cancel, spawn failure, or backing out left a stale id in
sessionStorage that the next unrelated SessionChat mount would consume.

Pass shareTransferId via /sessions/new search params instead; arm the
consumer only in handleSuccess after spawn, and delete the IDB row on
cancel.

Addresses upstream PR #933 review (Major).

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web/share): append share text to existing composer draft

ShareSeedConsumer called setText(seedText) unconditionally, clobbering
per-session drafts restored by useComposerDraft from sessionStorage.

Merge share title/text/url after any in-composer text or saved draft,
joined with a blank line. Pass sessionId into ShareSeedConsumer so
getDraft() can be consulted when the composer is still empty.

Addresses upstream PR #933 review (Major).

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web/share): preserve shareTransferId through /browse detour

New-session spawn from the share picker could lose shareTransferId when
the operator opened /browse to pick a folder: handleChooseFolder and
BrowsePage handleStartSession dropped the search param, so handleSuccess
never armed the composer consumer.

Thread shareTransferId through browseRoute search validation and both
navigation hops.

Addresses upstream PR #933 review (Major).

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web/share): consume pending transfer in effect for StrictMode

ShareSeedConsumer called consumeSharePendingTransfer during render.
React.StrictMode double-invokes render in dev; the discarded pass
deleted the sessionStorage key before the committed render seeded.

Move consume into a mount-only useEffect and gate the seed effect on
transferReady.

Addresses upstream PR #933 review (Minor).

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-18 10:16:03 +08:00

35 lines
1.1 KiB
TypeScript

import { afterEach, describe, expect, it } from 'vitest'
import {
SHARE_PENDING_TRANSFER_KEY,
consumeSharePendingTransfer,
setSharePendingTransfer,
} from './sharePendingState'
afterEach(() => {
try { window.sessionStorage.clear() } catch { /* noop */ }
})
describe('sharePendingState', () => {
it('round-trips a transfer id and clears the slot on consume', () => {
setSharePendingTransfer('xfer-1')
expect(window.sessionStorage.getItem(SHARE_PENDING_TRANSFER_KEY)).toBe('xfer-1')
const first = consumeSharePendingTransfer()
expect(first).toBe('xfer-1')
const second = consumeSharePendingTransfer()
expect(second).toBeNull()
})
it('returns null when no transfer is pending', () => {
expect(consumeSharePendingTransfer()).toBeNull()
})
it('overwrites a stale id rather than appending', () => {
setSharePendingTransfer('a')
setSharePendingTransfer('b')
expect(consumeSharePendingTransfer()).toBe('b')
expect(consumeSharePendingTransfer()).toBeNull()
})
})