Skip to content

Mobile gamification (toasts + confetti) & note-link data-loss fix - #99

Merged
ddutchie merged 6 commits into
mainfrom
ddutchie/mobileconfetti
Jul 26, 2026
Merged

ddutchie merged 6 commits into
mainfrom
ddutchie/mobileconfetti

Conversation

@ddutchie

@ddutchie ddutchie commented Jul 26, 2026 •

Copy link
Copy Markdown
Owner

What does this PR do?

Adds a mobile gamification layer (toasts, task-complete celebrations, confetti in the hidden mini-games) and fixes several bugs found while building it — including a note data-loss bug in link_note_to_task.

Features (mobile)

  • Toast/snackbar system (Toast.tsx) — root-mounted, reanimated, with a module-level singleton fireable from non-component code.
  • Task-complete celebration — dragging a card into a Done column (or moving it there from the task screen) fires a success haptic + toast (counting remaining tasks) + confetti.
  • Confetti via react-native-confetti-cannon (pure-JS, Expo-Go safe); ConfettiHost + InlineConfetti (for use inside fullscreen game modals).
  • Mini-game celebrations — Cairn Stacker persists its best score and celebrates a new high score; Breakout erupts in confetti on clearing the board.

Fixes

  • link_note_to_task no longer deletes the note. writeNoteFile rewrote the .md via tmp-file + rename even on an unchanged path; the inode swap looked like an unlink to the separate-process file-watcher, which — after the mcp_active_writes lock had been released — tombstoned the note row. Now writes in place when the path is unchanged; tmp+rename is kept only for real relocations. Regression tests added.
  • Mobile: new-task back label showed (tabs) instead of the project name until the card was reopened from the board. The project name is now carried through to the freshly-created card.
  • Mobile: Breakout declared "Cleared!" with bricks still on screen (win count only tallied bricks scanned before the collision break) — now counts all remaining bricks. The game-over/cleared "Close" button was also unreadable over the scrim — now legible.

Type of change

  • Bug fix
  • New feature
  • Refactor / code quality
  • Docs / changelog
  • Tests

Screenshots / recording

Checklist

  • npm run type-check:all passes
  • npm run lint passes (lint-clean on all touched files)
  • npm test passes (runs npm run compile first so electron/bundle-guard.test.ts actually executes — npm run test:bundle to run just that)
  • npm run test:e2e passes (run before merging UI changes or cutting a release)
  • If this ships a major, user-facing feature: added an entry to scripts/features.config.js (not treated as headline-worthy yet — mobile-only)
  • No hardcoded colours — CSS variables / theme tokens only
  • No text-[Npx] pixel font classes — rem/type-scale tokens only
  • New IPC handlers wrapped in handle() and return IpcResult<T> — N/A (no new IPC)
  • New DB migrations appended (not edited) in schema.ts — N/A (no schema changes)
  • New SQL goes in electron/db/queries.ts — N/A (no new desktop SQL; mobile listColumns type column already existed)
  • New dependencies added to ROLE_MAP / licenses.json — N/A (new dep react-native-confetti-cannon is mobile-only; desktop licenses.json unaffected)
  • New MCP tools registered — N/A (no new tools)
  • No --external:<pkg> flag changes

Notes for reviewer

  • The link_note_to_task fix only takes effect once the app's bundled cairn-mcp binary is rebuilt (npm run compile) and the app repackaged. Until then, linking notes to tasks via MCP still risks the tombstone. I did not run compile in this PR — flagging so it happens before release.
  • The data-loss root cause is a cross-process (watcher ↔ MCP binary) timing race; the in-place-write fix removes the unlink event entirely for metadata-only writes, which is the robust fix rather than widening the lock window. See electron/shared/notes-io.test.ts (inode-stability assertion).
  • New mobile dependency: react-native-confetti-cannon@1.5.2 (pure JS, no native module → safe for Expo Go and prebuilds).

Summary by CodeRabbit

  • New Features

    • Added success celebrations, haptic feedback, and toasts when completing tasks, including an “All tasks done!” message.
    • New personal-best tracking and confetti celebrations in Stacker.
    • Improved task navigation with clearer back-button context.
  • Bug Fixes

    • Fixed Breakout win detection and improved overlay button readability.
    • Prevented note updates from accidentally deleting notes.
  • Tests

    • Added coverage for note creation, updates, and relocations.

