Cap icon indicating copy to clipboard operation
Cap copied to clipboard

fix(desktop): restore last confirmed capture area when reopening selector

Open ManthanNimodiya opened this issue 6 months ago • 1 comments

Problem

When a user had previously selected a capture area and reopened the area selector, it always started blank, forcing them to redraw their selection every time. This was reported by multiple users in the community.

The root cause was in target-select-overlay.tsx: initialAreaBounds (which seeds the Cropper's starting position) was always initialized to undefined, even when an existing area target was already set.

Solution

Added an effectiveInitialBounds memo that falls back to the current captureTarget area bounds when no explicit initialAreaBounds is set. Both initialCrop and shouldShowSelectionHint now use this memo, so:

  • Opening the selector with a previously confirmed area pre-loads those bounds
  • The "draw a selection" hint is suppressed when bounds are available
  • Re-entering area mode within the same session also restores correctly

Also fixed capture-area.tsx (the alternate area selection flow) with the same pattern, activeScreenId now handles both "display" and "area" capture target variants.

Test Plan

  • [x] Confirm a capture area → reopen selector → previous selection is pre-loaded ✓
  • [x] Adjust the pre-loaded area → close → reopen → shows updated bounds ✓
  • [x] Switch to display mode and back to area mode within same session → bounds restored ✓
  • [x] First-time use (no previous area) → blank selector with draw hint ✓

Greptile Summary

This PR restores previously confirmed capture-area bounds when the selector is reopened, fixing a reported UX regression. The fix addresses both selection flows independently: target-select-overlay.tsx gets an effectiveInitialBounds memo that falls back to options.captureTarget.bounds (guarded by target.screen === params.displayId for multi-display safety), and capture-area.tsx gets a screenId derived from both "display" and "area" variants so that a prior area confirmation no longer silently breaks subsequent saves and pre-loads.

  • target-select-overlay.tsx: new effectiveInitialBounds memo correctly short-circuits to stored captureTarget bounds; drives both shouldShowSelectionHint and initialCrop.
  • capture-area.tsx: activeScreenId now returns target.screen for the "area" variant; a "frozen on first non-null" pattern prevents stale async Tauri-store updates from overwriting the resolved screen ID. Minor gap: initialCrop doesn't fall back to rawOptions.captureTarget.bounds, so the first open of capture-area.tsx after an overlay-confirmed area still starts blank.

Confidence Score: 4/5

Safe to merge; the fix is scoped to UI initialisation logic and cannot cause data loss or corrupt the saved capture target.

The overlay fix is solid and well-guarded. The capture-area.tsx fix correctly unblocks the previously broken area variant path, but the initialCrop accessor still reads only from state.lastSelectedBounds and doesn't fall back to rawOptions.captureTarget.bounds, leaving a small parity gap with the overlay flow. The redundant reactive dependency in the frozen-signal effect is harmless but worth cleaning up.

apps/desktop/src/routes/capture-area.tsx — the initialCrop fallback logic and the screenId guard effect.

Important Files Changed

Filename Overview
apps/desktop/src/routes/capture-area.tsx Adds activeScreenId memo to handle both display and area variants, and a frozen screenId signal to prevent stale async Tauri-store resets; correctly threads screenId through hasStoredSelection, handleConfirm, reset, and initialCrop. Minor: screenId() is read as a reactive dep inside the guard effect (benign extra run), and initialCrop doesn't fall back to rawOptions.captureTarget.bounds for the area variant, leaving a gap when the area was last confirmed via the overlay flow.
apps/desktop/src/routes/target-select-overlay.tsx Adds effectiveInitialBounds memo that falls back to options.captureTarget.bounds when initialAreaBounds is unset and the current display matches; correctly guards on target.screen === params.displayId for multi-display safety; updates both shouldShowSelectionHint and initialCrop to use the new memo. Logic looks correct.
Prompt To Fix All With AI
Fix the following 2 code review issues. Work through them one at a time, proposing concise fixes.

---

### Issue 1 of 2
apps/desktop/src/routes/capture-area.tsx:95-98
**Effect reads `screenId()` as a reactive dependency**

`screenId()` is accessed inside the effect body, so SolidJS tracks it as a dependency. When `setScreenId(id)` fires, the effect re-runs: `activeScreenId()` is still the same `id`, `!screenId()` is now `false`, so nothing happens — it's benign but causes an extra scheduling cycle. Using `untrack(screenId)` inside the condition removes the unnecessary dependency and matches the intent of "only set once."

```suggestion
	createEffect(() => {
		const id = activeScreenId();
		if (id && !untrack(screenId)) setScreenId(id);
	});
```

### Issue 2 of 2
apps/desktop/src/routes/capture-area.tsx:313-321
**`initialCrop` doesn't fall back to `rawOptions.captureTarget.bounds` for the area variant**

`state.lastSelectedBounds` is only populated by `capture-area.tsx`'s own `handleConfirm`. If the user previously confirmed an area through `target-select-overlay.tsx` (which writes only to `options.captureTarget`), `state.lastSelectedBounds` will have no entry for that screen, and `initialCrop` returns `CROP_ZERO`. The overlay's `effectiveInitialBounds` memo handles this by falling back to `options.captureTarget.bounds` when variant is `"area"` — the same pattern could be applied here to keep both flows consistent.

Reviews (1): Last reviewed commit: "fix(desktop): restore last confirmed cap..." | Re-trigger Greptile

Greptile also left 2 inline comments on this PR.

ManthanNimodiya avatar May 26 '26 15:05 ManthanNimodiya

@richiemcilroy, have a look when you get chance and lmk for any changes

ManthanNimodiya avatar May 26 '26 16:05 ManthanNimodiya

@greptileai please re-review

ManthanNimodiya avatar Jun 07 '26 02:06 ManthanNimodiya

@tembo please review

ManthanNimodiya avatar Jun 16 '26 02:06 ManthanNimodiya

@tembo please review

done — posted a review on PR #1872.

the fix is solid: i traced both flows against Cropper.computeInitialBounds and confirmed the cropper reads initialCrop imperatively (only at mount/reset), so making effectiveInitialBounds reactive can't cause spurious crop resets. target-select-overlay.tsx looks correct.

three points raised:

  1. (medium) the frozen screenId in capture-area.tsx can latch onto the "0" default. createOptionsQuery seeds captureTarget to the hardcoded { variant: "display", id: "0" }, and the real value loads async from the tauri store. so untrack(activeScreenId) is always non-null at freeze time. in the happy path localStorage sync-hydrates the right target first, but if localStorage is empty/migrated (e.g. first open after the -2 key rename, wiped webview cache), it freezes on "0" and the async update can never correct it — the guarding effect is dead because screenId() is already truthy. result would be a blank cropper + handleConfirm saving screen: "0". worth confirming or simplifying (a plain reactive activeScreenId() gives the same value at mount).

  2. (low) hasStoredSelection doesn't mirror the new initialCrop area fallback — same thing greptile flagged. can briefly flash the "draw a selection" hint on reopen when the area was confirmed via the overlay flow. one-line fix.

  3. target-select-overlay.tsx — no concerns, display-scoping is correct.

ship-able once #1 is confirmed safe or simplified and #2 is polished.

tembo[bot] avatar Jun 16 '26 02:06 tembo[bot]

Superagent didn't find any vulnerabilities or security issues in this PR.

superagent-security avatar Jun 16 '26 16:06 superagent-security

@tembo, @greptileai please re-review

ManthanNimodiya avatar Jun 16 '26 16:06 ManthanNimodiya

@tembo, @greptileai please re-review

re-reviewed pr #1872. the earlier rounds are all resolved now — screenid is a plain memo (no reactive effect), initialcrop falls back to capturetarget bounds, effectiveinitialbounds guards ≤1×1 bounds, and hasstoredselection checks lastselectedbounds before the capturetarget fallback.

one regression is still open: in capture-area.tsx, reset() clears the persisted lastselectedbounds but leaves rawoptions.capturetarget untouched. since this pr added the capturetarget fallback to both hasstoredselection and initialcrop, reset is now only half-effective — in-session the draw hint stays suppressed, and on reopen the just-cleared area reappears. before this pr reset fully cleared the selection, so it's a regression scoped to exactly what this pr touches.

i posted the details + a suggested fix (also zero out the area bounds on capturetarget in reset()) as a pr comment, and offered to push the fix if they want it.

https://github.com/CapSoftware/Cap/pull/1872#issuecomment-4721299746

tembo[bot] avatar Jun 16 '26 17:06 tembo[bot]

Re-review — looks close. The earlier rounds are resolved; one regression in capture-area.tsx's reset() is still open.

✅ Verified resolved on 4de6f6dcc:

  • screenId no longer read reactively inside an effect (now a plain memo alias).
  • initialCrop falls back to captureTarget.bounds for the area variant.
  • effectiveInitialBounds guards ≤1×1 bounds so the draw-selection hint still shows.
  • hasStoredSelection checks lastSelectedBounds before the captureTarget fallback.

⚠️ Open: reset() clears the persisted store but not captureTarget, so the fallback resurrects the old bounds

apps/desktop/src/routes/capture-area.tsx (lines 161-170):

function reset() {
	cropperRef?.reset();
	setAspect(null);

	const id = screenId();
	if (!id) return;
	setState("lastSelectedBounds", (values) =>
		values?.filter((v) => v.screenId !== id),
	);
}

reset() removes the entry from the persisted lastSelectedBounds, but rawOptions.captureTarget still holds the old area bounds. Because this PR added the captureTarget fallback to both hasStoredSelection and initialCrop, the clear is now only half-effective:

  • In-session: right after Reset, crop() is zeroed but hasStoredSelection() still returns true via the area branch → the "draw a selection" hint stays suppressed even though there's no selection.
  • Across reopens: next time the window opens, lastSelectedBounds has no entry, so initialCrop falls through to captureTarget.bounds and the just-cleared area reappears.

Before this PR lastSelectedBounds was the only source, so Reset fully cleared the selection — this is a behavior regression introduced here, scoped exactly to the surface the PR touches.

Suggested fix — also clear the area bounds on the captureTarget for that screen:

function reset() {
	cropperRef?.reset();
	setAspect(null);

	const id = screenId();
	if (!id) return;
	setState("lastSelectedBounds", (values) =>
		values?.filter((v) => v.screenId !== id),
	);

	const target = rawOptions.captureTarget;
	if (target.variant === "area" && target.screen === id) {
		setOptions(
			"captureTarget",
			reconcile({
				variant: "area",
				screen: id,
				bounds: {
					position: { x: 0, y: 0 },
					size: { width: 0, height: 0 },
				},
			}),
		);
	}
}

The ≤1 size guards already in hasStoredSelection/effectiveInitialBounds then correctly treat the zeroed bounds as "no selection", so the hint reappears and reopening starts blank.

(Note: the overlay's "Reset selection" in target-select-overlay.tsx doesn't persist anything either way — it only mutates captureTarget on confirm/mode-switch — so it's internally consistent and not affected by this.)

Happy to push this fix to the branch if you'd like.

tembo[bot] avatar Jun 16 '26 17:06 tembo[bot]

@tembo please re-review

ManthanNimodiya avatar Jun 16 '26 17:06 ManthanNimodiya

@tembo please re-review

done re-reviewing #1872 (at commit dc13f2b9) — posted the review on the pr.

everything from my last pass plus greptile's concern is now resolved:

  • #1 frozen screenId latching onto the "0" default → gone, screenId is now a plain reactive alias of the activeScreenId memo
  • #2 hasStoredSelection not mirroring the initialCrop area fallback → fixed, now falls back to the captureTarget area variant (guarded on width/height > 1), so the hint no longer flashes on reopen
  • greptile — reset() leaving captureTarget intact and resurrecting old bounds → fixed, reset() now zeros the area bounds and all read sites agree (> 1 = has selection, <= 1 = none), so the cleared state persists across reopen
  • overlay flow still correctly scoped to the right display

two minor non-blocking notes (both pre-existing, not regressions): reset() calls cropperRef.reset() before clearing state so the box briefly animates back to the old selection; and a reset-without-confirm now persists a 0×0 area target worth a quick sanity-check at the recording entry point.

net: lgtm, shippable.

tembo[bot] avatar Jun 16 '26 17:06 tembo[bot]

@tembo please re-review

ManthanNimodiya avatar Jun 16 '26 17:06 ManthanNimodiya

@tembo please re-review

done re-reviewing #1872 at the latest commit (9ed93e9) — posted the review on the pr.

the only change since my last pass was one commit reordering initialCrop to prefer captureTarget bounds over lastSelectedBounds. traced it through and it's correct:

  • consistency holds across all read sites — hasStoredSelection is true exactly when initialCrop returns non-zero bounds, in all four state combinations, so no flash-of-hint or blank-cropper mismatch
  • it's a real improvement: the overlay flow writes captureTarget but never the window's persisted lastSelectedBounds, so preferring captureTarget shows the freshest confirmed area instead of a stale one. within capture-area.tsx the two stay in sync anyway (confirm writes both, reset clears both)

everything from earlier rounds still holds (plain screenId memo, reset() zeroes the area bounds, ≤1×1 guards consistent). ci is green (typecheck/lint/format all pass).

net: lgtm, shippable. left two pre-existing non-blocking notes (cosmetic animate-back on reset; a reset-without-confirm persists a 0×0 area target worth a sanity-check at the recording entry point) — neither introduced by this commit.

tembo[bot] avatar Jun 16 '26 17:06 tembo[bot]

@tembo please re-review

ManthanNimodiya avatar Jun 17 '26 17:06 ManthanNimodiya