Hardening HarmonyOS Share Outbox Recovery Against Short Writes and Async Races
A post-tag review of Lynsi 3.2.4 (commit b019dbe) uncovered four concurrency and I/O bugs in Share.ets's .txt outbox recovery: unchecked short writes, missing pre-await locks, Mac target drift, and cleanup races on page dismissal.
The first rule of HarmonyOS system sharing is that ShareAbility (and OpenFileAbility) runs in an independent extension process, separate from the main app.
Temporary URI grants from the source app belong exclusively to the receiving extension component; you cannot hand them off to the main process to read. So Lynsi’s harmony/entry/src/main/ets/pages/Share.ets connects directly to the Mac to transfer files. When the Mac is unreachable, 3.2.4 added a recovery action (stageTextAsOutboxFile) so users can save unsent links or text as shared-<stamp>.txt into the Pro offline outbox (OutboxStore.stageOwned).
On November 15, 2026—the same day v3.2.4 was tagged—a follow-up review caught four I/O and concurrency bugs inside that recovery path, fixed in commit b019dbe for candidate reviewed-20261115/.
1. Single fileIo.write Calls Truncate Silently on Short Writes
The original code wrote the .txt file in a single call:
await fileIo.write(file.fd, buffer.slice(0, byteLength));
A short write does not throw in fileIo.write—it resolves with the number of bytes actually written. Without a write loop and count check, partial writes silently proceed through close and OutboxStore.stageOwned, enqueueing a truncated .txt file while telling the user their text was saved.
utils/FileBytes.ets already provided writeFullyAsync(fd, payload), which writes in FILE_IO_CHUNK_BYTES slices, shrinks chunkSize to wrote on a partial write, and returns early if wrote <= 0. Switching to writeFullyAsync and enforcing an exact length check closed the gap:
const written: number = await writeFullyAsync(file.fd, buffer.slice(0, byteLength));
if (written !== byteLength) { throw new Error(I18n.s($r('app.string.error_export_incomplete'))); }
Zero-progress (wrote === 0) or thrown errors abort before publication, report failure, and clean up the temp file.
2. Claiming the Lock After the First await Let Double-Taps Race
stageTextAsOutboxFile previously checked this.stagedTextAsFile and then immediately awaited OutboxSetting.load(context) and MacTierCache.isPro(context) without marking an in-flight state.
Tapping the button twice in quick succession let both calls pass the initial guard, compute identical ${context.cacheDir}/share-text-${stamp} paths within the same millisecond, and enqueue duplicate .txt items.
We added @State private stagingTextAsFile: boolean = false, set it before the first await, disabled the button with .enabled(!this.stagingTextAsFile), and appended -${Math.random().toString(16).slice(2)} to dirPath so concurrent invocations never share a directory.
3. Target Mac Drift Across Suspension Points
OutboxStore.stageOwned binds each queued file to the target Mac’s certificatePem and deviceName.
Reading this.client.certificatePem and this.deviceName after preferences loaded and the file finished writing meant switching Macs mid-flight staged the file under the wrong destination. Both values are now captured alongside this.generation before the first await.
4. Dismissing the Sheet During a Native Write
A user can swipe away the share sheet at any time, firing aboutToDisappear() and incrementing this.generation.
If writeFullyAsync is suspended inside native I/O when that happens, cleanup cannot unlink the open file prematurely, nor can the resumed continuation publish into OutboxStore after the page is gone:
- Every
awaitboundary is followed bythis.requireCurrent(generation)to abort further steps and skip touching stale UI state. finallywaits for the pending native write to finish, closesfile(fileIo.close), unlinksfilePath, removesdirPath, and resetsstagingTextAsFile = false.
Locking All Five Races Down in Node vm
Reproducing “native fileIo.write accepts 3 bytes per call” or “aboutToDisappear() fires mid-write” reliably on a phone is tedious.
scripts/test-share-lifetime.cjs slices the production methods straight out of Share.ets along with FileBytes.ets, transpiles them with typescript, and executes them in vm.runInNewContext against fake fileIo, OutboxSetting, and OutboxStore stubs with deferred() promises.
Commit b019dbe added five regression tests covering:
- Chunking across 3-byte short writes until every UTF-8 byte (including emojis and newlines) is flushed and closed before
stageOwned. - Zero-progress (2 bytes then
0) anddisk fullfailures never publishing, always closing and unlinking. - Rapid double-taps while
OutboxSetting.loadis suspended sharing one operation. aboutToDisappear()firing mid-writewaiting for native completion before closing/unlinking and blocking publication.- Switching
client.certificatePemanddeviceNamemid-awaitstill binding to the original Mac.
All 24/24 share-lifetime assertions (and all 43 cross-platform regression scripts) passed. Once an ArkTS handler crosses an await, every uncaptured field, missing re-entrancy lock, and unchecked byte count becomes a real production race.
Comments