ddutchie added 4 commits July 26, 2026 16:29
Add a lightweight toast/snackbar system (Toast.tsx) with a module-level
singleton fireable from non-component code, and a confetti burst overlay
(Confetti.tsx, react-native-confetti-cannon). Celebrate completing a
task — dragging a card into a done column or moving it there from the
task screen — with confetti + haptic + a toast that counts remaining
tasks. Reward logic centralised in gamification/rewards.ts.

Adds ColumnRow.type to listColumns so done columns are detectable on the
board. Changelog appended to v0.1.3.md.
Extract InlineConfetti from Confetti.tsx so bursts can render inside a
fullscreen Modal (the app-root ConfettiHost sits behind it). Stacker now
persists its best score in the meta store and fires confetti + a "New
high score!" overlay when beaten; Breakout erupts in confetti when the
board is cleared.
writeNoteFile rewrote the note's .md via tmp-file + rename even when the
path was unchanged. Rename-over-existing swaps the inode, which the
separate-process file-watcher sees as an unlink of the note's own path;
delivered asynchronously, it could land after the mcp_active_writes lock
was released, so the watcher tombstoned the note row.

Write in place when the resolved path is unchanged (change event only,
no unlink); keep tmp+rename solely for genuine relocations. Adds
regression tests (inode stable on rewrite; title change relocates).
- New task screen now carries the project name through, so the freshly
  created card shows '< {Project}' instead of '(tabs)'.
- Breakout win check counts every remaining brick (not just those
  scanned before the collision break), so it no longer declares
  'Cleared!' with bricks still on screen.
- Breakout game-over/cleared 'Close' button is legible over the scrim
  (textSecondary, matching Stacker).
@coderabbitai

coderabbitai Bot commented Jul 26, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The PR changes note writes to preserve unchanged file paths, adds regression coverage, and introduces mobile toast/confetti feedback. Task completion rewards, project-aware back navigation, persisted Stacker scores, and corrected Breakout win detection are also added.

Changes

Note write safety

Layer / File(s) Summary
Conditional note-file writes
electron/shared/notes-io.ts, electron/shared/notes-io.test.ts, changelogs/v2.5.12.md
Unchanged note paths are rewritten in place, while title or folder changes use temporary-file replacement and remove the old path. Tests cover creation, inode preservation, and relocation cleanup.

Mobile feedback and task flow

Layer / File(s) Summary
Toast and confetti infrastructure
mobile/src/components/Toast.tsx, mobile/src/components/Confetti.tsx, mobile/app/_layout.tsx, mobile/package.json
Adds themed toast and confetti APIs, provider integration, modal-compatible rendering, and the confetti dependency.
Done-column reward contract
mobile/src/db/types.ts, mobile/src/db/queries.ts, mobile/src/gamification/rewards.ts
Adds column-type data and reward helpers for done-column completion messages, confetti, and haptics.
Task completion and navigation flow
mobile/src/screens/CardDetailScreen.tsx, mobile/src/screens/ProjectScreen.tsx, mobile/app/card/new.tsx, mobile/changelogs/v0.1.3.md
Task saves and board moves trigger rewards when entering done columns, while new-card routes preserve project back-button context.
Game completion feedback and persistence
mobile/src/components/BreakoutGame.tsx, mobile/src/components/StackerGame.tsx, mobile/changelogs/v0.1.3.md
Breakout recalculates remaining bricks and displays modal confetti; Stacker persists best scores and displays new-record feedback.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant ProjectScreen
  participant CardDetailScreen
  participant Database
  participant Rewards
  participant ToastProvider
  participant Confetti
  ProjectScreen->>Database: move card into done column
  Database-->>ProjectScreen: refreshed board
  ProjectScreen->>Rewards: calculate remaining open cards
  CardDetailScreen->>Database: save column change
  Database-->>CardDetailScreen: list remaining cards
  CardDetailScreen->>Rewards: pass remaining open count
  Rewards->>Confetti: trigger celebration burst
  Rewards->>ToastProvider: show completion toast
Loading

Possibly related PRs

  • ddutchie/cairn#88: Related note-write and move/delete regression work in the same writeNoteFile area.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 64.71% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly captures the two main themes: mobile gamification and the note-link data-loss fix.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch ddutchie/mobileconfetti

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

reset() didn't clear the celebrate trigger, so reopening after a
high-score run fired confetti immediately. The finished ConfettiCannon
also stayed mounted, re-rendering every rAF frame (the game re-renders
~60fps) and dragging the game to a crawl.

