Skip to content

Commit 6da7435

Browse files
fix(mobile): give incoming shares durable entry identities
1 parent e7c5515 commit 6da7435

6 files changed

Lines changed: 40 additions & 60 deletions

File tree

‎apps/mobile/src/Stack.tsx‎

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -588,10 +588,8 @@ function ThreadOutboxDrainWorker() {
588588
function RootStackLayout(props: {
589589
readonly children: React.ReactNode;
590590
readonly state: NavigationState;
591-
// The navigator's own helpers, not useNavigation(): the layout renders
592-
// outside the helpers context, so useNavigation() falls back to the container
593-
// ref, whose actions are dropped until the navigator's focus listener
594-
// registers. Its effect runs after this one on the first commit.
591+
// Layout effects run before the container's focus listener is registered;
592+
// navigator-owned helpers can dispatch on that first commit.
595593
readonly navigation: {
596594
readonly navigate: (name: "NewTaskSheet", params: object) => void;
597595
};
@@ -618,10 +616,8 @@ function RootStackLayout(props: {
618616
const shareId = transition.shareIdToDiscard;
619617
discardShare(shareId).catch((error: unknown) => {
620618
console.warn("[incoming-share] could not discard dismissed share", error);
621-
// Drop the latch so the share is presented again instead of sitting
622-
// in the inbox unreachable until the next foreground refresh.
623619
if (sharePresentationRef.current.discardedShareId === shareId) {
624-
// Only the latch: a newer share may already be presented.
620+
// A newer sheet may already be open when this discard rejects.
625621
sharePresentationRef.current = {
626622
...sharePresentationRef.current,
627623
discardedShareId: null,

‎apps/mobile/src/features/sharing/IncomingShareProvider.tsx‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,6 @@ type IncomingShareContextValue = {
3939
expectedDestination: IncomingShareDestination,
4040
) => Promise<void>;
4141
readonly consumeShare: (shareId: string) => Promise<void>;
42-
/** Drops a share the user walked away from, along with the files it owned. */
4342
readonly discardShare: (shareId: string) => Promise<void>;
4443
readonly refresh: () => Promise<void>;
4544
};
@@ -74,7 +73,9 @@ async function resolvedPayloadsForFiles(): Promise<ReadonlyArray<ResolvedSharePa
7473
}
7574
}
7675

77-
async function incomingShareIdForPayloads(payloads: ReadonlyArray<SharePayload>): Promise<string> {
76+
async function incomingShareFingerprintForPayloads(
77+
payloads: ReadonlyArray<SharePayload>,
78+
): Promise<string> {
7879
const fingerprint = JSON.stringify(
7980
payloads.map((payload) => ({
8081
shareType: payload.shareType,
@@ -198,7 +199,8 @@ const incomingShareInbox = new IncomingShareInbox({
198199
};
199200
},
200201
cleanupReplayedPayloads: removeReplayedPayloadFiles,
201-
idForPayloads: incomingShareIdForPayloads,
202+
fingerprintForPayloads: incomingShareFingerprintForPayloads,
203+
createId: () => `share-${Crypto.randomUUID()}`,
202204
now: () => new Date().toISOString(),
203205
onClearError: (error) => {
204206
console.warn("[incoming-share] could not acknowledge native payload", error);
@@ -305,7 +307,6 @@ export function IncomingShareProvider(props: React.PropsWithChildren) {
305307
const discarded = drafts.find((draft) => draft.id === shareId);
306308
const snapshot = await incomingShareInbox.consume(shareId);
307309
if (discarded) {
308-
// The inbox entry was the only owner of these files.
309310
scheduleUnusedComposerAttachmentCleanup(discarded.attachments);
310311
}
311312
if (mountedRef.current) {

‎apps/mobile/src/features/sharing/incoming-share-inbox.test.ts‎

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import {
55
EMPTY_INCOMING_SHARE_PRESENTATION_STATE,
66
transitionIncomingSharePresentation,
77
} from "./incoming-share-presentation";
8-
import type { IncomingShareDraft } from "./incoming-share-model";
8+
import { decodeIncomingShareDraft, type IncomingShareDraft } from "./incoming-share-model";
99
import { IncomingShareInbox, type IncomingShareInboxDependencies } from "./incoming-share-inbox";
1010

1111
const PAYLOAD: SharePayload = {
@@ -36,8 +36,9 @@ function deferred() {
3636
function createHarness(overrides: Partial<IncomingShareInboxDependencies> = {}) {
3737
const persisted = new Map<string, IncomingShareDraft>();
3838
let payloads: ReadonlyArray<SharePayload> = [PAYLOAD];
39+
let nextId = 0;
3940
const dependencies: IncomingShareInboxDependencies = {
40-
loadDrafts: async () => [...persisted.values()],
41+
loadDrafts: async () => [...persisted.values()].map(decodeIncomingShareDraft),
4142
writeDraft: async (value) => {
4243
persisted.set(value.id, value);
4344
},
@@ -52,7 +53,8 @@ function createHarness(overrides: Partial<IncomingShareInboxDependencies> = {})
5253
draft: draft(id, createdAt),
5354
cleanup: async () => undefined,
5455
}),
55-
idForPayloads: async () => "share-stable",
56+
fingerprintForPayloads: async () => "share-stable",
57+
createId: () => `share-entry-${++nextId}`,
5658
now: () => "2026-07-16T08:00:00.000Z",
5759
...overrides,
5860
};
@@ -80,15 +82,20 @@ describe("IncomingShareInbox", () => {
8082
await building.promise;
8183
return { draft: draft(id, createdAt), cleanup: async () => undefined };
8284
});
83-
const { inbox } = createHarness({ buildDraft });
85+
const { inbox } = createHarness({
86+
buildDraft,
87+
clearPayloads: () => {
88+
throw new Error("native acknowledgement failed");
89+
},
90+
});
8491

8592
const first = inbox.refresh({ ingestNative: true });
8693
const second = inbox.refresh({ ingestNative: true });
8794
building.resolve();
8895

8996
await expect(Promise.all([first, second])).resolves.toEqual([
90-
[draft("share-stable")],
91-
[draft("share-stable")],
97+
[{ ...draft("share-entry-1"), payloadFingerprint: "share-stable" }],
98+
[{ ...draft("share-entry-1"), payloadFingerprint: "share-stable" }],
9299
]);
93100
expect(buildDraft).toHaveBeenCalledTimes(1);
94101
});
@@ -103,10 +110,12 @@ describe("IncomingShareInbox", () => {
103110
});
104111

105112
const refresh = inbox.refresh({ ingestNative: true });
106-
const consume = inbox.consume("share-stable");
113+
const consume = inbox.consume("share-entry-1");
107114
building.resolve();
108115

109-
await expect(refresh).resolves.toEqual([draft("share-stable")]);
116+
await expect(refresh).resolves.toEqual([
117+
{ ...draft("share-entry-1"), payloadFingerprint: "share-stable" },
118+
]);
110119
await expect(consume).resolves.toEqual([]);
111120
expect([...persisted.values()]).toEqual([]);
112121
});

‎apps/mobile/src/features/sharing/incoming-share-inbox.ts‎

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,8 @@ export interface IncomingShareInboxDependencies {
2323
readonly rollback?: () => Promise<void>;
2424
}>;
2525
readonly cleanupReplayedPayloads?: (payloads: ReadonlyArray<SharePayload>) => Promise<void>;
26-
readonly idForPayloads: (payloads: ReadonlyArray<SharePayload>) => Promise<string>;
26+
readonly fingerprintForPayloads: (payloads: ReadonlyArray<SharePayload>) => Promise<string>;
27+
readonly createId: () => string;
2728
readonly now: () => string;
2829
readonly onClearError?: (error: unknown) => void;
2930
readonly onCleanupError?: (error: unknown) => void;
@@ -86,11 +87,10 @@ export class IncomingShareInbox {
8687
return persisted;
8788
}
8889

89-
// A share extension payload remains available until the containing app
90-
// acknowledges it. Use a content-derived id so a crash after the durable
91-
// write but before acknowledgement reuses the same inbox item.
92-
const shareId = await this.dependencies.idForPayloads(payloads);
93-
if (loaded.some((draft) => draft.id === shareId)) {
90+
// Persist replay detection separately from entry identity: a later identical
91+
// handoff must not be addressed by an earlier sheet's dismissal or import.
92+
const payloadFingerprint = await this.dependencies.fingerprintForPayloads(payloads);
93+
if (loaded.some((draft) => (draft.payloadFingerprint ?? draft.id) === payloadFingerprint)) {
9494
if (this.dependencies.cleanupReplayedPayloads) {
9595
await this.cleanup(() => this.dependencies.cleanupReplayedPayloads!(payloads));
9696
}
@@ -100,10 +100,10 @@ export class IncomingShareInbox {
100100

101101
const built = await this.dependencies.buildDraft({
102102
payloads,
103-
id: shareId,
103+
id: this.dependencies.createId(),
104104
createdAt: this.dependencies.now(),
105105
});
106-
const { draft } = built;
106+
const draft = { ...built.draft, payloadFingerprint };
107107
if (!hasIncomingShareContent(draft)) {
108108
await this.cleanup(built.cleanup);
109109
this.clearNativePayloads();
@@ -131,9 +131,6 @@ export class IncomingShareInbox {
131131

132132
consume(shareId: string): Promise<ReadonlyArray<IncomingShareDraft>> {
133133
return this.runExclusive(async () => {
134-
// The stable payload-derived id already coalesces retries of the same
135-
// native handoff. Payload equality cannot identify duplicate handoffs:
136-
// users may intentionally share identical content more than once.
137134
await this.dependencies.removeDraft(shareId);
138135
return sortAndDedupeIncomingShares(await this.dependencies.loadDrafts());
139136
});

‎apps/mobile/src/features/sharing/incoming-share-model.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import { estimateBase64ByteSize } from "../../lib/base64";
1919
export interface IncomingShareDraft {
2020
readonly schemaVersion: 1;
2121
readonly id: string;
22+
readonly payloadFingerprint?: string;
2223
readonly createdAt: string;
2324
readonly destination?: IncomingShareDestination;
2425
readonly text: string;
@@ -39,6 +40,7 @@ const IncomingShareDestinationSchema = Schema.Struct({
3940
export const IncomingShareDraftSchema = Schema.Struct({
4041
schemaVersion: Schema.Literal(1),
4142
id: Schema.String,
43+
payloadFingerprint: Schema.optional(Schema.String),
4244
createdAt: Schema.String,
4345
destination: Schema.optional(IncomingShareDestinationSchema),
4446
text: Schema.String,

‎apps/mobile/src/features/sharing/incoming-share-presentation.ts‎

Lines changed: 5 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,6 @@
11
export interface IncomingSharePresentationState {
2-
/** Share the layout last asked the new-task sheet to open. */
32
readonly presentedShareId: string | null;
4-
/** Whether the sheet was actually observed carrying `presentedShareId`. */
53
readonly sheetSeen: boolean;
6-
/** Share the user closed the sheet on; ignored until the inbox drops it. */
74
readonly discardedShareId: string | null;
85
}
96

@@ -32,13 +29,8 @@ function incomingShareIdOfParams(params: object | undefined): string | null {
3229
return typeof id === "string" ? id : null;
3330
}
3431

35-
/**
36-
* The share id the new-task sheet is carrying, if the sheet is anywhere in the
37-
* root stack. Routes pushed above it (Add environment, a notification tap) do
38-
* not close it, so they must not read as a dismissal. Before the nested
39-
* navigator mounts, the id still sits in the `navigate` payload
40-
* (`params.params`); afterwards it lives on the nested route that owns it.
41-
*/
32+
// A root route above the sheet leaves it open. Before the nested navigator
33+
// mounts, the share ID lives in the navigate payload instead of its routes.
4234
export function incomingShareIdOfSheetRoute(
4335
state: { readonly routes: ReadonlyArray<RouteLike> },
4436
sheetRouteName: string,
@@ -58,17 +50,6 @@ export function incomingShareIdOfSheetRoute(
5850
return { isSheetPresented: true, shareId: incomingShareIdOfParams(payload ?? undefined) };
5951
}
6052

61-
/**
62-
* Decides when the pending inbox share opens the new-task sheet and when the
63-
* user has walked away from it. A share counts as dismissed only after the
64-
* sheet was seen carrying it and then left the stack; until then a missing
65-
* sheet means the navigation never landed (container not ready, another route
66-
* won the race) and the request is simply repeated. Dismissal discards the
67-
* share so that sharing the same content again yields a fresh handoff instead
68-
* of a silent no-op. The tracked share survives a newer pending one arriving
69-
* while its sheet is still up, so closing that sheet discards it rather than
70-
* letting it resurface after the newer share is handled.
71-
*/
7253
export function transitionIncomingSharePresentation(
7354
state: IncomingSharePresentationState,
7455
input: {
@@ -95,20 +76,14 @@ export function transitionIncomingSharePresentation(
9576

9677
const tracked = state.presentedShareId;
9778
if (input.isSheetPresented) {
98-
if (tracked === null) {
99-
// A sheet nobody here asked for (a manual new task). Wait for it to close.
100-
return { ...hold, state: EMPTY_INCOMING_SHARE_PRESENTATION_STATE };
101-
}
102-
if (input.sheetShareId === tracked && !state.sheetSeen) {
79+
if (tracked !== null && input.sheetShareId === tracked && !state.sheetSeen) {
10380
return { ...hold, state: { ...state, sheetSeen: true } };
10481
}
10582
return hold;
10683
}
10784

108-
// The sheet is gone. A tracked share that was seen is dismissed; anything
109-
// else is a request that never landed and is repeated. A consumed share can
110-
// also land here (its sheet closed onto the thread); discarding it again is
111-
// a no-op since the inbox no longer has it.
85+
// A missing sheet is a dismissal only after it carried this entry's ID.
86+
// Otherwise the navigation may never have landed and remains eligible.
11287
const shareIdToDiscard = tracked !== null && state.sheetSeen ? tracked : null;
11388
const shareIdToPresent = shareIdToDiscard === pendingShareId ? null : pendingShareId;
11489
return {

0 commit comments

Comments
 (0)