- Stacker reset() now clears celebrate.
- InlineConfetti unmounts the cannon once its burst finishes
  (onAnimationEnd), so it never lingers as a per-frame render cost.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (2)
mobile/src/components/Toast.tsx (1)

165-226: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Toasts aren't announced to screen readers.

The toast card has no accessibilityLiveRegion and doesn't call AccessibilityInfo.announceForAccessibility, so VoiceOver/TalkBack users get no signal when a reward toast (or any toast) appears — since it's pointerEvents="none", they also can't discover it by touch exploration.

Consider announcing the message on mount:

♿ Proposed fix
+import { AccessibilityInfo, ... } from "react-native";
...
   useEffect(() => {
+    AccessibilityInfo.announceForAccessibility(
+      state.detail ? `${state.message}. ${state.detail}` : state.message,
+    );
     opacity.value = withTiming(1, { duration: 180 });
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@mobile/src/components/Toast.tsx` around lines 165 - 226, Update ToastCard’s
mount effect to announce each toast message through
AccessibilityInfo.announceForAccessibility, and import the required
accessibility API. Trigger the announcement when the toast appears while
preserving the existing animation and timeout cleanup behavior.
mobile/src/components/Confetti.tsx (1)

52-71: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Cleanup doesn't check identity, unlike the sibling externalShow bridge.

Toast.tsx's equivalent cleanup checks externalShow === show before nulling; here it's just a truthiness check. Low risk today (single host), but worth matching the safer pattern for consistency.

♻️ Proposed fix
   useEffect(() => {
-    externalFire = () => setBurst((n) => n + 1);
+    const fire = () => setBurst((n) => n + 1);
+    externalFire = fire;
     return () => {
-      if (externalFire) externalFire = null;
+      if (externalFire === fire) externalFire = null;
     };
   }, []);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@mobile/src/components/Confetti.tsx` around lines 52 - 71, Update
ConfettiHost’s useEffect cleanup to clear externalFire only when it still
references the callback registered by that effect, matching the identity-check
pattern used by the externalShow bridge; leave the confetti firing behavior
unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@electron/shared/notes-io.ts`:
- Around line 192-194: Update the same-path branch in the note write flow to
avoid calling fs.writeFileSync directly on the existing target, preserving the
original file if writing fails or the process terminates. Use the existing
recovery-safe backup/temp-file strategy, including durable writes and
restoration/sync of the target as needed, while keeping the early return
behavior after a successful rewrite.
- Around line 192-194: Update the in-place write branch guarded by existingPath
=== newPath to prevent symlink traversal: reject symlinked note paths and write
through a no-follow file-descriptor-based path where supported, rather than
calling fs.writeFileSync(newPath, ...). Do not rely on a standalone lstat check;
ensure the protected open/write operation itself cannot follow a replaced
symlink.

---

Nitpick comments:
In `@mobile/src/components/Confetti.tsx`:
- Around line 52-71: Update ConfettiHost’s useEffect cleanup to clear
externalFire only when it still references the callback registered by that
effect, matching the identity-check pattern used by the externalShow bridge;
leave the confetti firing behavior unchanged.

In `@mobile/src/components/Toast.tsx`:
- Around line 165-226: Update ToastCard’s mount effect to announce each toast
message through AccessibilityInfo.announceForAccessibility, and import the
required accessibility API. Trigger the announcement when the toast appears
while preserving the existing animation and timeout cleanup behavior.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: baf657d2-1b65-4b9c-89f1-cf27a9957c38

📥 Commits

Reviewing files that changed from the base of the PR and between 2f51fdb and e40d340.

⛔ Files ignored due to path filters (1)
  • mobile/package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (16)
  • changelogs/v2.5.12.md
  • electron/shared/notes-io.test.ts
  • electron/shared/notes-io.ts
  • mobile/app/_layout.tsx
  • mobile/app/card/new.tsx
  • mobile/changelogs/v0.1.3.md
  • mobile/package.json
  • mobile/src/components/BreakoutGame.tsx
  • mobile/src/components/Confetti.tsx
  • mobile/src/components/StackerGame.tsx
  • mobile/src/components/Toast.tsx
  • mobile/src/db/queries.ts
  • mobile/src/db/types.ts
  • mobile/src/gamification/rewards.ts
  • mobile/src/screens/CardDetailScreen.tsx
  • mobile/src/screens/ProjectScreen.tsx

Comment on lines +192 to +194
if (existingPath && existingPath === newPath) {
fs.writeFileSync(newPath, serialized, "utf-8");
return;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "## files"
git ls-files | rg '(^|/)notes-io\.ts$|node_modules/next/dist/docs/'

echo "## electron/shared/notes-io.ts outline"
ast-grep outline electron/shared/notes-io.ts --view compact || true

echo "## relevant writeNoteFile section"
wc -l electron/shared/notes-io.ts
sed -n '1,260p' electron/shared/notes-io.ts | cat -n

echo "## same/write note usages/tests"
rg -n "writeNoteFile|renameNote|rename.*note|notes-io" . --glob '!node_modules/**' | head -200

echo "## next docs snippets about fs write (if present)"
fd -a . node_modules/next/dist/docs | head -50 || true
rg -n "rename|writeFileSync|atomic|writefile" node_modules/next/dist/docs 2>/dev/null | head -100 || true

Repository: ddutchie/cairn

Length of output: 47826


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "## electron/shared/notes-io.test.ts"
sed -n '1,140p' electron/shared/notes-io.test.ts | cat -n

echo "## fs.writeFileSync truncation behavior probe"
node - <<'JS'
const fs = require('fs');
const path = require('path');

const tmp = path.join(process.env.TMPDIR || '/tmp', 'node-writesync-probe');
fs.rmSync(tmp, { recursive: true, force: true });
fs.mkdirSync(tmp);

const p = path.join(tmp, 'note.md');
fs.writeFileSync(p, 'a'.repeat(12), 'utf-8');
const before = fs.statSync(p);
console.log('before_size', before.size);

let syncError;
try {
  const bytesWritten = fs.writeFileSync(p, Buffer.alloc(4));
  console.log('bytes_written', bytesWritten);
} catch (error) {
  syncError = error;
}
console.log('write_error', syncError?.name, syncError?.code, syncError?.message);

const afterStat = fs.statSync(p);
console.log('after_size', afterStat.size);
console.log('after_content', fs.readFileSync(p, 'utf-8'));
JS

Repository: ddutchie/cairn

Length of output: 4153


🌐 Web query:

Node.js fs.writeFileSync truncate existing file if write fails documentation

💡 Result:

The fs.writeFileSync function in Node.js does not guarantee an atomic write operation [1]. If fs.writeFileSync fails partway through the writing process—for example, due to a system error, lack of disk space, or a process interruption—it does not automatically roll back the file to its original state [2]. If the function is used with its default flags (which typically include w), the file is opened in a mode that truncates the file to zero length upon opening [1]. Because the truncation occurs before the write operations begin, if the subsequent write operations fail, the file may remain truncated (empty or partially written) and the original data will be lost [3][2]. Key points regarding this behavior: - Lack of Atomicity: fs.writeFileSync performs multiple write operations internally [4]. It is not an atomic operation; a failure during execution can leave the file in a partially written or corrupted state [2][4]. - Truncation Timing: When using standard write flags like w, the file is truncated to length zero immediately when it is opened [1]. If the actual data writing fails afterwards, the initial truncation is already committed to the filesystem [2]. - Error Handling: As a synchronous function, fs.writeFileSync will throw an exception if an error occurs [5]. However, this exception is raised after the failure has already occurred, meaning the filesystem state has already been modified [5]. - Best Practices: To ensure data integrity, it is a common pattern to write data to a temporary file first and then rename that file to the destination path using fs.renameSync (or fs.promises.rename). This "write-then-rename" approach is atomic on most POSIX-compliant filesystems, ensuring that the destination file is either fully updated or left in its original state.

Citations:


Restore recovery safety for same-path note rewrites.

fs.writeFileSync(newPath, serialized, "utf-8") truncates the existing note file before attempting the write; an ENOSPC, I/O error, or process termination can leave it empty or partially written and corrupt durable note storage. Use an in-place recovery path, such as writing to a durable backup/tmp file, syncing the new contents, then restoring/syncing the target path, or otherwise avoid truncating an existing note before the write succeeds.

🧰 Tools
🪛 ast-grep (0.44.1)

[warning] 192-192: Filesystem path is not a string literal; a request-/variable-derived path can enable path traversal. Validate and normalize the path before use.
Context: fs.writeFileSync(newPath, serialized, "utf-8")
Note: [CWE-22] Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal').

(detect-non-literal-fs-filename-typescript)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@electron/shared/notes-io.ts` around lines 192 - 194, Update the same-path
branch in the note write flow to avoid calling fs.writeFileSync directly on the
existing target, preserving the original file if writing fails or the process
terminates. Use the existing recovery-safe backup/temp-file strategy, including
durable writes and restoration/sync of the target as needed, while keeping the
early return behavior after a successful rewrite.

🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== repo files around notes-io =="
fd -a 'notes-io\.ts$' . || true

echo "== git status stat =="
git status --short || true

echo "== relevant file outline/size =="
if [ -f electron/shared/notes-io.ts ]; then
  wc -l electron/shared/notes-io.ts
  ast-grep outline electron/shared/notes-io.ts --view compact || true
  sed -n '140,225p' electron/shared/notes-io.ts
fi

echo "== search writeFileSync and note write paths =="
rg -n "writeFileSync|open\\(|fs\\.rename|rename\\(|\\blstat\\(|\\bstats|Note|note" electron/shared/notes-io.ts electron/shared || true
rg -n "electron/shared/notes-io" . || true

echo "== Next docs refs =="
fd -a . node_modules/next/dist/docs -t f 2>/dev/null | head -50 | sed 's#^\./##' || true
if [ -d node_modules/next/dist/docs ]; then
  rg -n "workspace|symlink|symlinks|writeFileSync|rename|noatime|nofollow|replace|race" node_modules/next/dist/docs -S || true
fi

Repository: ddutchie/cairn

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== imports/namespace setup =="
sed -n '1,40p' electron/shared/notes-io.ts

echo "== writeNoteFile helpers surrounding path resolution =="
sed -n '128,215p' electron/shared/notes-io.ts

echo "== findNoteFilePath implementation =="
sed -n '95,126p' electron/shared/notes-io.ts

echo "== package/runtime type relevant =="
node - <<'JS'
const fs = require('fs');
console.log(JSON.stringify({
  nodeVersion: process.version,
  fsWriteFileSyncPathSupported: 'path' in fs.writeFileSync.toString(),
}, null, 2));

fs.writeFileSync('/tmp/crain-test-writefile.txt', 'ok');
console.log(fs.readFileSync('/tmp/crain-test-writefile.txt', 'utf8'));
fs.unlinkSync('/tmp/crain-test-writefile.txt');

const path = require('path');
const resolved = path.resolve('/tmp/a/b/c.md');
console.log("path.resolve does not follow fs symlinks:", resolved);
JS

echo "== behavioral probe: fs.writeFileSync follows resolved symlink =="
tmp="$(mktemp -d)"
mkdir -p "$tmp/inside"
printf "# initial" > "$tmp/inside/note.md"
ln -s "$tmp/inside/note.md" "$tmp/link.md"
node - <<JS
const fs = require('fs');
const path = require('path');
const tmp = process.argv[1];
process.chdir(tmp);
fs.writeFileSync('link.md', 'redirected');
console.log(fs.readFileSync(path.resolve(tmp, 'note.md'), 'utf8'));
process.stdin.destroy(); // no await fs.unlink...
JS
rm -rf "$tmp"

Repository: ddutchie/cairn

Length of output: 8268


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== behavioral probe: fs.writeFileSync resolves symlinks =="
tmp="$(mktemp -d)"
mkdir -p "$tmp/inside"
printf "# initial" > "$tmp/inside/note.md"
ln -s "$tmp/inside/note.md" "$tmp/link.md"
node - <<JS
const fs = require('fs');
const path = require('path');
const tmp = process.argv[1];
process.chdir(tmp);
fs.writeFileSync('link.md', 'redirected');
console.log(fs.readFileSync(path.resolve(tmp, 'note.md'), 'utf8'));
JS
rm -rf "$tmp"

echo "== package versions/scripts relevant to ts check =="
if [ -f package.json ]; then
  jq '{scripts, devDependencies, dependencies}' package.json | sed -n '1,180p' || true
fi

Repository: ddutchie/cairn

Length of output: 1060


🌐 Web query:

Node.js fs.writeFileSync symlink path follows symlink documentation

💡 Result:

In Node.js, the fs.writeFileSync() method follows symbolic links by default [1][2]. When a symbolic link is provided as the file path, the method will resolve the link and write the data to the target file [2]. This behavior is consistent with the underlying operating system's standard file system operations, where opening a file for writing typically follows symlinks [2]. If you intend to manage the symbolic link itself rather than the target file, you would typically use methods like fs.unlinkSync() or fs.symlinkSync() to handle the link, or verify the file type using fs.lstatSync() before performing write operations [1][3][4]. Documentation for fs.writeFileSync does not provide an explicit "follow symlinks" flag to toggle this behavior, unlike some other newer or specific file system utilities in Node.js (such as certain globbing or directory traversal options) that have recently introduced followSymlinks parameters [4][5].

Citations:


🌐 Web query:

Node.js fs writeFile path option resolves symlinks lstat nofollow flags fs.openNoFollow

💡 Result:

In Node.js, the fs.writeFile and fsPromises.writeFile functions do not provide a direct option to specify lstat or O_NOFOLLOW (which prevents following symbolic links) for the destination path [1][2][3]. When you call fs.writeFile(path, data, options), Node.js inherently resolves symbolic links at the provided path [4][1]. The function essentially opens the file for writing, which involves following symbolic links to the actual target file [1][3]. There is no "verbatimSymlinks" or "noFollow" flag available for writeFile that would allow you to write directly to a symbolic link without resolving it, nor is there an interface to pass low-level flags like fs.constants.O_NOFOLLOW directly to the writeFile operation in the options object [1][2][3]. Key points regarding your inquiry: - Path Resolution: writeFile resolves symbolic links by design [4][1]. If path is a symbolic link, the data will be written to the file that the symlink points to, not to the symlink itself [1][3]. - O_NOFOLLOW: While Node.js provides fs.constants.O_NOFOLLOW for use with fs.open (or fsPromises.open), this constant cannot be passed through fs.writeFile. If you require behavior where symbolic links are not followed (e.g., to fail if a symlink is encountered instead of following it), you must use the lower-level fs.open method with the O_NOFOLLOW flag to obtain a file handle, and then perform the write operation using that handle [1][3]. - Related Options: Note that some newer Node.js APIs (such as those for recursive directory operations or globbing) have introduced options like verbatimSymlinks or followSymlinks, but these are not applicable to the fs.writeFile function [2][5][6][7]. To achieve behavior that respects O_NOFOLLOW, consider this pattern: 1. Use fs.open(path, 'w', fs.constants.O_NOFOLLOW) to open the file. 2. If the operation succeeds, use fs.write with the resulting file descriptor. 3. If it fails due to a symbolic link, you will receive an error (typically ELOOP or similar, depending on the platform) indicating the path was a symbolic link.

Citations:


Do not follow workspace symlinks during in-place writes.

fs.writeFileSync(newPath, ...) resolves the destination path, so a malicious or replaced note entry can redirect an MCP write outside the allowed workspace. Reject symlinked note paths and use a no-follow open path where available; a standalone lstat check is raceable.

🧰 Tools
🪛 ast-grep (0.44.1)

[warning] 192-192: Filesystem path is not a string literal; a request-/variable-derived path can enable path traversal. Validate and normalize the path before use.
Context: fs.writeFileSync(newPath, serialized, "utf-8")
Note: [CWE-22] Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal').

(detect-non-literal-fs-filename-typescript)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@electron/shared/notes-io.ts` around lines 192 - 194, Update the in-place
write branch guarded by existingPath === newPath to prevent symlink traversal:
reject symlinked note paths and write through a no-follow file-descriptor-based
path where supported, rather than calling fs.writeFileSync(newPath, ...). Do not
rely on a standalone lstat check; ensure the protected open/write operation
itself cannot follow a replaced symlink.

Source: Linters/SAST tools

…polish

- notes-io: the same-path in-place write is now crash-safe. It backs up
  the current bytes, truncates the existing file (openSync 'w', keeping
  the inode so no unlink event fires), fsyncs, then drops the backup;
  on any error it restores the original. Adds a regression test.
- Confetti: ConfettiHost cleanup detaches externalFire only if it still
  references this effect's fn (identity check, matching the Toast bridge).
- Toast: announce each toast via AccessibilityInfo.announceForAccessibility
  so screen-reader users hear it (the card is pointerEvents=none).
@ddutchie
ddutchie merged commit ef74813 into main Jul 26, 2026
6 checks passed
@ddutchie
ddutchie deleted the ddutchie/mobileconfetti branch July 26, 2026 21:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant