You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by as...@apache.org on 2026/10/10 10:49:56 UTC

(maka) branch main updated: fix(desktop,ui): stage a selected message's quotes on edit (#5274)

This is an automated email from the ASF dual-hosted git repository.

Astro-Han pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/maka.git


The following commit(s) were added to refs/heads/main by this push:
     new 92b8c086c7 fix(desktop,ui): stage a selected message's quotes on edit (#5274)
92b8c086c7 is described below

commit 92b8c086c74bc0d7e98c3c89092d404d0c240601
Author: 小七 <gg...@gmail.com>
AuthorDate: Sat Oct 10 18:49:51 2026 +0800

    fix(desktop,ui): stage a selected message's quotes on edit (#5274)
    
    Review follow-ups (#5274 review):
    
    - prepareRevisionSend re-keyed the edit-start snapshot, so quotes the user
      removed or re-annotated during the edit reappeared on the branch and
      could be sent. The re-key now lands the plate's current quotes, and the
      send reads them live (the before-send snapshot retires — the re-key
      covers its case).
    - Drops the stale-base footer copy block and a dead regenerate key: no
      production code on current main references the old footer shape that
      survived in this branch's base.
    
    The no-op gate keeps counting the model-facing comment.
    
    Generated-by: GLM-5.3-Flash (ZCode)
    Merge upstream/main into fix/desktop-revision-structured-context
    fix(desktop,ui): preserve the quote plate across the in-flight revision send
    
    The revision send awaited prepareRevisionSend before reading the plate,
    and the lifecycle re-keys it mid-send: the plate's current quotes are
    copied onto the branch child and the source bucket is emptied in place.
    The still-running sendWithAttachments invocation holds quotesForSend
    from the render that started the send, so it read the emptied source
    bucket, got undefined, and submitted the edited replacement without its
    quotes or their edited annotations (#5274 review).
    
    Read the plate through the re-keyed owner explicitly: quotesForSend now
    resolves the bucket by owner key (defaulting to the live draft key for
    the non-revision send paths), and the revision send passes the prepared
    draft's session id. The resumed send therefore reads the child bucket
    the lifecycle just wrote — removals and re-annotations included.
    
    The regression test drives beginEditUserMessage → an in-render
    quotesForSend capture → prepareRevisionSend and asserts the re-keyed
    plate with its edited annotation still reaches the send; it fails on
    the previous head with `actual: undefined`.
    
    Generated-by: GLM-5.3-Flash (ZCode)
    fix(desktop,ui): keep quotes added during a cancelled edit
    
    Cancelling a revision draft cleared both draft keys wholesale, so quotes
    the user staged during the edit were lost together with the edit's own
    restaged set (#5274 review: "Cancelling an edit deletes quotes added
    during it" — on main they stayed in the composer, and adding quotes
    during an edit is supported).
    
    clearQuotes now returns the entries it removed, and
    clearRevisionStagedContext re-stages whatever lies beyond the edit's
    beginEdit snapshot (matched per QuoteRef field set, counted as a
    multiset) onto the source Session the cancel returns to — whether the
    user added them before or after the branch child was prepared. The
    edit's own items are still dropped wherever the commit left them.
    
    The regression tests drive a cancelled edit with a user-added quote on
    each side of the prepare step and assert the addition survives on the
    source key while the composer text rolls back; both fail on the
    previous head, the first with the edit's restaged quote returned
    instead of the user's own, the second with no plate restore at all.
    
    Generated-by: GLM-5.3-Flash (ZCode)
    fix(ui): treat negative owned counts as fully user-owned
    
    clearRevisionStagedContext drops the edit's own quotes by per-key count:
    the first N entries matching the beginEdit snapshot are the edit's, and
    everything past that count is the user's own staging. The kept check
    compared the remaining count with `=== 0`, so once the counter ran
    negative the surplus stopped matching: when the user added a second copy
    of a quote the edit had also staged, the third identical plate entry was
    dropped despite being the user's.
    
    Treat any non-positive count as fully user-owned (`<= 0`), so every
    entry past the edit's own count survives the cancel.
    
    Fixes a P3 raised inline on apache/maka#5274.
    
    Generated-by: GLM-5.3-Flash (ZCode)
    Merge upstream/main (8648258d0)
    
    Brings in the composer-submit extraction (#5815) and the allow-unchanged
    edit-and-resend decision, merged into the revision staged-context feature:
    
    - app-shell.tsx keeps the upstream extraction; the staged-context wiring and
      the #5274 re-keyed quotesForSend/clearQuotes semantics move into
      features/conversation/controller/composer-submit.ts (owner-keyed ports).
    - app-shell-revision-actions.ts keeps the @maka/ui delegation;
      TurnRevisionDraftBase drops originalText and the unchanged gate
      (revisionStagedContextUnchanged) so unchanged resends pass through per
      upstream #5815, while the mixed-context conflict gate stays.
    - conversation-copy.ts keeps both new locale keys
      (revisionDraftQuoteConflict, revisionMixedContextUnsupported) on top of
      upstream's revisionUnchanged removal and #5815 copy updates.
    - renderer-architecture.json regenerated via check-renderer-architecture
      --write; app-shell.tsx budget drops 12091 -> 11154.
    Tests: upstream app-shell-revision-resend gains a stagedContext fake; the ui
    revision suite expectations updated to the allow-unchanged behavior.
    
    Generated-by: GLM-5.3-Flash (ZCode)
    fix(desktop): assemble the revision staged context outside the frozen shell
    
    Root cause: upstream #5546 extracted app-shell helpers and drove the frozen
    shell's nonTriviaTokens baseline down to 11129 with zero headroom, so the
    merge that re-attached this PR's stagedContext wiring (a 7-line factory in
    the createAppShellRevisionActions ports object, +25 tokens) broke the
    renderer architecture ratchet: 11129 -> 11154.
    
    Fix: assemble the RevisionStagedContext closure inside the desktop
    useComposerAttachments controller (a feature file outside the debt
    ledger), right beside the hooks that own the quote/attachment buckets.
    The frozen shell now forwards one member (stagedContext,) instead of
    building the factory inline. The restoreAttachments entry the shell only
    carried for that factory is dropped from its destructure: its sole
    consumer was the deleted block (RevisionStagedContext declares no such
    member and nothing in @maka/ui reads it from the staged context).
    
    Verification:
    - check:renderer-architecture --base 6e21e61119 --strict-base: red
      (11129 -> 11154) before, green (11129 == base) after; ledger diff is
      the single app-shell.tsx nonTriviaTokens line, no other entry moved.
    - desktop focused suites (app-shell-revision-actions,
      use-composer-quotes-revision-send, app-shell-revision-resend,
      new-task-staged-content): 18/18 pass.
    - packages/ui full suite: 710/710 pass.
    - typecheck green: ui tsconfig + desktop preload/main/renderer/storybook.
    - biome lint clean on both touched source files; check:asf-headers green.
    
    Generated-by: GLM-5.3-Flash (ZCode)
    Merge upstream/main (28cc4e647)
    
    Resolve the renderer-architecture.json conflict by re-pricing the ledger
    from the merged tree via check-renderer-architecture.mjs --write (all
    entries at real merged-tree values, within baseline); drop the trailing
    blank line at EOF in conversation-copy.ts flagged by diff-check.
    Merge upstream/main (0aa2707b5)
    
    Resolve renderer-architecture.json by re-pricing from the merged tree via check-renderer-architecture.mjs --write.
    Merge upstream/main (d6876d708)
    
    Resolve the renderer-architecture.json conflict by taking main's ledger
    (new #5851 file entries) as the base and re-pricing every entry from the
    merged tree via check-renderer-architecture.mjs --write; the check passes
    against the ratchet baseline.
    Merge upstream/main (d7dffca98)
    Merge upstream/main (c838e1fa7)
    
    Fourth structural catch-up for #5274: carries #5868 (Composer staging
    moved into a persistent ComposerStagingProvider owner) and #5884 (task
    archive timestamps).
    
    Conflict resolution ports the revision staged-context semantics onto the
    new owner structure: ComposerStagingSubmission gains optional owner-key
    reads/clears (snapshot for captured submissions, live plate for the
    revision re-key) and ComposerStagingCommands gains stagedContext(); the
    frozen shell forwards the one composerStaging handle and the revision
    assembler derives the gate probe and plate reads from it.
    Merge upstream/main (1e80e3b88) into fix/desktop-revision-structured-context
    
    # Conflicts:
    #       apps/desktop/renderer-architecture.json
    Merge upstream/main (c7fa6bb6a) into fix/desktop-revision-structured-context
    
    # Conflicts:
    #       apps/desktop/renderer-architecture.json
    Merge upstream/main (255ae23ae) into fix/desktop-revision-structured-context
    Merge upstream/main (229e1b466) into fix/desktop-revision-structured-context
    Merge upstream/main (f7633c3d7) into fix/desktop-revision-structured-context
    Merge upstream/main (7c90bac2d) into fix/desktop-revision-structured-context
    Merge remote-tracking branch 'upstream/main' into fix/desktop-revision-structured-context
    
    # Conflicts:
    #       apps/desktop/renderer-architecture.json
    fix(desktop): drop the stale regenerate footer copy
    
    #5468 removed the Regenerate feature (87ff2799a), deleting the footer's
    `regenerate` label and the `regenerateRunning` / `regenerateAgain` /
    `regenerate` / `requestRegenerate` keys from the conversation copy. This
    branch's stale base still carried the block, so the merge-base diff
    re-adds those keys across the contract type and all three locales
    (including the zh-TW 本輪迴答 wording) while nothing on current main
    references them — merging would resurrect dead strings.
    
    Drop the block from the type and the zh-CN / zh-TW / en entries, matching
    the upstream shape exactly; the `lineage.regenerated*` keys are a
    different, live feature and stay.
    
    Generated-by: GLM-5.3-Flash (ZCode)
---
 apps/desktop/renderer-architecture.json            |  16 +-
 .../scripts/check-renderer-architecture.mjs        |  25 +-
 .../scripts/check-renderer-architecture.test.mjs   |  79 +++
 .../__tests__/app-shell-revision-actions.test.ts   |  76 ++-
 .../__tests__/app-shell-revision-resend.test.ts    |  14 +-
 .../main/__tests__/composer-staging-owner.test.ts  |   2 +-
 .../use-composer-quotes-revision-send.test.ts      | 161 ++++++
 .../application/contracts/conversation-copy.ts     |   8 +-
 .../controller/composer-staging-commands.ts        |   1 +
 .../conversation/controller/composer-submit.ts     |  17 +-
 .../conversation/controller/revision-actions.ts    | 384 +++----------
 .../controller/use-composer-attachments.ts         |  13 +-
 .../conversation/controller/use-composer-quotes.ts |  45 +-
 .../controller/use-composer-submission.ts          |   4 +-
 .../model/composer-staging-contract.ts             |  16 +-
 .../conversation/ui/composer-staging-provider.tsx  |  12 +-
 .../__tests__/chat-turn-answer-identity.test.tsx   |  79 +++
 .../src/__tests__/revision-staged-context.test.ts  | 463 ++++++++++++++++
 packages/ui/src/chat-turn.tsx                      |  23 +-
 packages/ui/src/conversation-copy.ts               |  14 +-
 packages/ui/src/index.ts                           |   1 +
 packages/ui/src/revision-staged-context.ts         | 605 +++++++++++++++++++++
 packages/ui/src/use-composer-attachments.ts        |   4 +
 23 files changed, 1684 insertions(+), 378 deletions(-)

diff --git a/apps/desktop/renderer-architecture.json b/apps/desktop/renderer-architecture.json
index c85c094fce..185f752a00 100644
--- a/apps/desktop/renderer-architecture.json
+++ b/apps/desktop/renderer-architecture.json
@@ -507,7 +507,7 @@
   "legacyAppShell": {
     "files": {
       "src/renderer/app-shell-chrome-actions.tsx": {
-        "importDeclarations": 1,
+        "importDeclarations": 0,
         "bridgePaths": {},
         "environmentCapabilities": {},
         "hookCalls": {
@@ -522,7 +522,7 @@
           "./shell/window-titlebar": 1,
           "@maka/ui": 1
         },
-        "importSpecifiers": 1,
+        "importSpecifiers": 0,
         "nonTriviaTokens": 122
       },
       "src/renderer/app-shell-command-actions.ts": {
@@ -612,7 +612,7 @@
         "nonTriviaTokens": 843
       },
       "src/renderer/app-shell-overlays.tsx": {
-        "importDeclarations": 5,
+        "importDeclarations": 4,
         "bridgePaths": {},
         "environmentCapabilities": {
           "window.addEventListener": 1,
@@ -638,11 +638,11 @@
           "@maka/ui": 1,
           "react": 1
         },
-        "importSpecifiers": 8,
+        "importSpecifiers": 7,
         "nonTriviaTokens": 858
       },
       "src/renderer/app-shell.tsx": {
-        "importDeclarations": 35,
+        "importDeclarations": 34,
         "bridgePaths": {},
         "environmentCapabilities": {
           "window.requestAnimationFrame": 3
@@ -730,11 +730,11 @@
           "@maka/ui": 1,
           "react": 1
         },
-        "importSpecifiers": 52,
+        "importSpecifiers": 43,
         "nonTriviaTokens": 7330
       },
       "src/renderer/use-app-shell-session-list.ts": {
-        "importDeclarations": 4,
+        "importDeclarations": 3,
         "bridgePaths": {},
         "environmentCapabilities": {},
         "hookCalls": {
@@ -757,7 +757,7 @@
           "@maka/ui": 1,
           "react": 1
         },
-        "importSpecifiers": 5,
+        "importSpecifiers": 4,
         "nonTriviaTokens": 479
       },
       "src/renderer/use-app-shell-session-workspace.ts": {
diff --git a/apps/desktop/scripts/check-renderer-architecture.mjs b/apps/desktop/scripts/check-renderer-architecture.mjs
index 29252357c8..f306541785 100644
--- a/apps/desktop/scripts/check-renderer-architecture.mjs
+++ b/apps/desktop/scripts/check-renderer-architecture.mjs
@@ -108,6 +108,10 @@ const RENDERER_VITE_CONFIG = 'vite.config.ts';
 const RENDERER_BUILD_SCRIPT =
   'vite build && node scripts/check-renderer-entry-output.mjs && node ../../scripts/check-third-party-notices.mjs';
 const DESKTOP_SELF_PREFIX = '@maka/desktop/';
+// The package renderer ownership is migrating into. Shell debt is defined to
+// shrink by moving onto it, so depending on the destination is the opposite
+// of debt and its edges are sanctioned for shell importers.
+const MIGRATION_TARGET_PACKAGE = '@maka/ui';
 const FEATURE_PUBLIC_ENTRY = /^src\/renderer\/features\/[^/]+\/index\.(?:(?:c|m)?(?:js|ts)x?)$/u;
 const ROOT_SYMBOL_ZONES = ['appShell', 'bootstrap', 'composition'];
 const CAPABILITY_DEBT_METRICS = [
@@ -3951,9 +3955,28 @@ function withoutSanctionedDependencies(desktopRoot, section, importerPath, depen
   return filtered;
 }
 
+function isMigrationTargetPackageSpecifier(dependency) {
+  const specifier = dependency.split(/[?#]/u, 1)[0];
+  return (
+    specifier === MIGRATION_TARGET_PACKAGE ||
+    specifier.startsWith(`${MIGRATION_TARGET_PACKAGE}/`)
+  );
+}
+
 function isSanctionedDependencyTarget(desktopRoot, section, importerPath, dependency) {
   const target = resolveDependency(desktopRoot, resolve(desktopRoot, importerPath), dependency);
-  if (!target) return false;
+  if (!target) {
+    // Bare package specifiers resolve to nothing inside the desktop tree.
+    // The migration destination is the one free among them: a shell importer
+    // depending on @maka/ui sheds ownership the shell is defined to lose,
+    // the same way validated copy catalogs take bare-package imports for
+    // free. Root entries stay fully priced: they are meant to become thin
+    // mounts.
+    return (
+      (section === 'legacyAppShell' || section === 'legacyAppShellClosure') &&
+      isMigrationTargetPackageSpecifier(dependency)
+    );
+  }
   const targetRelative = normalizePath(relative(desktopRoot, target));
   if (isValidatedCopyCatalog(desktopRoot, targetRelative)) return true;
   // Root entries are meant to become thin mounts; only catalogs are free for them.
diff --git a/apps/desktop/scripts/check-renderer-architecture.test.mjs b/apps/desktop/scripts/check-renderer-architecture.test.mjs
index ea05128a17..2fe7328ae7 100644
--- a/apps/desktop/scripts/check-renderer-architecture.test.mjs
+++ b/apps/desktop/scripts/check-renderer-architecture.test.mjs
@@ -3558,6 +3558,85 @@ describe('renderer architecture base-tree derivation (git fixtures)', () => {
     });
   });
 
+  it('sanctions a shell file migrating onto @maka/ui relative to the derived base tree', async () => {
+    // Only files named app-shell* enter the legacyAppShell ledger section,
+    // and every section file needs an ownership entry to pass validation.
+    const LEGACY_SHELL_WIDGET = 'src/renderer/app-shell-widget.ts';
+    const seed = architectureConfig({
+      rootDebt: { [RENDERER_ENTRY_PATH]: emptyDebt() },
+      ownership: [
+        {
+          capability: 'fixture-root',
+          targetZone: 'bootstrap',
+          legacyPaths: [RENDERER_ENTRY_PATH],
+        },
+        {
+          capability: 'fixture-shell-widget',
+          targetZone: 'shell',
+          legacyPaths: [LEGACY_SHELL_WIDGET],
+        },
+      ],
+    });
+    await withGitFixture(async (fixture) => {
+      // The base file carries more debt than the head ever will: the migration
+      // edge must be the only delta under test, so every priced metric shrinks.
+      await fixture.writeFiles({
+        [LEGACY_SHELL_WIDGET]: `
+          import { existsSync } from 'node:fs';
+          import { join } from 'node:path';
+
+          const widgetSlots = ['header', 'body', 'footer'];
+          const resolveWidgetPath = (root: string, name: string) =>
+            existsSync(join(root, name)) ? join(root, name) : root;
+
+          export const legacyWidget = {
+            name: 'legacy-widget',
+            slots: widgetSlots,
+            resolve: resolveWidgetPath,
+          };
+        `,
+      });
+      await fixture.writeLedger(seed);
+      const base = fixture.commit('base');
+
+      await fixture.writeFiles({
+        [LEGACY_SHELL_WIDGET]: `
+          import { revisionStage } from '@maka/ui';
+
+          export const legacyWidget = { name: 'legacy-widget', stage: revisionStage };
+        `,
+      });
+      await fixture.writeLedger(seed);
+      fixture.commit('migrate a legacy shell file onto @maka/ui');
+
+      for (const args of [['--base', base], ['--base', base, '--strict-base']]) {
+        assertPassed(fixture.runChecker(args), base, args.join(' '));
+      }
+    });
+  });
+
+  it('keeps pricing an @maka/ui edge gained by a root debt entry under --strict-base', async () => {
+    await withGitFixture(async (fixture) => {
+      await fixture.writeLedger();
+      const base = fixture.commit('base');
+      await fixture.writeFiles({
+        [RENDERER_ENTRY_PATH]: `
+          import { revisionStage } from '@maka/ui';
+          export const main = revisionStage;
+        `,
+      });
+      await fixture.writeLedger();
+      fixture.commit('point the root entry at @maka/ui');
+
+      const result = fixture.runChecker(['--base', base, '--strict-base']);
+      assert.notEqual(result.status, 0);
+      assert.match(
+        result.stderr,
+        /^- src\/renderer\/main\.tsx: new dependency debt @maka\/ui/mu,
+      );
+    });
+  });
+
   it('does not wedge on a base ledger that under-reports its own tree (#4250)', async () => {
     await withGitFixture(async (fixture) => {
       // The base ledger only knows one legacy file while the base *tree*
diff --git a/apps/desktop/src/main/__tests__/app-shell-revision-actions.test.ts b/apps/desktop/src/main/__tests__/app-shell-revision-actions.test.ts
index 6456c698b9..1f7240f3b4 100644
--- a/apps/desktop/src/main/__tests__/app-shell-revision-actions.test.ts
+++ b/apps/desktop/src/main/__tests__/app-shell-revision-actions.test.ts
@@ -48,6 +48,12 @@ function createActions(input: { messages: StoredMessage[]; failRefresh?: boolean
   let composerText = '';
   let selectionRevision = 0;
   const activeIdRef: { current: string | undefined } = { current: SESSION_1 };
+  const staged: {
+    quotes: unknown[];
+    restoredQuotes: unknown[][];
+    restoredAttachments: unknown[][];
+    clearedKeys: string[];
+  } = { quotes: [], restoredQuotes: [], restoredAttachments: [], clearedKeys: [] };
   const revisionDraftRef: { current: unknown } = { current: null };
   const actions = createRevisionActions({
     services: windowSubmissionServices(),
@@ -71,7 +77,24 @@ function createActions(input: { messages: StoredMessage[]; failRefresh?: boolean
       } as never,
     },
     readMessages: () => input.messages,
-    hasPendingAttachments: () => false,
+    staging: {
+      captureSubmission: () => ({ hasPendingContext: false }),
+      stagedContext: () => ({
+        quotes: staged.quotes,
+        attachments: [],
+        restoreQuotes: (_ownerKey: string, quotes: unknown[]) => {
+          staged.restoredQuotes.push(quotes);
+          staged.quotes.push(...quotes);
+        },
+        restoreAttachments: (_ownerKey: string, attachments: unknown[]) => {
+          staged.restoredAttachments.push(attachments);
+        },
+        clearQuotes: (ownerKey: string) => {
+          staged.clearedKeys.push(ownerKey);
+          return staged.quotes.splice(0, staged.quotes.length);
+        },
+      }),
+    },
     openSessionInChat: (sessionId: string) => {
       selectionRevision += 1;
       activeIdRef.current = sessionId;
@@ -92,10 +115,18 @@ function createActions(input: { messages: StoredMessage[]; failRefresh?: boolean
   } as never);
   return Object.assign(actions, {
     drafts,
+    staged,
     errors,
     infos,
     activeIdRef,
-    composerState: { get text(): string { return composerText; } },
+    composerState: {
+      get text(): string {
+        return composerText;
+      },
+      get attachments(): unknown[] {
+        return staged.restoredAttachments.at(-1) ?? [];
+      },
+    },
   });
 }
 
@@ -135,7 +166,11 @@ describe('app-shell revision actions with structured context (#5109)', () => {
     assert.equal(h.composerState.text, 'plain follow-up');
   });
 
-  it('rejects a source message that itself carries attachments', () => {
+  it('refuses editing a message that carries attachments (#5274 review)', () => {
+    // Attachment ownership does not follow a revision copy — the copied
+    // transcript stops before the selected turn, so no target-owned refs
+    // exist client-side to restage. The edit refuses rather than silently
+    // dropping the files.
     const h = createActions({
       messages: [
         userMessage('turn-1', 'with image', {
@@ -154,7 +189,30 @@ describe('app-shell revision actions with structured context (#5109)', () => {
 
     h.beginEditUserMessage('turn-1');
 
-    assert.equal(h.drafts.at(-1), undefined, 'attachment-bearing sources stay explicitly rejected');
+    assert.equal(
+      h.drafts.at(-1),
+      undefined,
+      'a revision copy excludes the revised turn, so no target-owned attachment rewrite exists to restage',
+    );
+    assert.equal(h.composerState.text, '', 'the composer stays untouched');
+  });
+
+  it('stages a source message quotes into the composer', () => {
+    const quote = { text: 'a large pasted excerpt', sourceTurnId: 'turn-0' };
+    const h = createActions({
+      messages: [userMessage('turn-1', 'explain this', { quotes: [quote] })],
+    });
+
+    h.beginEditUserMessage('turn-1');
+
+    const draft = h.drafts.at(-1) as { originalQuotes?: unknown[] } | undefined;
+    assert.ok(draft, 'a quote-carrying source message is editable now');
+    assert.deepEqual(draft?.originalQuotes, [quote]);
+    assert.deepEqual(
+      h.staged.restoredQuotes.at(-1),
+      [quote],
+      'the source quotes stage into the composer verbatim',
+    );
   });
 });
 
@@ -264,7 +322,15 @@ describe('revision draft lifecycle over a prepared send', () => {
         },
       },
       readMessages: () => [userMessage('turn-1', 'original message')],
-      hasPendingAttachments: () => false,
+      staging: {
+        captureSubmission: () => ({ hasPendingContext: false }),
+        stagedContext: () => ({
+          quotes: [],
+          attachments: [],
+          restoreQuotes: (_ownerKey: string, _quotes: unknown[]) => {},
+          clearQuotes: (_ownerKey: string) => [],
+        }),
+      },
       openSessionInChat: (sessionId: string) => {
         selectionRevision += 1;
         activeIdRef.current = sessionId;
diff --git a/apps/desktop/src/main/__tests__/app-shell-revision-resend.test.ts b/apps/desktop/src/main/__tests__/app-shell-revision-resend.test.ts
index 74cdc51274..4f0ec1f972 100644
--- a/apps/desktop/src/main/__tests__/app-shell-revision-resend.test.ts
+++ b/apps/desktop/src/main/__tests__/app-shell-revision-resend.test.ts
@@ -20,8 +20,8 @@
 /**
  * Unchanged-text edit-and-resend regression (PR #5815 follow-up).
  *
- * The production fix removed the `text.trim() === revision.originalText.trim()`
- * early return from the composer's submit path. The existing
+ * The production fix removed the unchanged-text early return from the
+ * revision send path. The existing
  * `app-shell-revision-actions.test.ts` suite only calls `prepareRevisionSend()`
  * directly, so it cannot tell whether the real submit path still short-circuits
  * unchanged text. This suite mounts the real ChatComposerRegion, wires its
@@ -214,7 +214,15 @@ async function mountRevisionWorld(): Promise<RevisionWorld> {
     },
     composerRef: composer,
     readMessages: () => [userMessage('turn-1', ORIGINAL_TEXT)],
-    hasPendingAttachments: () => false,
+    staging: {
+      captureSubmission: () => ({ hasPendingContext: false }),
+      stagedContext: () => ({
+        quotes: [],
+        attachments: [],
+        restoreQuotes: () => {},
+        clearQuotes: () => [],
+      }),
+    },
     openSessionInChat: (sessionId: string) => {
       selectionRevision += 1;
       activeIdRef.current = sessionId;
diff --git a/apps/desktop/src/main/__tests__/composer-staging-owner.test.ts b/apps/desktop/src/main/__tests__/composer-staging-owner.test.ts
index 24db5a463f..9eff95772a 100644
--- a/apps/desktop/src/main/__tests__/composer-staging-owner.test.ts
+++ b/apps/desktop/src/main/__tests__/composer-staging-owner.test.ts
@@ -371,7 +371,7 @@ for (const context of ['attachment', 'directory'] as const) {
       services: windowSubmissionServices(),
       uiLocale: 'en', activeIdRef, captureSelection: () => () => true, composerRef: view.composer,
       readMessages: () => [{ type: 'user', id: 'message', turnId: `guard-${context}`, text: 'original', ts: 1 }],
-      hasPendingAttachments: () => view.commands.captureSubmission().hasPendingContext,
+      staging: view.commands,
       openSessionInChat() {}, refreshSessions: async () => [],
       commitRevisionDraft: (draft) => { revisionDraftRef.current = draft; }, revisionDraftRef,
       toastApi: { info() {}, error: () => assert.fail('unexpected revision error') },
diff --git a/apps/desktop/src/main/__tests__/use-composer-quotes-revision-send.test.ts b/apps/desktop/src/main/__tests__/use-composer-quotes-revision-send.test.ts
new file mode 100644
index 0000000000..08b7fc4af9
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/use-composer-quotes-revision-send.test.ts
@@ -0,0 +1,161 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import assert from 'node:assert/strict';
+import { afterEach, test } from 'node:test';
+import { act, createElement } from 'react';
+import type { QuoteRef } from '@maka/core/events';
+import type { StoredMessage } from '@maka/core/session';
+// The feature index stopped re-exporting controller hooks (#5868); the test
+// support entry is the sanctioned channel for driving the quote bucket and
+// the revision lifecycle.
+import {
+  createRevisionActions,
+  useComposerQuotes,
+  type TurnRevisionDraft,
+} from '../../renderer/features/conversation/testing.js';
+import { installWindow, windowSubmissionServices } from './app-shell-chat-actions-fixture.js';
+import { cleanupFakeDom, installReactRenderer } from './fake-dom.js';
+
+const SESSION_1 = JSON.stringify(['host-1', 'session-1']);
+const SESSION_2 = JSON.stringify(['host-1', 'session-2']);
+
+function userMessage(
+  turnId: string,
+  text: string,
+  extra: Record<string, unknown> = {},
+): StoredMessage {
+  return {
+    id: `msg-${turnId}`,
+    type: 'user',
+    turnId,
+    ts: 1,
+    text,
+    ...extra,
+  } as StoredMessage;
+}
+
+afterEach(cleanupFakeDom);
+
+test('the in-flight revision send still reads the re-keyed plate (#5274 review)', async () => {
+  // The AppShell send is an in-flight closure: it captures quotesForSend from
+  // the render that started the send (draft key = the source Session), then
+  // awaits prepareRevisionSend, which copies the plate onto the branch child
+  // and empties the source bucket in place. The resumed send must therefore
+  // read the plate through the re-keyed owner key, or the replacement goes
+  // out without its quotes and their edited annotations.
+  const quotedQuote: QuoteRef = { text: 'a large pasted excerpt', sourceTurnId: 'turn-0' };
+  const { root } = installReactRenderer();
+  const activeIdRef: { current: string | undefined } = { current: SESSION_1 };
+  const revisionDraftRef: { current: TurnRevisionDraft | null } = { current: null };
+  const composerText = { current: '' };
+
+  let surface!: ReturnType<typeof useComposerQuotes>;
+  function Probe() {
+    surface = useComposerQuotes({ draftKey: activeIdRef.current ?? SESSION_1 });
+    return null;
+  }
+  await act(async () => root.render(createElement(Probe)));
+
+  const actions = createRevisionActions({
+    services: windowSubmissionServices(),
+    uiLocale: 'en' as never,
+    activeIdRef,
+    captureSelection: () => () => true,
+    composerRef: {
+      current: {
+        getText: () => composerText.current,
+        setText: (text: string) => {
+          composerText.current = text;
+        },
+        focus: () => {},
+        setDraft: (_sessionId: string, text: string) => {
+          composerText.current = text;
+        },
+        clearDraft: () => {},
+      } as never,
+    },
+    readMessages: () => [userMessage('turn-1', 'explain this', { quotes: [quotedQuote] })],
+    staging: {
+      captureSubmission: () => ({ hasPendingContext: false }),
+      stagedContext: () => ({
+        quotes: surface.pendingQuotes,
+        attachments: [],
+        restoreQuotes: surface.restoreQuotes,
+        clearQuotes: surface.clearQuotes,
+      }),
+    },
+    openSessionInChat: (sessionId: string) => {
+      activeIdRef.current = sessionId;
+    },
+    refreshSessions: async () => [],
+    commitRevisionDraft: (draft: TurnRevisionDraft | null) => {
+      revisionDraftRef.current = draft;
+    },
+    revisionDraftRef,
+    toastApi: { info: () => {}, error: () => {} },
+  } as never);
+
+  const restoreWindow = installWindow({
+    sessions: {
+      reviseBeforeTurn: async () => ({ id: SESSION_2 }),
+      abandonSessionCopy: async () => {},
+    },
+  });
+  try {
+    // Edit click stages the source message's quote under the source key.
+    await act(async () => actions.beginEditUserMessage('turn-1'));
+    assert.deepEqual(surface.pendingQuotes, [quotedQuote]);
+
+    // During the edit the user re-annotates the excerpt — the plate is the
+    // truth the replacement must carry (#5274 review).
+    await act(async () => surface.updateQuoteComment(0, 'the edited annotation'));
+
+    // The send captures quotesForSend from this render, then awaits the
+    // revision lifecycle — exactly the app-shell send's shape.
+    const quotesForSendAtSendStart: (ownerKey?: string) => readonly QuoteRef[] | undefined =
+      surface.quotesForSend;
+    assert.deepEqual(quotesForSendAtSendStart(), [
+      { text: 'a large pasted excerpt', sourceTurnId: 'turn-0', comment: 'the edited annotation' },
+    ]);
+
+    await act(async () => {
+      assert.equal(await actions.prepareRevisionSend('edited text'), true);
+    });
+    const expectedRevisionDraft = revisionDraftRef.current;
+    assert.equal(expectedRevisionDraft?.draftSessionId, SESSION_2);
+
+    // The resumed send reads the plate through the re-keyed owner: the
+    // render-time closure still points at the emptied source bucket.
+    const quotes = quotesForSendAtSendStart(expectedRevisionDraft?.draftSessionId);
+    assert.deepEqual(
+      quotes,
+      [
+        {
+          text: 'a large pasted excerpt',
+          sourceTurnId: 'turn-0',
+          comment: 'the edited annotation',
+        },
+      ],
+      'the in-flight send must deliver the re-keyed plate, edits included',
+    );
+  } finally {
+    restoreWindow();
+  }
+});
diff --git a/apps/desktop/src/renderer/application/contracts/conversation-copy.ts b/apps/desktop/src/renderer/application/contracts/conversation-copy.ts
index 00895fec0d..2a461f7dfc 100644
--- a/apps/desktop/src/renderer/application/contracts/conversation-copy.ts
+++ b/apps/desktop/src/renderer/application/contracts/conversation-copy.ts
@@ -41,6 +41,8 @@ export interface DesktopConversationCopy {
     revisionReadyTitle: string;
     revisionReadyDescription: string;
     revisionUnavailableTitle: string;
+    revisionDraftQuoteConflict: string;
+    revisionMixedContextUnsupported: string;
     revisionAttachmentsUnsupported: string;
     revisionTransformedTextUnsupported: string;
     revisionDraftAttachmentConflict: string;
@@ -342,7 +344,7 @@ function enDetail(parts: readonly string[]): string {
 
 const COPY = {
   'zh-CN': {
-    actions: { stopFailedTitle: '停止失败', stopFailedFallback: '任务操作失败,请稍后重试。', refreshSessionsFailedTitle: '刷新任务列表失败', refreshSessionsFailedFallback: '刷新任务列表失败,请稍后重试。', conversationErrorTitle: '任务出错', conversationErrorFallback: '任务运行失败,请稍后重试。', branchCreatedTitle: '已创建分支', branchCreatedDescription: (name) => `新任务 ${name}`, revisionStartedTitle: '已创建修改版草稿', revisionStartedDescription: '原任务仍会保留;发送后将在新版本中继续', revisionReadyTitle: '可以修改并重发了', revisionReadyDescription: '已回到该消息之前;可直接重发或修改后发送', re [...]
+    actions: { stopFailedTitle: '停止失败', stopFailedFallback: '任务操作失败,请稍后重试。', refreshSessionsFailedTitle: '刷新任务列表失败', refreshSessionsFailedFallback: '刷新任务列表失败,请稍后重试。', conversationErrorTitle: '任务出错', conversationErrorFallback: '任务运行失败,请稍后重试。', branchCreatedTitle: '已创建分支', branchCreatedDescription: (name) => `新任务 ${name}`, revisionStartedTitle: '已创建修改版草稿', revisionStartedDescription: '原任务仍会保留;发送后将在新版本中继续', revisionReadyTitle: '可以修改并重发了', revisionReadyDescription: '已回到该消息之前;可直接重发或修改后发送', re [...]
     model: {
       fakeBackendLabel: '本地模拟连接',
       setupTitle: '等待配置真实模型',
@@ -592,7 +594,7 @@ const COPY = {
     turnError: { streamTruncated: '响应中途断开。', requestRejected: '模型服务拒绝了请求,请检查模型与请求配置。', retryExhausted: '已达到自动重试次数上限。', retryDeclined: { side_effects: '本次已有工具活动,为避免重复操作,未自动重试。请先检查工具结果。', observable_output: '本次已有部分输出,未自动重试。请先检查已保留的内容。', policy: '按当前重试规则,本次未自动重试。', budget: '本次执行预算已用尽,未自动重试。' }, unknown: '出错了,暂时无法确定原因。', contextOverflow: '上下文超出模型窗口限制,减少附件或开启新任务。', timeout: '模型请求超时。', auth: '模型鉴权失败,请到设置里重新连接或登录。', providerBilling: '模型服务计费受限,请检查账号余额或订阅状态。', providerCapacity: '模型服务暂时满载。', rateL [...]
   },
   'zh-TW': {
-    actions: { stopFailedTitle: '停止失敗', stopFailedFallback: '任務操作失敗,請稍後重試。', refreshSessionsFailedTitle: '重新整理任務列表失敗', refreshSessionsFailedFallback: '重新整理任務列表失敗,請稍後重試。', conversationErrorTitle: '任務出錯', conversationErrorFallback: '任務執行失敗,請稍後重試。', branchCreatedTitle: '已建立分支', branchCreatedDescription: (name) => `新任務 ${name}`, revisionStartedTitle: '已建立修改版草稿', revisionStartedDescription: '原任務仍會保留;傳送後將在新版本中繼續', revisionReadyTitle: '可以修改並重發了', revisionReadyDescription: '已回到該訊息之前;可直接重發或修改後傳送' [...]
+    actions: { stopFailedTitle: '停止失敗', stopFailedFallback: '任務操作失敗,請稍後重試。', refreshSessionsFailedTitle: '重新整理任務列表失敗', refreshSessionsFailedFallback: '重新整理任務列表失敗,請稍後重試。', conversationErrorTitle: '任務出錯', conversationErrorFallback: '任務執行失敗,請稍後重試。', branchCreatedTitle: '已建立分支', branchCreatedDescription: (name) => `新任務 ${name}`, revisionStartedTitle: '已建立修改版草稿', revisionStartedDescription: '原任務仍會保留;傳送後將在新版本中繼續', revisionReadyTitle: '可以修改並重發了', revisionReadyDescription: '已回到該訊息之前;可直接重發或修改後傳送' [...]
     model: {
       fakeBackendLabel: '本地模擬連線',
       setupTitle: '等待設定真實模型',
@@ -833,7 +835,7 @@ const COPY = {
     turnError: { streamTruncated: '回應中途斷開。', requestRejected: '模型服務拒絕了請求,請檢查模型與請求設定。', retryExhausted: '已達到自動重試次數上限。', retryDeclined: { side_effects: '本次已有工具活動,為避免重複操作,未自動重試。請先檢查工具結果。', observable_output: '本次已有部分輸出,未自動重試。請先檢查已保留的內容。', policy: '依目前重試規則,本次未自動重試。', budget: '本次執行預算已用盡,未自動重試。' }, unknown: '出錯了,暫時無法確定原因。', contextOverflow: '上下文超出模型視窗限制,減少附件或開啟新任務。', timeout: '模型請求逾時。', auth: '模型鑑權失敗,請到設定裡重新連線或登入。', providerBilling: '模型服務計費受限,請檢查帳號餘額或訂閱狀態。', providerCapacity: '模型服務暫時滿載。', rateL [...]
   },
   en: {
-    actions: { stopFailedTitle: 'Failed to stop', stopFailedFallback: 'The task action failed. Try again later.', refreshSessionsFailedTitle: 'Failed to refresh tasks', refreshSessionsFailedFallback: 'The task list could not be refreshed. Try again later.', conversationErrorTitle: 'Task error', conversationErrorFallback: 'The task run failed. Try again later.', branchCreatedTitle: 'Branch created', branchCreatedDescription: (name) => `New task: ${name}`, revisionStartedTitle: 'Edit draft [...]
+    actions: { stopFailedTitle: 'Failed to stop', stopFailedFallback: 'The task action failed. Try again later.', refreshSessionsFailedTitle: 'Failed to refresh tasks', refreshSessionsFailedFallback: 'The task list could not be refreshed. Try again later.', conversationErrorTitle: 'Task error', conversationErrorFallback: 'The task run failed. Try again later.', branchCreatedTitle: 'Branch created', branchCreatedDescription: (name) => `New task: ${name}`, revisionStartedTitle: 'Edit draft [...]
     model: {
       fakeBackendLabel: 'Local simulation',
       setupTitle: 'Configure a real model',
diff --git a/apps/desktop/src/renderer/features/conversation/controller/composer-staging-commands.ts b/apps/desktop/src/renderer/features/conversation/controller/composer-staging-commands.ts
index dda092bdd6..9cf48f062e 100644
--- a/apps/desktop/src/renderer/features/conversation/controller/composer-staging-commands.ts
+++ b/apps/desktop/src/renderer/features/conversation/controller/composer-staging-commands.ts
@@ -28,6 +28,7 @@ export function createComposerStagingCommands(): ComposerStagingCommands {
   };
   const commands: ComposerStagingCommands = {
     captureSubmission: () => requireOwner().captureSubmission(),
+    stagedContext: () => requireOwner().stagedContext(),
     addQuote: (quote) => requireOwner().addQuote(quote),
     resetImageNotice: (key) => requireOwner().resetImageNotice(key),
     transferImageNotice: (from, to) => requireOwner().transferImageNotice(from, to),
diff --git a/apps/desktop/src/renderer/features/conversation/controller/composer-submit.ts b/apps/desktop/src/renderer/features/conversation/controller/composer-submit.ts
index f26988ef18..ffd95ad2d5 100644
--- a/apps/desktop/src/renderer/features/conversation/controller/composer-submit.ts
+++ b/apps/desktop/src/renderer/features/conversation/controller/composer-submit.ts
@@ -224,14 +224,12 @@ export async function revisionAwareSend<TDraft extends RevisionDraftIdentity>(
   }
   if (revisionSend && revision) {
     const actionCopy = ports.revisionUnavailableCopy;
-    if (staging.hasPendingContext) {
-      ports.toastApi.info(actionCopy.revisionUnavailableTitle, actionCopy.revisionAttachmentsUnsupported);
-      return false;
-    }
     if (slashCommand) {
       ports.toastApi.info(actionCopy.revisionUnavailableTitle, actionCopy.revisionCommandUnsupported);
       return false;
     }
+    // The attachments / mixed-context refusals live inside the revision
+    // lifecycle (prepareRevisionSend), which toasts and stops the send.
     if (!(await ports.prepareRevisionSend(text))) return false;
   }
   if (slashCommand?.kind === 'compact') {
@@ -363,7 +361,12 @@ export async function revisionAwareSend<TDraft extends RevisionDraftIdentity>(
   const expectedRevisionDraft = revisionSend
     ? ports.revisionDraftRef.current
     : undefined;
-  const quotes = staging.quotesForSend();
+  // The re-key lands the plate's current quotes on the branch child before
+  // this send, while this invocation's captured submission still holds the
+  // source bucket's snapshot — read the re-keyed owner explicitly so the
+  // replacement carries exactly what the user staged, edits included
+  // (#5274 review).
+  const quotes = staging.quotesForSend(expectedRevisionDraft?.draftSessionId);
   const ok = await ports.send(text, pending, {
     waitForHostAdmission: revisionSend,
     targetSessionId: expectedRevisionDraft?.draftSessionId,
@@ -376,7 +379,9 @@ export async function revisionAwareSend<TDraft extends RevisionDraftIdentity>(
   });
   if (ok !== false) {
     staging.clearSubmittedContext(pending);
-    if (quotes) staging.clearQuotes();
+    // A revision's quotes now live under the branch child's bucket; clear
+    // that owner explicitly rather than the snapshot the submission captured.
+    if (quotes) staging.clearQuotes(expectedRevisionDraft?.draftSessionId);
     ports.settleNewTaskImageNoticeOwner(sessionId);
     if (sessionId) delete ports.retractedWorkspaceReferencesRef.current[sessionId];
   }
diff --git a/apps/desktop/src/renderer/features/conversation/controller/revision-actions.ts b/apps/desktop/src/renderer/features/conversation/controller/revision-actions.ts
index 009f9b075f..6dc27c22b7 100644
--- a/apps/desktop/src/renderer/features/conversation/controller/revision-actions.ts
+++ b/apps/desktop/src/renderer/features/conversation/controller/revision-actions.ts
@@ -19,23 +19,20 @@
 
 import type { StoredMessage } from '@maka/core/session';
 import type { UiLocale } from '@maka/core/ui-locale';
-import { userFacingText } from '@maka/core/session';
 import type { ComposerHandle } from '@maka/ui';
+import {
+  createRevisionActions as createStagedRevisionActions,
+  type TurnRevisionDraftBase,
+} from '@maka/ui';
 import { getDesktopConversationCopy } from '../../../application/contracts/conversation-copy.js';
-import { getShellCopy, localizedShellErrorMessage } from '../../../locales/shell-copy.js';
+import * as sessionCopyAttempts from '../../../application/contracts/session-copy-attempt.js';
 import {
   isSessionWorkspaceUnavailableError,
   showSessionWorkspaceUnavailableToast,
 } from '../../../application/contracts/session-workspace-errors.js';
+import { getShellCopy, localizedShellErrorMessage } from '../../../locales/shell-copy.js';
 import type { ComposerSubmissionServices } from '../submission-services.js';
-import {
-  acquireSessionCopyAttempt,
-  abandonSessionCopyAttempt,
-  completeSessionCopyAttempt,
-  startSessionCopyAttempt,
-  type SessionCopyAttemptPhase,
-  type SessionCopyAttemptKey,
-} from '../../../application/contracts/session-copy-attempt.js';
+import type { ComposerStagingCommands } from '../model/composer-staging-contract.js';
 
 type ReadonlyRef<T> = { readonly current: T };
 
@@ -49,18 +46,11 @@ type ToastApi = {
   ): void;
 };
 
-/** Active edit-and-resend draft, owned by the Composer submission owner. */
-export type TurnRevisionDraft = {
-  sourceSessionId: string;
-  sourceTurnId: string;
-  copyId: string;
-  copyPhase: SessionCopyAttemptPhase;
-  /** Active owner of the draft. Changes to the branch child after prepare. */
-  draftSessionId: string;
-  /** Composer text that was present before edit began; restored on cancel.
-   *  Staged Skills ride along inside it as `/skill:<id>` chips. */
-  previousComposerText: string;
-};
+/**
+ * The desktop revision draft: the shared lifecycle's draft extended with the
+ * staged-context snapshot the edit restages into the composer plates (#5109).
+ */
+export type TurnRevisionDraft = TurnRevisionDraftBase<string>;
 
 export interface RevisionActions {
   beginEditUserMessage(turnId: string): void;
@@ -78,10 +68,10 @@ export interface RevisionActions {
  *
  * If normal send fails after a revision was prepared, that version remains
  * active with the edited text and a second send retries there instead of
- * creating another version. Attachment-bearing source messages are rejected
- * until the revision draft can carry their target-owned references (#5109);
- * retained historical attachments are fine — the Host revision copier
- * rewrites their Session refs losslessly.
+ * creating another version. The lifecycle itself lives in `@maka/ui`; this
+ * assembler injects the submission services, the locale catalog, and the
+ * copy-attempt tracker, and derives both the pending-context probe and the
+ * live plate reads from the shell's one persistent staging handle.
  */
 export function createRevisionActions(deps: {
   services: Pick<ComposerSubmissionServices, 'reviseBeforeTurn' | 'abandonSessionCopy'>;
@@ -90,297 +80,73 @@ export function createRevisionActions(deps: {
   captureSelection(): () => boolean;
   composerRef: ReadonlyRef<ComposerHandle | null>;
   readMessages(): readonly StoredMessage[];
-  hasPendingAttachments: () => boolean;
-  openSessionInChat: (sessionId: string, turnId?: string) => void;
-  refreshSessions: () => Promise<unknown>;
-  commitRevisionDraft: (draft: TurnRevisionDraft | null) => void;
+  /** The persistent staging owner: the gate's pending-context probe and the
+   *  lifecycle's live plate reads both derive from this one handle. */
+  staging: ComposerStagingCommands;
+  openSessionInChat(sessionId: string, turnId?: string): void;
+  refreshSessions(): Promise<unknown>;
+  commitRevisionDraft(draft: TurnRevisionDraft | null): void;
   revisionDraftRef: ReadonlyRef<TurnRevisionDraft | null>;
   toastApi: ToastApi;
 }): RevisionActions {
-  const {
-    services,
-    uiLocale,
-    activeIdRef,
-    captureSelection,
-    composerRef,
-    readMessages,
-    hasPendingAttachments,
-    openSessionInChat,
-    refreshSessions,
-    commitRevisionDraft,
-    revisionDraftRef,
-    toastApi,
-  } = deps;
-  const copy = getDesktopConversationCopy(uiLocale).actions;
-
-  function revisionCopyKey(sourceSessionId: string, sourceTurnId: string): SessionCopyAttemptKey {
-    return {
-      scope: `edit-and-resend:${sourceTurnId}`,
-      kind: 'revision',
-      sourceSessionId,
-    };
-  }
-
-  function beginEditUserMessage(turnId: string): void {
-    const sessionId = activeIdRef.current;
-    if (!sessionId) return;
-    const existing = revisionDraftRef.current;
-    if (existing) {
-      if (existing.draftSessionId === sessionId && existing.sourceTurnId === turnId) {
-        composerRef.current?.focus();
-      } else {
-        toastApi.info(copy.revisionUnavailableTitle, copy.revisionAlreadyActive);
-      }
-      return;
-    }
-    if (hasPendingAttachments()) {
-      toastApi.info(copy.revisionUnavailableTitle, copy.revisionDraftAttachmentConflict);
-      return;
-    }
-    const userMessage = readMessages().find(
-      (message): message is Extract<StoredMessage, { type: 'user' }> =>
-        message.type === 'user' && message.turnId === turnId,
-    );
-    if (!userMessage) {
-      toastApi.error(
-        copy.operationFailedTitle,
-        copy.operationFailedFallback,
-        undefined,
-        { sessionId },
-      );
-      return;
-    }
-
-    if (userMessage.attachments && userMessage.attachments.length > 0) {
-      // Attachment references are session-owned and their rewritten targets
-      // are not exposed to clients yet, so those stay explicitly rejected.
-      // Quotes never reach this point: chat-turn's editDisabled gate excludes them.
-      toastApi.info(copy.revisionUnavailableTitle, copy.revisionAttachmentsUnsupported);
-      return;
-    }
-    if (userMessage.displayText !== undefined && userMessage.displayText !== userMessage.text) {
-      toastApi.info(copy.revisionUnavailableTitle, copy.revisionTransformedTextUnsupported);
-      return;
-    }
-
-    const prompt = userFacingText(userMessage);
-    const copyAttempt = acquireSessionCopyAttempt(
-      revisionCopyKey(sessionId, turnId),
-      turnId,
-    );
-    commitRevisionDraft({
-      sourceSessionId: sessionId,
-      sourceTurnId: copyAttempt.sourceTurnId,
-      copyId: copyAttempt.copyId,
-      copyPhase: copyAttempt.phase,
-      draftSessionId: sessionId,
-      previousComposerText: composerRef.current?.getText() ?? '',
-    });
-    composerRef.current?.setText(prompt);
-    composerRef.current?.focus();
-    toastApi.info(copy.revisionStartedTitle, copy.revisionStartedDescription);
-  }
-
-  async function rollbackPreparedRevision(
-    draft: TurnRevisionDraft,
-    revisionSessionId: string,
-    text: string,
-    selectionIsCurrent: () => boolean,
-  ): Promise<void> {
-    composerRef.current?.clearDraft(revisionSessionId);
-    const current = revisionDraftRef.current;
-    if (selectionIsCurrent() && activeIdRef.current === revisionSessionId) {
-      openSessionInChat(draft.sourceSessionId);
-      selectionIsCurrent = captureSelection();
-    }
-    const abandonment = await abandonRevisionCopy(draft);
-    const abandoningDraft = abandonment.draft;
-    let restored: TurnRevisionDraft | undefined;
-    if (current?.copyId === draft.copyId && revisionDraftRef.current === abandoningDraft) {
-      if (abandonment.acknowledged) {
-        const nextAttempt = acquireSessionCopyAttempt(
-          revisionCopyKey(draft.sourceSessionId, draft.sourceTurnId),
-          draft.sourceTurnId,
-        );
-        restored = {
-          ...draft,
-          sourceTurnId: nextAttempt.sourceTurnId,
-          copyId: nextAttempt.copyId,
-          copyPhase: nextAttempt.phase,
-          draftSessionId: draft.sourceSessionId,
-        };
-      } else {
-        restored = { ...abandoningDraft, draftSessionId: draft.sourceSessionId };
-      }
-      composerRef.current?.setDraft(draft.sourceSessionId, text);
-      commitRevisionDraft(restored);
-    }
-    if (selectionIsCurrent() && activeIdRef.current === draft.sourceSessionId && revisionDraftRef.current === restored) {
-      composerRef.current?.setText(text);
-      composerRef.current?.focus();
-    }
-    await refreshSessions().catch(() => []);
-  }
-
-  async function abandonRevisionCopy(
-    draft: TurnRevisionDraft,
-  ): Promise<{ acknowledged: boolean; draft: TurnRevisionDraft }> {
-    const tracked = abandonSessionCopyAttempt(
-      revisionCopyKey(draft.sourceSessionId, draft.sourceTurnId),
-      draft.copyId,
-    );
-    const current = revisionDraftRef.current;
-    const trackedDraft = current?.copyId === draft.copyId ? current : draft;
-    const abandoningDraft =
-      tracked && trackedDraft.copyPhase !== 'abandoning'
-        ? { ...trackedDraft, copyPhase: 'abandoning' as const }
-        : trackedDraft;
-    if (revisionDraftRef.current === trackedDraft && abandoningDraft !== trackedDraft) {
-      commitRevisionDraft(abandoningDraft);
-    }
-    try {
-      // Main acknowledges only after the cleanup intent is durable; physical
-      // removal may finish after this renderer has closed the draft.
-      await services.abandonSessionCopy(draft.sourceSessionId, draft.copyId);
-      completeTurnRevisionCopyAttempt(draft);
-      return { acknowledged: true, draft: abandoningDraft };
-    } catch {
-      // An ambiguous cleanup acknowledgement stays in `abandoning`; this
-      // target may only retry cleanup and can never be copied into again.
-      return { acknowledged: false, draft: abandoningDraft };
-    }
-  }
-
-  async function prepareRevisionSend(text: string): Promise<boolean> {
-    let selectionIsCurrent = captureSelection();
-    let draft = revisionDraftRef.current;
-    if (!draft || activeIdRef.current !== draft.draftSessionId) return false;
-    // A previous attempt already prepared the version; retry normal send there.
-    if (draft.draftSessionId !== draft.sourceSessionId) return true;
-
-    if (draft.copyPhase === 'abandoning') {
-      const abandonment = await abandonRevisionCopy(draft);
-      if (
-        !selectionIsCurrent() || !abandonment.acknowledged ||
-        revisionDraftRef.current !== abandonment.draft ||
-        activeIdRef.current !== draft.sourceSessionId
-      ) {
-        return false;
-      }
-      const nextAttempt = acquireSessionCopyAttempt(
-        revisionCopyKey(draft.sourceSessionId, draft.sourceTurnId),
-        draft.sourceTurnId,
-      );
-      draft = {
-        ...draft,
-        copyId: nextAttempt.copyId,
-        copyPhase: nextAttempt.phase,
-      };
-      commitRevisionDraft(draft);
-    }
-
-    const startedDraft =
-      draft.copyPhase === 'started' ? draft : { ...draft, copyPhase: 'started' as const };
-    if (startedDraft !== draft) {
-      if (
-        !startSessionCopyAttempt(
-          revisionCopyKey(draft.sourceSessionId, draft.sourceTurnId),
-          draft.copyId,
-        )
-      ) {
-        return false;
-      }
-      commitRevisionDraft(startedDraft);
-    }
-    const sourceSessionId = startedDraft.sourceSessionId;
-    let preparedSessionId: string | undefined;
-    try {
-      const newSession = await services.reviseBeforeTurn(sourceSessionId, {
-        sourceTurnId: startedDraft.sourceTurnId,
-        copyId: startedDraft.copyId,
+  const actions = createStagedRevisionActions<string, TurnRevisionDraft>({
+    uiLocale: deps.uiLocale,
+    activeIdRef: deps.activeIdRef,
+    captureSelection: deps.captureSelection,
+    composerRef: deps.composerRef,
+    readMessages: deps.readMessages,
+    hasPendingAttachments: () => deps.staging.captureSubmission().hasPendingContext,
+    stagedContext: deps.staging.stagedContext,
+    openSessionInChat: deps.openSessionInChat,
+    refreshSessions: async () => {
+      await deps.refreshSessions();
+      return [];
+    },
+    commitRevisionDraft: deps.commitRevisionDraft,
+    revisionDraftRef: deps.revisionDraftRef,
+    toastApi: deps.toastApi,
+    copy: getDesktopConversationCopy(deps.uiLocale).actions,
+    reviseBeforeTurn: (sourceSessionId, input) =>
+      deps.services.reviseBeforeTurn(sourceSessionId, input),
+    abandonSessionCopy: (sourceSessionId, copyId) =>
+      deps.services.abandonSessionCopy(sourceSessionId, copyId),
+    localizedShellErrorMessage: (error, fallback, locale) =>
+      localizedShellErrorMessage(error, fallback, locale),
+    reportSessionWorkspaceUnavailable: (error, sessionId) => {
+      if (!isSessionWorkspaceUnavailableError(error)) return false;
+      showSessionWorkspaceUnavailableToast(deps.toastApi, getShellCopy(deps.uiLocale).errors, {
+        sessionId,
       });
-      preparedSessionId = newSession.id;
-      if (!selectionIsCurrent() || revisionDraftRef.current !== startedDraft) {
-        await rollbackPreparedRevision(startedDraft, newSession.id, text, selectionIsCurrent);
-        return false;
-      }
-
-      const prepared = { ...startedDraft, draftSessionId: newSession.id };
-      composerRef.current?.setDraft(newSession.id, text);
-      commitRevisionDraft(prepared);
-      openSessionInChat(newSession.id);
-      selectionIsCurrent = captureSelection();
-      await refreshSessions();
-      if (!selectionIsCurrent() || revisionDraftRef.current !== prepared) {
-        await rollbackPreparedRevision(startedDraft, newSession.id, text, selectionIsCurrent);
-        return false;
-      }
-      composerRef.current?.focus();
-      toastApi.info(copy.revisionReadyTitle, copy.revisionReadyDescription);
       return true;
-    } catch (error) {
-      // Rollback itself navigates back to the source Session, so the failure
-      // must be surfaced before it runs — checking after it is always stale.
-      if (selectionIsCurrent()) {
-        if (isSessionWorkspaceUnavailableError(error)) {
-          showSessionWorkspaceUnavailableToast(toastApi, getShellCopy(uiLocale).errors, {
-            sessionId: sourceSessionId,
-          });
-        } else {
-          toastApi.error(
-            copy.operationFailedTitle,
-            localizedShellErrorMessage(error, copy.operationFailedFallback, uiLocale),
-            undefined,
-            { sessionId: sourceSessionId },
-          );
-        }
-      }
-      if (preparedSessionId) {
-        await rollbackPreparedRevision(startedDraft, preparedSessionId, text, selectionIsCurrent);
-      }
-      return false;
-    }
-  }
-
-  async function cancelRevisionDraft() {
-    let selectionIsCurrent = captureSelection();
-    const draft = revisionDraftRef.current;
-    if (!draft) return;
-    const cleanupSessionId = draft.copyPhase !== 'reserved'
-      ? draft.draftSessionId !== draft.sourceSessionId
-        ? draft.draftSessionId
-        : draft.copyId
-      : undefined;
-    if (cleanupSessionId) await abandonRevisionCopy(draft);
-    else completeTurnRevisionCopyAttempt(draft);
-    commitRevisionDraft(null);
-    composerRef.current?.setDraft(draft.sourceSessionId, draft.previousComposerText);
-    if (draft.draftSessionId !== draft.sourceSessionId) {
-      composerRef.current?.clearDraft(draft.draftSessionId);
-    }
-    if (selectionIsCurrent() && activeIdRef.current !== draft.sourceSessionId) {
-      openSessionInChat(draft.sourceSessionId);
-      selectionIsCurrent = captureSelection();
-    }
-    if (cleanupSessionId) {
-      await refreshSessions().catch(() => []);
-    }
-    if (selectionIsCurrent() && activeIdRef.current === draft.sourceSessionId) {
-      composerRef.current?.setText(draft.previousComposerText);
-      composerRef.current?.focus();
-    }
-  }
-
-  return { beginEditUserMessage, prepareRevisionSend, cancelRevisionDraft };
+    },
+    acquireCopyAttempt: (key, turnId) =>
+      sessionCopyAttempts.acquireSessionCopyAttempt(key as never, turnId),
+    startCopyAttempt: (key, copyId) =>
+      sessionCopyAttempts.startSessionCopyAttempt(key as never, copyId),
+    abandonCopyAttempt: (key, copyId) =>
+      sessionCopyAttempts.abandonSessionCopyAttempt(key as never, copyId),
+    completeCopyAttempt: (key, copyId) =>
+      sessionCopyAttempts.completeSessionCopyAttempt(key as never, copyId),
+  });
+  return {
+    beginEditUserMessage: actions.beginEditUserMessage,
+    prepareRevisionSend: actions.prepareRevisionSend,
+    cancelRevisionDraft: actions.cancelRevisionDraft,
+  };
 }
 
+/**
+ * Module-level copy-attempt bookkeeping a send needs beside the lifecycle:
+ * completion on send, and abandonment with the same ambiguous-acknowledgement
+ * contract the lifecycle above uses.
+ */
 export function completeTurnRevisionCopyAttempt(draft: TurnRevisionDraft): void {
-  completeSessionCopyAttempt(
+  sessionCopyAttempts.completeSessionCopyAttempt(
     {
       scope: `edit-and-resend:${draft.sourceTurnId}`,
       kind: 'revision',
       sourceSessionId: draft.sourceSessionId,
-    },
+    } as never,
     draft.copyId,
   );
 }
@@ -389,15 +155,15 @@ export async function abandonTurnRevisionCopyAttempt(
   services: Pick<ComposerSubmissionServices, 'abandonSessionCopy'>,
   draft: TurnRevisionDraft,
 ): Promise<boolean> {
-  const key: SessionCopyAttemptKey = {
+  const key = {
     scope: `edit-and-resend:${draft.sourceTurnId}`,
     kind: 'revision',
     sourceSessionId: draft.sourceSessionId,
-  };
-  abandonSessionCopyAttempt(key, draft.copyId);
+  } as never;
+  sessionCopyAttempts.abandonSessionCopyAttempt(key, draft.copyId);
   try {
     await services.abandonSessionCopy(draft.sourceSessionId, draft.copyId);
-    completeSessionCopyAttempt(key, draft.copyId);
+    sessionCopyAttempts.completeSessionCopyAttempt(key, draft.copyId);
     return true;
   } catch {
     return false;
diff --git a/apps/desktop/src/renderer/features/conversation/controller/use-composer-attachments.ts b/apps/desktop/src/renderer/features/conversation/controller/use-composer-attachments.ts
index fdbe63da5d..4eea57376b 100644
--- a/apps/desktop/src/renderer/features/conversation/controller/use-composer-attachments.ts
+++ b/apps/desktop/src/renderer/features/conversation/controller/use-composer-attachments.ts
@@ -17,7 +17,7 @@
  * under the License.
  */
 
-import { useUiLocale } from '@maka/ui';
+import { useUiLocale, type RevisionStagedContext } from '@maka/ui';
 import { useComposerAttachments as useSharedComposerAttachments } from '@maka/ui/use-composer-attachments';
 import { getDesktopConversationCopy } from '../../../application/contracts/conversation-copy.js';
 import { localizedShellErrorMessage } from '../../../locales/shell-copy.js';
@@ -34,5 +34,14 @@ export function useComposerAttachments(options: Omit<Parameters<typeof useShared
     formatError: (error, fallback) => localizedShellErrorMessage(error, fallback, locale),
   });
   const quotes = useComposerQuotes({ draftKey: options.draftKey });
-  return { ...attachments, ...quotes };
+  // The revision lifecycle reads its staged plates through this getter (see
+  // RevisionStagedContext). It is assembled here, beside the hooks that own
+  // the buckets, so the frozen shell only forwards one member.
+  const stagedContext = (): RevisionStagedContext => ({
+    quotes: quotes.pendingQuotes,
+    attachments: attachments.submittableAttachments ?? [],
+    restoreQuotes: quotes.restoreQuotes,
+    clearQuotes: quotes.clearQuotes,
+  });
+  return { ...attachments, ...quotes, stagedContext };
 }
diff --git a/apps/desktop/src/renderer/features/conversation/controller/use-composer-quotes.ts b/apps/desktop/src/renderer/features/conversation/controller/use-composer-quotes.ts
index 5fd8bf6b9d..b494e4cdc1 100644
--- a/apps/desktop/src/renderer/features/conversation/controller/use-composer-quotes.ts
+++ b/apps/desktop/src/renderer/features/conversation/controller/use-composer-quotes.ts
@@ -78,18 +78,22 @@ export function useComposerQuotes(options: { readonly draftKey: string }) {
     publish();
   }, [bucket, publish]);
 
-  const clearQuotes = useCallback((): void => {
-    bucket.splice(0, bucket.length);
+  // An explicit owner key clears another draft's bucket — the revision
+  // lifecycle re-keys its restored quotes across the commit and clears both
+  // the source and the branch-child keys (#5109 review); the live draft is
+  // the default for composer flows. The removed entries come back so the
+  // cancel path can re-stage the ones the edit did not stage itself
+  // (#5274 review).
+  const clearQuotes = useCallback((ownerKey = options.draftKey): QuoteRef[] => {
+    const target = pendingByKeyRef.current[ownerKey];
+    const removed = target ? target.splice(0, target.length) : [];
     publish();
-  }, [bucket, publish]);
-
-  const clearSubmittedQuotes = useCallback((submitted: readonly QuoteRef[]): void => {
-    for (let index = bucket.length - 1; index >= 0; index -= 1) {
-      if (submitted.includes(bucket[index]!)) bucket.splice(index, 1);
-    }
-    publish();
-  }, [bucket, publish]);
+    return removed;
+  }, [options.draftKey, publish]);
 
+  // The revision lifecycle re-keys the selected message's quotes onto the
+  // branch child after the copy commits; restoring them into the owner's
+  // bucket copies the refs so the plate never aliases the read model.
   const restoreQuotes = useCallback((ownerKey: string, quotes: readonly QuoteRef[]): void => {
     if (quotes.length === 0) return;
     const ownerBucket = pendingByKeyRef.current[ownerKey] ??
@@ -98,14 +102,31 @@ export function useComposerQuotes(options: { readonly draftKey: string }) {
     publish();
   }, [publish]);
 
+  // A captured submission clears exactly the entries it sent (#5868); the
+  // revision lifecycle's owner-keyed clearing lives in clearQuotes above.
+  const clearSubmittedQuotes = useCallback((submitted: readonly QuoteRef[]): void => {
+    for (let index = bucket.length - 1; index >= 0; index -= 1) {
+      if (submitted.includes(bucket[index]!)) bucket.splice(index, 1);
+    }
+    publish();
+  }, [bucket, publish]);
+
+
   // The composer's token asks the transcript to open the note editor over the
   // excerpt; a synchronous false means it falls back to its own popover.
   const chatViewRef = useRef<ChatViewHandle>(null);
   const tryAnnotateQuote = (index: number): boolean =>
     chatViewRef.current?.openQuoteAnnotation(index) ?? false;
 
-  const quotesForSend = (): QuoteRef[] | undefined =>
-    bucket.length ? bucket : undefined;
+  // An in-flight send must not be bound to the render that started it: the
+  // revision lifecycle re-keys the plate onto the branch child mid-send and
+  // empties the source bucket in place (#5274 review), so the resumed send
+  // reads through the re-keyed owner key. The ref is stable across renders
+  // and buckets are mutated in place, never replaced.
+  const quotesForSend = (ownerKey = options.draftKey): QuoteRef[] | undefined => {
+    const target = pendingByKeyRef.current[ownerKey];
+    return target?.length ? target : undefined;
+  };
 
   return {
     pendingQuotes: bucket,
diff --git a/apps/desktop/src/renderer/features/conversation/controller/use-composer-submission.ts b/apps/desktop/src/renderer/features/conversation/controller/use-composer-submission.ts
index 72174df642..32921f51dd 100644
--- a/apps/desktop/src/renderer/features/conversation/controller/use-composer-submission.ts
+++ b/apps/desktop/src/renderer/features/conversation/controller/use-composer-submission.ts
@@ -153,7 +153,9 @@ export function useComposerSubmission<Owner extends ComposerSurfaceOwner>(input:
     captureSelection: commands.captureSelection,
     composerRef,
     readMessages: commands.readMessages,
-    hasPendingAttachments: () => staging.captureSubmission().hasPendingContext,
+    // The lifecycle derives both its pending-context probe and its live plate
+    // reads from this one staging handle (#5109).
+    staging,
     openSessionInChat: shell.openSession,
     refreshSessions: shell.refreshSessions,
     commitRevisionDraft,
diff --git a/apps/desktop/src/renderer/features/conversation/model/composer-staging-contract.ts b/apps/desktop/src/renderer/features/conversation/model/composer-staging-contract.ts
index 3447607ac7..de4d68417a 100644
--- a/apps/desktop/src/renderer/features/conversation/model/composer-staging-contract.ts
+++ b/apps/desktop/src/renderer/features/conversation/model/composer-staging-contract.ts
@@ -19,6 +19,7 @@
 
 import type { DirectoryReference, QuoteRef } from '@maka/core/events';
 import type { PendingAttachment } from '@maka/ui/composer-attachments';
+import type { RevisionStagedContext } from '@maka/ui';
 import type { RestoredDraftContent } from '../../../application/contracts/transient-message-projection.js';
 
 /** A submission owns the staging it captured, even after navigation or another edit. */
@@ -28,14 +29,25 @@ export interface ComposerStagingSubmission {
   readonly hasStagedQuotes: boolean;
   readonly submittableAttachments: readonly PendingAttachment[] | undefined;
   readonly directoryOptions: { readonly directoryReferences?: readonly DirectoryReference[] };
-  quotesForSend(): QuoteRef[] | undefined;
+  /** Without an owner key this answers from the captured snapshot; the
+   *  revision send passes the branch child's key because the lifecycle
+   *  re-keys the plate mid-send and empties the source bucket, so the
+   *  resumed send must read the live plate through the new owner
+   *  (#5274 review). */
+  quotesForSend(ownerKey?: string): QuoteRef[] | undefined;
   clearSubmittedContext(submitted?: readonly PendingAttachment[]): void;
-  clearQuotes(): void;
+  /** Without an owner key this removes exactly the captured entries; an
+   *  explicit owner key clears that owner's whole live plate (the revision
+   *  path clears the branch child the lifecycle re-keyed the quotes onto). */
+  clearQuotes(ownerKey?: string): void;
 }
 
 /** Commands only: there is deliberately no subscription or controller getter. */
 export interface ComposerStagingCommands {
   captureSubmission(): ComposerStagingSubmission;
+  /** Live plate reads for the revision lifecycle, assembled beside the hooks
+   *  that own the buckets (see RevisionStagedContext). */
+  stagedContext(): RevisionStagedContext;
   addQuote(input: {
     text: string;
     turnId?: string;
diff --git a/apps/desktop/src/renderer/features/conversation/ui/composer-staging-provider.tsx b/apps/desktop/src/renderer/features/conversation/ui/composer-staging-provider.tsx
index a234a64c36..e222e74835 100644
--- a/apps/desktop/src/renderer/features/conversation/ui/composer-staging-provider.tsx
+++ b/apps/desktop/src/renderer/features/conversation/ui/composer-staging-provider.tsx
@@ -56,11 +56,19 @@ export function ComposerStagingProvider(props: {
           hasStagedQuotes: Boolean(quotes?.length),
           submittableAttachments: staging.submittableAttachments,
           directoryOptions: staging.directoryOptions,
-          quotesForSend: () => quotes,
+          // An explicit owner key reads the live plate — the revision send
+          // passes the branch child the lifecycle re-keyed the quotes onto
+          // mid-send (#5274 review); without one the snapshot answers.
+          quotesForSend: (ownerKey?: string) =>
+            ownerKey === undefined ? quotes : staging.quotesForSend(ownerKey),
           clearSubmittedContext: staging.clearSubmittedContext,
-          clearQuotes: () => staging.clearSubmittedQuotes(quotes ?? []),
+          clearQuotes: (ownerKey?: string) => {
+            if (ownerKey === undefined) staging.clearSubmittedQuotes(quotes ?? []);
+            else staging.clearQuotes(ownerKey);
+          },
         };
       },
+      stagedContext: staging.stagedContext,
       addQuote: staging.addQuote,
       resetImageNotice: (key) => staging.imageNoticeLifecycle.reset(key),
       transferImageNotice: (from, to) => staging.imageNoticeLifecycle.transfer(from, to),
diff --git a/packages/ui/src/__tests__/chat-turn-answer-identity.test.tsx b/packages/ui/src/__tests__/chat-turn-answer-identity.test.tsx
index f81ac17c9d..5c9a4ce7cc 100644
--- a/packages/ui/src/__tests__/chat-turn-answer-identity.test.tsx
+++ b/packages/ui/src/__tests__/chat-turn-answer-identity.test.tsx
@@ -435,6 +435,85 @@ test('does not edit and resend a message with folder references', async () => {
   assert.equal(editCalls, 0, 'folder references must not be silently dropped by revision');
 });
 
+/**
+ * Quotes and attachments restage into the revision draft (#5109): a selected
+ * user message carrying either stays editable, unlike folder references,
+ * whose Host-owned session binding has no client-side restage path.
+ */
+test('keeps an attachment-carrying message editable', async () => {
+  const { container, root } = domRoot();
+  let editCalls = 0;
+  const turn = {
+    ...turnWith([{ ...ANSWER, live: false }]),
+    status: 'completed' as const,
+    user: {
+      id: 'ask-with-image',
+      role: 'user' as const,
+      text: 'Read this chart',
+      ts: 1,
+      attachments: [
+        {
+          kind: 'image' as const,
+          name: 'chart.png',
+          mimeType: 'image/png',
+          bytes: 10,
+          ref: { kind: 'session_file' as const, sessionId: 'session-1', relativePath: 'a.png' },
+        },
+      ],
+    },
+  };
+
+  await act(() => {
+    root.render(
+      <LocaleProvider locale="en">
+        <TurnView turn={turn} onEditUserMessage={() => { editCalls += 1; }} />
+      </LocaleProvider>,
+    );
+  });
+
+  const editButton = container.querySelector('[data-action="edit"]');
+  assert.ok(editButton, 'the edit action renders');
+  assert.doesNotMatch(
+    editButton.getAttribute('aria-label') ?? '',
+    /does not yet support/,
+  );
+  await act(() => editButton.dispatchEvent(new window.Event('click', { bubbles: true })));
+  assert.equal(editCalls, 1, 'the selected message quotes and attachments restage');
+});
+
+test('keeps a quote-carrying message editable', async () => {
+  const { container, root } = domRoot();
+  let editCalls = 0;
+  const turn = {
+    ...turnWith([]),
+    status: 'completed' as const,
+    user: {
+      id: 'ask-with-quote',
+      role: 'user' as const,
+      text: 'Explain this excerpt',
+      ts: 1,
+      quotes: [{ text: 'selected excerpt', sourceTurnId: 'turn-0' }],
+    },
+  };
+
+  await act(() => {
+    root.render(
+      <LocaleProvider locale="en">
+        <TurnView turn={turn} onEditUserMessage={() => { editCalls += 1; }} />
+      </LocaleProvider>,
+    );
+  });
+
+  const editButton = container.querySelector('[data-action="edit"]');
+  assert.ok(editButton, 'the edit action renders');
+  assert.doesNotMatch(
+    editButton.getAttribute('aria-label') ?? '',
+    /does not yet support/,
+  );
+  await act(() => editButton.dispatchEvent(new window.Event('click', { bubbles: true })));
+  assert.equal(editCalls, 1, 'the selected message quotes restage into the draft');
+});
+
 /**
  * A structured-only user message (#4804) — empty inline text carrying a
  * quote — must render the quote without an empty text bubble, while keeping
diff --git a/packages/ui/src/__tests__/revision-staged-context.test.ts b/packages/ui/src/__tests__/revision-staged-context.test.ts
new file mode 100644
index 0000000000..7780f358b4
--- /dev/null
+++ b/packages/ui/src/__tests__/revision-staged-context.test.ts
@@ -0,0 +1,463 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { strict as assert } from 'node:assert/strict';
+import { describe, it } from 'node:test';
+
+import type { AttachmentRef, QuoteRef } from '@maka/core/events';
+import type { StoredMessage } from '@maka/core/session';
+import {
+  clearRevisionStagedContext,
+  createRevisionActions,
+  revisionSendGate,
+  stageRevisionSourceContext,
+  type RevisionActionsEnv,
+  type RevisionEditCopy,
+  type RevisionStagedContext,
+  type RevisionStagedSource,
+  type TurnRevisionDraftBase,
+} from '../revision-staged-context.js';
+
+const copy: RevisionEditCopy = {
+  revisionUnavailableTitle: 'unavailable',
+  revisionAttachmentsUnsupported: 'source-attachments-unsupported',
+  revisionAlreadyActive: 'already-active',
+  revisionDraftAttachmentConflict: 'draft-attachment-conflict',
+  revisionDraftQuoteConflict: 'draft-quote-conflict',
+  revisionMixedContextUnsupported: 'mixed-context-unsupported',
+  revisionTransformedTextUnsupported: 'transformed-text-unsupported',
+  revisionStartedTitle: 'started',
+  revisionStartedDescription: 'started-description',
+  revisionReadyTitle: 'ready',
+  revisionReadyDescription: 'ready-description',
+  operationFailedTitle: 'failed',
+  operationFailedFallback: 'failed-fallback',
+};
+
+function userMessage(turnId: string, text: string, extra: Record<string, unknown> = {}): StoredMessage {
+  return { id: `msg-${turnId}`, type: 'user', turnId, ts: 1, text, ...extra } as StoredMessage;
+}
+
+type StagedLog = {
+  restored: Array<{ ownerKey: string; quotes: QuoteRef[] }>;
+  cleared: string[];
+  /** The initial active Session's bucket — the plate the hooks bind to. */
+  quotes: QuoteRef[];
+  /** Per-owner buckets, so a clear only ever empties the key it names. */
+  buckets: Map<string, QuoteRef[]>;
+};
+
+function emptyStagedLog(): StagedLog {
+  const buckets = new Map<string, QuoteRef[]>();
+  const quotes: QuoteRef[] = [];
+  buckets.set('session-1', quotes);
+  return { restored: [], cleared: [], quotes, buckets };
+}
+
+function fakeStaged(log: StagedLog): RevisionStagedContext {
+  const bucketOf = (ownerKey: string): QuoteRef[] => {
+    let bucket = log.buckets.get(ownerKey);
+    if (!bucket) {
+      bucket = [];
+      log.buckets.set(ownerKey, bucket);
+    }
+    return bucket;
+  };
+  return {
+    quotes: log.quotes,
+    attachments: [],
+    restoreQuotes: (ownerKey, quotes) => {
+      if (quotes.length === 0) return;
+      log.restored.push({ ownerKey, quotes: [...quotes] });
+      bucketOf(ownerKey).push(...quotes);
+    },
+    clearQuotes: (ownerKey) => {
+      log.cleared.push(ownerKey);
+      return bucketOf(ownerKey).splice(0);
+    },
+  };
+}
+
+function createEnv(input: { messages: StoredMessage[]; staged: StagedLog }) {
+  const activeIdRef = { current: 'session-1' };
+  const revisionDraftRef: { current: TurnRevisionDraftBase<string> | null } = { current: null };
+  const toasts: Array<{ kind: 'info' | 'error'; title: string; description?: string }> = [];
+  const composer = { text: '' };
+  let attempts = 0;
+  const env: RevisionActionsEnv<string, TurnRevisionDraftBase<string>> = {
+    uiLocale: 'en' as never,
+    activeIdRef,
+    captureSelection: () => () => true,
+    composerRef: {
+      current: {
+        getText: () => composer.text,
+        setText: (text: string) => {
+          composer.text = text;
+        },
+        focus: () => {},
+        clearDraft: () => {},
+        setDraft: (_sessionId: string, text: string) => {
+          composer.text = text;
+        },
+      } as never,
+    },
+    readMessages: () => input.messages,
+    hasPendingAttachments: () => false,
+    stagedContext: () => fakeStaged(input.staged),
+    openSessionInChat: (sessionId) => {
+      activeIdRef.current = sessionId;
+    },
+    refreshSessions: async () => [],
+    commitRevisionDraft: (draft) => {
+      revisionDraftRef.current = draft;
+    },
+    revisionDraftRef,
+    toastApi: {
+      info: (title, description) => toasts.push({ kind: 'info', title, description }),
+      error: (title, description) => toasts.push({ kind: 'error', title, description }),
+    },
+    copy,
+    reviseBeforeTurn: async () => ({ id: 'session-2' }),
+    abandonSessionCopy: async () => {},
+    localizedShellErrorMessage: (_error, fallback) => fallback,
+    reportSessionWorkspaceUnavailable: () => false,
+    acquireCopyAttempt: (_key, turnId) => ({
+      sourceTurnId: turnId,
+      copyId: `copy-${++attempts}`,
+      phase: 'reserved',
+    }),
+    startCopyAttempt: () => true,
+    abandonCopyAttempt: () => true,
+    completeCopyAttempt: () => {},
+  };
+  return { env, activeIdRef, revisionDraftRef, toasts };
+}
+
+const quotedQuote: QuoteRef = { text: 'a large pasted excerpt', sourceTurnId: 'turn-0' };
+
+describe('revision lifecycle (#5109)', () => {
+  it('re-keys the restored quotes onto the branch child across the commit', async () => {
+    const staged = emptyStagedLog();
+    // The branch child transcript a revision copy really produces: the
+    // revised turn is excluded, so turn-1's message is absent and nothing in
+    // the copy rewrites it. The re-key therefore reads the draft snapshot —
+    // nothing ever consults a transcript (#5109 review).
+    const h = createEnv({
+      messages: [userMessage('turn-1', 'explain this', { quotes: [quotedQuote] })],
+      staged,
+    });
+    const actions = createRevisionActions(h.env);
+
+    actions.beginEditUserMessage('turn-1');
+    assert.deepEqual(staged.restored, [{ ownerKey: 'session-1', quotes: [quotedQuote] }]);
+
+    assert.equal(await actions.prepareRevisionSend('edited text'), true);
+    assert.deepEqual(
+      staged.restored.at(-1),
+      { ownerKey: 'session-2', quotes: [quotedQuote] },
+      'the restored quotes re-key onto the branch child',
+    );
+    assert.ok(staged.cleared.includes('session-1'), 'the source-key plate empties');
+  });
+
+  it('re-keys the plate the user edited, not the edit-start snapshot', async () => {
+    const staged = emptyStagedLog();
+    const h = createEnv({
+      messages: [
+        userMessage('turn-1', 'explain this', {
+          quotes: [quotedQuote, { text: 'second excerpt', sourceTurnId: 'turn-0' }],
+        }),
+      ],
+      staged,
+    });
+    const actions = createRevisionActions(h.env);
+
+    actions.beginEditUserMessage('turn-1');
+    // During the edit the user removes the second excerpt and re-annotates
+    // the first: the plate is the truth the replacement must carry, not the
+    // snapshot the edit started from (#5274 review).
+    staged.quotes.splice(1, 1);
+    staged.quotes[0] = { ...staged.quotes[0], comment: 'actually the other reason' };
+
+    assert.equal(await actions.prepareRevisionSend('edited text'), true);
+    assert.deepEqual(
+      staged.restored.at(-1)?.quotes,
+      [{ text: 'a large pasted excerpt', sourceTurnId: 'turn-0', comment: 'actually the other reason' }],
+      'user removals and re-annotations survive the re-key',
+    );
+  });
+
+  it('keeps the pre-gate quote snapshot equal to the child bucket the send reads', async () => {
+    // The Desktop send captures the staged payload BEFORE awaiting the
+    // revision lifecycle, because the re-key empties the source bucket the
+    // closure's array points at; the replacement send then delivers that
+    // snapshot. Whatever the gate does in between, the snapshot and the child
+    // bucket must agree — or the first replacement silently drops its quote
+    // (#5109 review, second round).
+    const staged = emptyStagedLog();
+    const h = createEnv({
+      messages: [userMessage('turn-1', 'explain this', { quotes: [quotedQuote] })],
+      staged,
+    });
+    const actions = createRevisionActions(h.env);
+
+    actions.beginEditUserMessage('turn-1');
+    const preGateSnapshot = [...(staged.restored.at(-1)?.quotes ?? [])];
+
+    assert.equal(await actions.prepareRevisionSend('edited text'), true);
+
+    assert.deepEqual(
+      staged.restored.at(-1)?.quotes,
+      preGateSnapshot,
+      'the child bucket equals the snapshot',
+    );
+  });
+
+  it('refuses to edit a message that carries attachments (#5274 review)', () => {
+    // Attachment ownership does not follow a revision copy — the copied
+    // transcript stops before the selected turn, so no target-owned refs
+    // exist client-side to restage. The edit refuses rather than silently
+    // dropping the files.
+    const h = createEnv({
+      messages: [
+        userMessage('turn-1', 'with image', {
+          attachments: [
+            {
+              kind: 'image',
+              name: 'chart.png',
+              mimeType: 'image/png',
+              bytes: 10,
+              ref: { kind: 'session_file', sessionId: 'session-1', relativePath: 'a.png' },
+            },
+          ],
+        }),
+      ],
+      staged: emptyStagedLog(),
+    });
+    const actions = createRevisionActions(h.env);
+
+    actions.beginEditUserMessage('turn-1');
+
+    assert.equal(h.revisionDraftRef.current, null, 'no draft is committed');
+    assert.deepEqual(h.toasts.at(-1), {
+      kind: 'info',
+      title: 'unavailable',
+      description: 'source-attachments-unsupported',
+    });
+  });
+
+  it('lets an unchanged replacement through (#5815)', async () => {
+    const h = createEnv({
+      messages: [userMessage('turn-1', 'explain this')],
+      staged: emptyStagedLog(),
+    });
+    const actions = createRevisionActions(h.env);
+
+    actions.beginEditUserMessage('turn-1');
+    assert.equal(await actions.prepareRevisionSend('explain this'), true);
+    assert.deepEqual(h.toasts.at(-1), {
+      kind: 'info',
+      title: 'ready',
+      description: 'ready-description',
+    });
+  });
+
+  it('blocks a replacement that mixes newly staged quotes into the edit', async () => {
+    const staged = emptyStagedLog();
+    const h = createEnv({
+      messages: [userMessage('turn-1', 'explain this')],
+      staged,
+    });
+    const actions = createRevisionActions(h.env);
+
+    actions.beginEditUserMessage('turn-1');
+    staged.quotes.push({ text: 'my own excerpt' });
+    assert.equal(await actions.prepareRevisionSend('edited text'), false);
+    assert.deepEqual(h.toasts.at(-1), {
+      kind: 'info',
+      title: 'ready',
+      description: 'mixed-context-unsupported',
+    });
+  });
+
+  it('cancels a prepared edit and clears both draft keys', async () => {
+    const staged = emptyStagedLog();
+    const h = createEnv({
+      messages: [userMessage('turn-1', 'explain this', { quotes: [quotedQuote] })],
+      staged,
+    });
+    const actions = createRevisionActions(h.env);
+
+    actions.beginEditUserMessage('turn-1');
+    await actions.prepareRevisionSend('edited text');
+    await actions.cancelRevisionDraft();
+
+    assert.deepEqual([...new Set(staged.cleared)].sort(), ['session-1', 'session-2']);
+    assert.equal(staged.quotes.length, 0, 'nothing stays staged after the cancel');
+    assert.equal(h.revisionDraftRef.current, null);
+  });
+
+  it('keeps quotes the user added when an edit is cancelled (#5274 review)', async () => {
+    const staged = emptyStagedLog();
+    const h = createEnv({
+      messages: [userMessage('turn-1', 'explain this', { quotes: [quotedQuote] })],
+      staged,
+    });
+    const actions = createRevisionActions(h.env);
+
+    actions.beginEditUserMessage('turn-1');
+    // Adding quotes during an edit is supported, so cancelling the edit
+    // undoes the edit — not the user's own staging (#5274 review).
+    const added: QuoteRef = { text: 'my own excerpt' };
+    staged.quotes.push(added);
+    await actions.cancelRevisionDraft();
+
+    assert.equal(h.revisionDraftRef.current, null);
+    assert.equal(h.env.composerRef.current?.getText(), '', 'the composer text rolls back');
+    assert.deepEqual(
+      staged.restored.at(-1),
+      { ownerKey: 'session-1', quotes: [added] },
+      'the user-added quote survives the cancel on the source key',
+    );
+  });
+
+  it('keeps a quote added on the branch child when a prepared edit is cancelled', async () => {
+    const staged = emptyStagedLog();
+    const h = createEnv({
+      messages: [userMessage('turn-1', 'explain this')],
+      staged,
+    });
+    const actions = createRevisionActions(h.env);
+
+    actions.beginEditUserMessage('turn-1');
+    assert.equal(await actions.prepareRevisionSend('edited text'), true);
+    const added: QuoteRef = { text: 'added while ready to send' };
+    // The plate re-keyed onto the branch child, so the composer the user
+    // stages into now binds to the branch-child bucket.
+    let branchBucket = staged.buckets.get('session-2');
+    if (!branchBucket) {
+      branchBucket = [];
+      staged.buckets.set('session-2', branchBucket);
+    }
+    branchBucket.push(added);
+    await actions.cancelRevisionDraft();
+
+    assert.equal(h.revisionDraftRef.current, null);
+    assert.deepEqual(
+      staged.restored.at(-1),
+      { ownerKey: 'session-1', quotes: [added] },
+      'the branch-child addition is re-keyed onto the source session',
+    );
+  });
+});
+
+describe('revision send gate', () => {
+  const source: RevisionStagedSource = {
+    originalQuotes: [{ text: 'q' }],
+    originalAttachments: [],
+  };
+  const restored = { quotes: [{ text: 'q' }] as readonly QuoteRef[], attachments: [] };
+
+  it('passes a genuine replacement', () => {
+    assert.equal(revisionSendGate(source, restored, false), 'pass');
+  });
+
+  it('passes an unchanged retry through (#5815)', () => {
+    assert.equal(revisionSendGate(source, restored, false), 'pass');
+  });
+
+  it('blocks newly staged quotes as a conflict', () => {
+    assert.equal(
+      revisionSendGate(
+        source,
+        { quotes: [{ text: 'q' }, { text: 'own' }], attachments: [] },
+        false,
+      ),
+      'conflict',
+    );
+  });
+
+  it('blocks pending directories with an empty attachment plate as a conflict', () => {
+    assert.equal(revisionSendGate(source, restored, true), 'conflict');
+  });
+});
+
+describe('revision staged-context helpers', () => {
+  it('stages the source quotes under the owner key and records them', () => {
+    const restored: Array<{ ownerKey: string; quotes: readonly QuoteRef[] }> = [];
+    const snapshot = stageRevisionSourceContext(
+      { restoreQuotes: (ownerKey, quotes) => restored.push({ ownerKey, quotes }) },
+      'session-1',
+      { quotes: [quotedQuote] },
+    );
+    assert.deepEqual(restored, [{ ownerKey: 'session-1', quotes: [quotedQuote] }]);
+    assert.deepEqual(snapshot.originalQuotes, [quotedQuote]);
+    assert.deepEqual(
+      snapshot.originalAttachments,
+      [],
+      'a message without attachments stages an empty attachment set',
+    );
+  });
+
+  it('clears every owner key once and keeps what the edit did not stage', () => {
+    const cleared: string[] = [];
+    const restored: Array<{ ownerKey: string; quotes: readonly QuoteRef[] }> = [];
+    const restoredByEdit = { text: 'restored by the edit' };
+    const addedByUser = { text: 'added during the edit' };
+    clearRevisionStagedContext(
+      {
+        restoreQuotes: (ownerKey, quotes) => restored.push({ ownerKey, quotes }),
+        clearQuotes: (ownerKey) => {
+          cleared.push(ownerKey);
+          return ownerKey === 'session-1' ? [restoredByEdit] : [addedByUser];
+        },
+      },
+      ['session-1', 'session-2', 'session-1'],
+      [restoredByEdit],
+    );
+    assert.deepEqual(cleared, ['session-1', 'session-2']);
+    assert.deepEqual(
+      restored,
+      [{ ownerKey: 'session-1', quotes: [addedByUser] }],
+      'the user-added quote re-keys onto the source Session',
+    );
+  });
+
+  it('keeps every user copy of a quote the edit also staged (#5274 review)', () => {
+    // The edit stages the source excerpt once and the user adds the identical
+    // excerpt twice during the edit: per-key counting means entries past the
+    // edit's own count are the user's, so the counter running negative must
+    // not drop the second copy — `=== 0` missed it (#5274 review).
+    const restored: Array<{ ownerKey: string; quotes: readonly QuoteRef[] }> = [];
+    const identical: QuoteRef = { text: 'the same excerpt' };
+    clearRevisionStagedContext(
+      {
+        restoreQuotes: (ownerKey, quotes) => restored.push({ ownerKey, quotes }),
+        clearQuotes: (ownerKey) => (ownerKey === 'session-1' ? [identical, identical, identical] : []),
+      },
+      ['session-1'],
+      [identical],
+    );
+    assert.deepEqual(
+      restored,
+      [{ ownerKey: 'session-1', quotes: [identical, identical] }],
+      'only the edit-owned entry is dropped; both user copies survive',
+    );
+  });
+});
diff --git a/packages/ui/src/chat-turn.tsx b/packages/ui/src/chat-turn.tsx
index 20119a8c69..796372acbb 100644
--- a/packages/ui/src/chat-turn.tsx
+++ b/packages/ui/src/chat-turn.tsx
@@ -623,28 +623,23 @@ export const TurnView = memo(function TurnView(props: {
                 ? () => props.onEditUserMessage?.(turn.turnId)
                 : undefined
             }
-            // A revision restages neither attachments, directory references,
-            // nor quotes, so a turn carrying any of them can't be edited
-            // without silently dropping context the answer was grounded in.
+            // Quotes and the selected message's own attachments restage into
+            // the surface's staged-context plates (#5109); directory
+            // references have no client-side restage path, so a turn carrying
+            // them still can't be edited without silently dropping context.
             editDisabled={
-              (turn.user.attachments?.length ?? 0) > 0 ||
               (turn.user.directoryReferences?.length ?? 0) > 0 ||
-              (turn.user.quotes?.length ?? 0) > 0 ||
               props.editUserMessageTransformed === true ||
               props.editUserMessageDisabled === true ||
               turn.status === 'running' ||
               !!props.liveStreaming
             }
             editDisabledReason={
-              (turn.user.attachments?.length ?? 0) > 0
-                ? copy.editMessageDisabledAttachments
-                : (turn.user.directoryReferences?.length ?? 0) > 0
-                  ? copy.editMessageDisabledDirectoryReferences
-                  : (turn.user.quotes?.length ?? 0) > 0
-                    ? copy.editMessageDisabledQuotes
-                    : props.editUserMessageTransformed
-                      ? copy.editMessageDisabledTransformedText
-                      : copy.editMessageDisabledRunning
+              (turn.user.directoryReferences?.length ?? 0) > 0
+                ? copy.editMessageDisabledDirectoryReferences
+                : props.editUserMessageTransformed
+                  ? copy.editMessageDisabledTransformedText
+                  : copy.editMessageDisabledRunning
             }
           />
 
diff --git a/packages/ui/src/conversation-copy.ts b/packages/ui/src/conversation-copy.ts
index c06b816443..ba48b34b2b 100644
--- a/packages/ui/src/conversation-copy.ts
+++ b/packages/ui/src/conversation-copy.ts
@@ -286,9 +286,7 @@ export interface ConversationCopy {
     copy: string;
     editMessage: string;
     editMessageDisabledRunning: string;
-    editMessageDisabledAttachments: string;
     editMessageDisabledDirectoryReferences: string;
-    editMessageDisabledQuotes: string;
     editMessageDisabledTransformedText: string;
     userAriaLabel: string;
     systemAriaLabel: string;
@@ -519,9 +517,8 @@ const CONVERSATION_COPY = {
       chooseAriaLabel: (label, branch) => branch ? `选择项目:${label},当前分支 ${branch}` : `选择项目:${label}`,
     },
     messages: {
-      you: '你', assistant: 'Maka', processing: '正在处理…', workingPhrases: ['正在琢磨…', '正在推敲…', '正在盘算…', '正在钻研…', '正在忙活…', '正在梳理…', '正在打磨…', '正在鼓捣…', '正在酝酿…', '正在攻坚…', '正在权衡…', '正在拾掇…'], processDetails: '执行过程', processDuration: (minutes, seconds) => `用时 ${minutes > 0 ? `${minutes} 分 ` : ''}${seconds} 秒`, turnStatusCompleted: (elapsed?: string) => ['已完成', elapsed].filter(Boolean).join(' · '), turnStatusAborted: (elapsed?: string) => ['已中止', elapsed].filter(Boolean).join(' · '), turnStatusFaile [...]
-      editMessageDisabledDirectoryReferences: '包含文件夹引用的历史消息暂不支持编辑并重发',
-      userAriaLabel: '你发送的消息', systemAriaLabel: '系统消息', assistantAriaLabel: 'Maka 的回答', answerActionsAriaLabel: (context) => `回答操作${context ? `:${context}` : ''}`, answerActionAriaLabel: (action, context) => `${action}回答${context ? `:${context}` : ''}`, messageActionAriaLabel: (action, context) => `${action}消息${context ? `:${context}` : ''}`, sourceAriaLabel: '本轮回答的来源', derivativesAriaLabel: '本轮回答的衍生', scheduledTaskTriggered: '定时任务触发', scheduledTaskTitle: (id) => `由定时任务触发 · ${id}`, legac [...]
+      you: '你', assistant: 'Maka', processing: '正在处理…', workingPhrases: ['正在琢磨…', '正在推敲…', '正在盘算…', '正在钻研…', '正在忙活…', '正在梳理…', '正在打磨…', '正在鼓捣…', '正在酝酿…', '正在攻坚…', '正在权衡…', '正在拾掇…'], processDetails: '执行过程', processDuration: (minutes, seconds) => `用时 ${minutes > 0 ? `${minutes} 分 ` : ''}${seconds} 秒`, turnStatusCompleted: (elapsed?: string) => ['已完成', elapsed].filter(Boolean).join(' · '), turnStatusAborted: (elapsed?: string) => ['已中止', elapsed].filter(Boolean).join(' · '), turnStatusFaile [...]
+      editMessageDisabledDirectoryReferences: '包含文件夹引用的历史消息暂不支持编辑并重发', userAriaLabel: '你发送的消息', systemAriaLabel: '系统消息', assistantAriaLabel: 'Maka 的回答', answerActionsAriaLabel: (context) => `回答操作${context ? `:${context}` : ''}`, answerActionAriaLabel: (action, context) => `${action}回答${context ? `:${context}` : ''}`, messageActionAriaLabel: (action, context) => `${action}消息${context ? `:${context}` : ''}`, sourceAriaLabel: '本轮回答的来源', derivativesAriaLabel: '本轮回答的衍生', scheduledTaskTriggere [...]
       thinkingTruncatedTitle: '部分 reasoning 已截断;显示的是最近的内容', outputTruncatedTitle: '助手输出已超过单次回合上限,超出部分未渲染。如需完整内容请重新生成或查看持久化的任务日志。', removeAttachmentAriaLabel: (name) => `移除 ${name}`, sessionSnapshotLabel: (name) => `会话:${name}`, sessionSnapshotPending: '发送时截取快照', sessionSnapshotCaptured: (iso, truncated) => `快照时间 ${iso}${truncated ? ' · 内容已截断' : ''}`, quoteSelectedTextLabel: '所选文本', quoteCommentLabel: '用户评论', quoteCommentPlaceholder: '添加可选评论…', quoteExpandAriaLabel: '展开引用全文', quoteCollaps [...]
       systemNotes: {
         contextCompacting: '正在压缩上下文…',
@@ -643,9 +640,8 @@ const CONVERSATION_COPY = {
       chooseAriaLabel: (label, branch) => branch ? `選擇專案:${label},目前分支 ${branch}` : `選擇專案:${label}`,
     },
     messages: {
-      you: '你', assistant: 'Maka', processing: '正在處理…', workingPhrases: ['正在琢磨…', '正在推敲…', '正在盤算…', '正在鑽研…', '正在忙活…', '正在梳理…', '正在打磨…', '正在鼓搗…', '正在醞釀…', '正在攻堅…', '正在權衡…', '正在拾掇…'], processDetails: '執行過程', processDuration: (minutes, seconds) => `用時 ${minutes > 0 ? `${minutes} 分 ` : ''}${seconds} 秒`, turnStatusCompleted: (elapsed?: string) => ['已完成', elapsed].filter(Boolean).join(' · '), turnStatusAborted: (elapsed?: string) => ['已中止', elapsed].filter(Boolean).join(' · '), turnStatusFaile [...]
-      editMessageDisabledDirectoryReferences: '包含資料夾引用的歷史訊息暫不支援編輯並重發',
-      userAriaLabel: '你傳送的訊息', systemAriaLabel: '系統訊息', assistantAriaLabel: 'Maka 的回答', answerActionsAriaLabel: (context) => `回答操作${context ? `:${context}` : ''}`, answerActionAriaLabel: (action, context) => `${action}回答${context ? `:${context}` : ''}`, messageActionAriaLabel: (action, context) => `${action}訊息${context ? `:${context}` : ''}`, sourceAriaLabel: '本輪迴答的來源', derivativesAriaLabel: '本輪迴答的衍生', scheduledTaskTriggered: '定時任務觸發', scheduledTaskTitle: (id) => `由定時任務觸發 · ${id}`, legac [...]
+      you: '你', assistant: 'Maka', processing: '正在處理…', workingPhrases: ['正在琢磨…', '正在推敲…', '正在盤算…', '正在鑽研…', '正在忙活…', '正在梳理…', '正在打磨…', '正在鼓搗…', '正在醞釀…', '正在攻堅…', '正在權衡…', '正在拾掇…'], processDetails: '執行過程', processDuration: (minutes, seconds) => `用時 ${minutes > 0 ? `${minutes} 分 ` : ''}${seconds} 秒`, turnStatusCompleted: (elapsed?: string) => ['已完成', elapsed].filter(Boolean).join(' · '), turnStatusAborted: (elapsed?: string) => ['已中止', elapsed].filter(Boolean).join(' · '), turnStatusFaile [...]
+      editMessageDisabledDirectoryReferences: '包含資料夾引用的歷史訊息暫不支援編輯並重發', userAriaLabel: '你傳送的訊息', systemAriaLabel: '系統訊息', assistantAriaLabel: 'Maka 的回答', answerActionsAriaLabel: (context) => `回答操作${context ? `:${context}` : ''}`, answerActionAriaLabel: (action, context) => `${action}回答${context ? `:${context}` : ''}`, messageActionAriaLabel: (action, context) => `${action}訊息${context ? `:${context}` : ''}`, sourceAriaLabel: '本輪迴答的來源', derivativesAriaLabel: '本輪迴答的衍生', scheduledTaskTriggere [...]
       thinkingTruncatedTitle: '部分 reasoning 已截斷;顯示的是最近的內容', outputTruncatedTitle: '助手輸出已超過單次回合上限,超出部分未渲染。如需完整內容請重新生成或檢視持久化的任務記錄。', removeAttachmentAriaLabel: (name) => `移除 ${name}`, sessionSnapshotLabel: (name) => `作業階段:${name}`, sessionSnapshotPending: '傳送時擷取快照', sessionSnapshotCaptured: (iso, truncated) => `快照時間 ${iso}${truncated ? ' · 內容已截斷' : ''}`, quoteSelectedTextLabel: '所選文字', quoteCommentLabel: '使用者評論', quoteCommentPlaceholder: '新增可選評論…', quoteExpandAriaLabel: '展開引用全文', quoteColl [...]
       systemNotes: {
         contextCompacting: '正在壓縮上下文…',
@@ -764,7 +760,7 @@ const CONVERSATION_COPY = {
       chooseAriaLabel: (label, branch) => branch ? `Choose project: ${label}, current branch ${branch}` : `Choose project: ${label}`,
     },
     messages: {
-      you: 'You', assistant: 'Maka', processing: 'Working…', workingPhrases: ['Pondering…', 'Tinkering…', 'Untangling…', 'Digging in…', 'Mulling…', 'Chewing on it…', 'Wrangling…', 'Piecing it together…'], processDetails: 'Execution process', processDuration: (minutes, seconds) => `Worked for ${minutes > 0 ? `${minutes}m ` : ''}${seconds}s`, turnStatusCompleted: (elapsed?: string) => ['Done', elapsed].filter(Boolean).join(' · '), turnStatusAborted: (elapsed?: string) => ['Stopped', elapse [...]
+      you: 'You', assistant: 'Maka', processing: 'Working…', workingPhrases: ['Pondering…', 'Tinkering…', 'Untangling…', 'Digging in…', 'Mulling…', 'Chewing on it…', 'Wrangling…', 'Piecing it together…'], processDetails: 'Execution process', processDuration: (minutes, seconds) => `Worked for ${minutes > 0 ? `${minutes}m ` : ''}${seconds}s`, turnStatusCompleted: (elapsed?: string) => ['Done', elapsed].filter(Boolean).join(' · '), turnStatusAborted: (elapsed?: string) => ['Stopped', elapse [...]
       editMessageDisabledDirectoryReferences: 'Edit & resend does not yet support messages with folder references',
       userAriaLabel: 'Your message', systemAriaLabel: 'System message', assistantAriaLabel: "Maka's response", answerActionsAriaLabel: (context) => `Response actions${context ? `: ${context}` : ''}`, answerActionAriaLabel: (action, context) => `${action} response${context ? `: ${context}` : ''}`, messageActionAriaLabel: (action, context) => `${action} message${context ? `: ${context}` : ''}`, sourceAriaLabel: 'Source of this response', derivativesAriaLabel: 'Responses derived from this o [...]
       thinkingTruncatedTitle: 'Some reasoning was truncated; showing the most recent content', outputTruncatedTitle: 'The assistant output exceeded the per-turn limit. Regenerate it or inspect the persisted task log for the complete content.', removeAttachmentAriaLabel: (name) => `Remove ${name}`, sessionSnapshotLabel: (name) => `Session: ${name}`, sessionSnapshotPending: 'snapshot captured when sent', sessionSnapshotCaptured: (iso, truncated) => `captured ${iso}${truncated ? ' · truncat [...]
diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.ts
index 98063c96ba..bb12af6578 100644
--- a/packages/ui/src/index.ts
+++ b/packages/ui/src/index.ts
@@ -202,3 +202,4 @@ export {
 export { PromptAnchorRail, type PromptAnchorRailTurn } from './prompt-anchor-rail.js';
 export { ChoicePanel, type ChoicePanelOption } from './choice-panel.js';
 export { formatCompactTokenCount } from './compact-token-count.js';
+export * from './revision-staged-context.js';
diff --git a/packages/ui/src/revision-staged-context.ts b/packages/ui/src/revision-staged-context.ts
new file mode 100644
index 0000000000..241dd49bdd
--- /dev/null
+++ b/packages/ui/src/revision-staged-context.ts
@@ -0,0 +1,605 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import type { AttachmentRef, QuoteRef } from '@maka/core/events';
+import { userFacingText, type StoredMessage } from '@maka/core/session';
+import type { UiLocale } from '@maka/core/ui-locale';
+import type { ComposerHandle } from './composer.js';
+import type { PendingAttachment } from './composer-attachments.js';
+
+/**
+ * Snapshot of the composer's staged context, read fresh at every use: the
+ * staging hooks bind their mutators to the active session's draft key, which
+ * moves across the revision commit (source → branch child). Restoring and
+ * clearing take an explicit owner key so the lifecycle can re-key the staged
+ * quotes across that commit; attachments do not restage — a revision copy
+ * excludes the revised turn and no target-owned refs exist client-side, so
+ * an edit of a message carrying them is refused outright (#5109 review).
+ */
+export type RevisionStagedContext = {
+  quotes: readonly QuoteRef[];
+  attachments: readonly PendingAttachment[];
+  restoreQuotes(ownerKey: string, quotes: readonly QuoteRef[]): void;
+  /** Removes and returns what an owner key holds, so the cancel path can
+   *  re-stage the entries the edit did not stage itself (#5274 review). */
+  clearQuotes(ownerKey: string): readonly QuoteRef[];
+};
+
+/** The edit-and-resend source context a staged plate must match verbatim. */
+export type RevisionStagedSource = {
+  originalQuotes: readonly QuoteRef[];
+  originalAttachments: readonly AttachmentRef[];
+};
+
+/**
+ * Surface-neutral revision draft: the shared staged-context fields every
+ * edit-and-resend client carries, parameterized by its copy-attempt phase.
+ */
+export type TurnRevisionDraftBase<Phase> = {
+  sourceSessionId: string;
+  sourceTurnId: string;
+  copyId: string;
+  copyPhase: Phase;
+  /** Active owner of the draft. Changes to the branch child after prepare. */
+  draftSessionId: string;
+  previousComposerText: string;
+  originalQuotes: readonly QuoteRef[];
+  originalAttachments: readonly AttachmentRef[];
+};
+
+
+function quoteKey(quote: QuoteRef): string {
+  // Every field participates: two snapshots can share text, label, and turn
+  // while differing in which Session they were captured from, when, or how
+  // completely — and treating a provenance-only replacement as a no-op would
+  // refuse a legitimate edit (apache/maka#5274 review). The model-facing
+  // comment counts too: editing only the annotation is a real change the
+  // composer exposes through onEditQuoteComment.
+  return JSON.stringify([
+    quote.text,
+    quote.label ?? null,
+    quote.sourceTurnId ?? null,
+    quote.sourceSessionId ?? null,
+    quote.sourceSessionName ?? null,
+    quote.sourceCapturedAt ?? null,
+    quote.sourceTruncated ?? null,
+    quote.comment ?? null,
+  ]);
+}
+
+/**
+ * Snapshot the source message's context at edit start and restage its quotes
+ * under the edit's owner key, so the gate can later tell the edit's own
+ * staging from the user's.
+ */
+export function stageRevisionSourceContext(
+  staged: Pick<RevisionStagedContext, 'restoreQuotes'>,
+  ownerKey: string,
+  message: { quotes?: readonly QuoteRef[] },
+): RevisionStagedSource {
+  const sourceQuotes = [...(message.quotes ?? [])];
+  if (sourceQuotes.length > 0) staged.restoreQuotes(ownerKey, sourceQuotes);
+  return { originalQuotes: sourceQuotes, originalAttachments: [] };
+}
+
+/**
+ * The pre-send gate for a revision replacement: 'conflict' blocks a send
+ * mixing user-staged context into the restored set (pending directories have
+ * no plate snapshot — flagged through pendingContext with an empty attachment
+ * plate). An unchanged-text retry is allowed through (#5815).
+ */
+export function revisionSendGate(
+  source: RevisionStagedSource,
+  staged: Pick<RevisionStagedContext, 'quotes' | 'attachments'>,
+  pendingContext: boolean,
+): 'pass' | 'conflict' {
+  if (
+    staged.quotes.length > source.originalQuotes.length ||
+    staged.attachments.length > source.originalAttachments.length ||
+    (pendingContext && staged.attachments.length === 0)
+  ) {
+    return 'conflict';
+  }
+  return 'pass';
+}
+
+/**
+ * Unstage the edit's staged context from under every draft key — the cancel
+ * path. Entries the edit staged itself (the beginEdit snapshot) are dropped
+ * wherever the commit left them (source key before it, branch child after);
+ * anything else on those plates is the user's own staging, added during the
+ * edit, so it survives — re-keyed onto the first owner key, the source
+ * Session the cancel returns to (#5274 review).
+ */
+export function clearRevisionStagedContext(
+  staged: Pick<RevisionStagedContext, 'clearQuotes' | 'restoreQuotes'>,
+  ownerKeys: readonly string[],
+  editOwnedQuotes: readonly QuoteRef[],
+): void {
+  const keys = [...new Set(ownerKeys)];
+  const owned = new Map<string, number>();
+  for (const quote of editOwnedQuotes) {
+    const key = quoteKey(quote);
+    owned.set(key, (owned.get(key) ?? 0) + 1);
+  }
+  const removed: QuoteRef[] = [];
+  for (const ownerKey of keys) removed.push(...staged.clearQuotes(ownerKey));
+  const kept: QuoteRef[] = [];
+  for (const quote of removed) {
+    // Past the edit's own per-quote count, every entry is the user's own —
+    // including once the counter has run negative past zero, because a user
+    // addition can duplicate a quote the edit staged itself (#5274 review).
+    const key = quoteKey(quote);
+    const ownedCount = owned.get(key) ?? 0;
+    owned.set(key, ownedCount - 1);
+    if (ownedCount <= 0) kept.push(quote);
+  }
+  if (keys.length > 0 && kept.length > 0) staged.restoreQuotes(keys[0], kept);
+}
+
+/** Localized strings an edit-and-resend surface needs from its own catalog. */
+export interface RevisionEditCopy {
+  revisionUnavailableTitle: string;
+  revisionAlreadyActive: string;
+  revisionAttachmentsUnsupported: string;
+  revisionDraftAttachmentConflict: string;
+  revisionDraftQuoteConflict: string;
+  revisionMixedContextUnsupported: string;
+  revisionTransformedTextUnsupported: string;
+  revisionStartedTitle: string;
+  revisionStartedDescription: string;
+  revisionReadyTitle: string;
+  revisionReadyDescription: string;
+  operationFailedTitle: string;
+  operationFailedFallback: string;
+}
+
+/** Identity of one copy attempt, owned by the surface's attempt tracker. */
+export interface RevisionCopyKey {
+  scope: string;
+  kind: string;
+  sourceSessionId: string;
+}
+
+/** Toast surface used by the revision lifecycle. */
+export interface RevisionToastApi {
+  info(title: string, description?: string): void;
+  error(
+    title: string,
+    description?: string,
+    diagnosticDetails?: string,
+    diagnosticTarget?: { sessionId: string },
+  ): void;
+}
+
+/**
+ * Everything a surface must inject so the edit-and-resend lifecycle can run
+ * without knowing the bridge, the locale catalog, or the attempt tracker:
+ * desktop touchpoints arrive as values and callbacks, never as imports.
+ *
+ * Why this lives in @maka/ui: the desktop renderer's debt ratchet forbids
+ * new dependency edges in the legacy shell files, and the lifecycle needs a
+ * runtime import of this module's composer types. Surfaces that already hold
+ * an @maka/ui edge (app-shell) assemble the env; the injected shell file
+ * keeps only type-level contact with this module.
+ */
+export interface RevisionActionsEnv<
+  Phase,
+  TDraft extends TurnRevisionDraftBase<Phase>,
+> {
+  uiLocale: UiLocale;
+  activeIdRef: { readonly current: string | undefined };
+  captureSelection(): () => boolean;
+  composerRef: { readonly current: ComposerHandle | null };
+  readMessages(): readonly StoredMessage[];
+  hasPendingAttachments(): boolean;
+  stagedContext(): RevisionStagedContext;
+  openSessionInChat(sessionId: string, turnId?: string): void;
+  refreshSessions(): Promise<unknown[]>;
+  commitRevisionDraft(draft: TurnRevisionDraftBase<Phase> | null): void;
+  revisionDraftRef: { readonly current: TDraft | null };
+  toastApi: RevisionToastApi;
+  copy: RevisionEditCopy;
+  reviseBeforeTurn(
+    sourceSessionId: string,
+    input: { sourceTurnId: string; copyId: string },
+  ): Promise<{ id: string }>;
+  abandonSessionCopy(sourceSessionId: string, copyId: string): Promise<void>;
+  localizedShellErrorMessage(error: unknown, fallback: string, locale: UiLocale): string;
+  /** True when the error is the workspace-unavailable class, having toasted. */
+  reportSessionWorkspaceUnavailable(error: unknown, sessionId: string): boolean;
+  acquireCopyAttempt(
+    key: RevisionCopyKey,
+    turnId: string,
+  ): { sourceTurnId: string; copyId: string; phase: Phase };
+  startCopyAttempt(key: RevisionCopyKey, copyId: string): boolean;
+  abandonCopyAttempt(key: RevisionCopyKey, copyId: string): boolean;
+  completeCopyAttempt(key: RevisionCopyKey, copyId: string): void;
+}
+
+function revisionCopyKey(
+  sourceSessionId: string,
+  sourceTurnId: string,
+): RevisionCopyKey {
+  return {
+    scope: `edit-and-resend:${sourceTurnId}`,
+    kind: 'revision',
+    sourceSessionId,
+  };
+}
+
+/**
+ * The edit-and-resend lifecycle shared by surfaces that stage the selected
+ * message's context into composer plates (#5109): edit click stages without
+ * branching; send prepares the before-turn branch, swaps the staged
+ * attachment refs for the copied message's target-owned refs, and hands back
+ * to the surface's normal send. Cancel unbranches and restores the plates.
+ */
+export function createRevisionActions<
+  Phase,
+  TDraft extends TurnRevisionDraftBase<Phase>,
+>(
+  env: RevisionActionsEnv<Phase, TDraft>,
+): {
+  beginEditUserMessage(turnId: string): void;
+  prepareRevisionSend(text: string): Promise<boolean>;
+  cancelRevisionDraft(): Promise<void>;
+} {
+  const {
+    uiLocale,
+    activeIdRef,
+    captureSelection,
+    composerRef,
+    readMessages,
+    hasPendingAttachments,
+    stagedContext,
+    openSessionInChat,
+    refreshSessions,
+    commitRevisionDraft,
+    revisionDraftRef,
+    toastApi,
+    copy,
+  } = env;
+
+  function beginEditUserMessage(turnId: string): void {
+    const sessionId = activeIdRef.current;
+    if (!sessionId) return;
+    const existing = revisionDraftRef.current;
+    if (existing) {
+      if (existing.draftSessionId === sessionId && existing.sourceTurnId === turnId) {
+        composerRef.current?.focus();
+      } else {
+        toastApi.info(copy.revisionUnavailableTitle, copy.revisionAlreadyActive);
+      }
+      return;
+    }
+    if (hasPendingAttachments()) {
+      toastApi.info(copy.revisionUnavailableTitle, copy.revisionDraftAttachmentConflict);
+      return;
+    }
+    const userMessage = readMessages().find(
+      (message): message is Extract<StoredMessage, { type: 'user' }> =>
+        message.type === 'user' && message.turnId === turnId,
+    );
+    if (!userMessage) {
+      toastApi.error(copy.operationFailedTitle, copy.operationFailedFallback, undefined, {
+        sessionId,
+      });
+      return;
+    }
+    if ((userMessage.attachments?.length ?? 0) > 0) {
+      // Host-side attachment ownership does not follow a revision copy — the
+      // copied transcript stops before the selected turn, so no target-owned
+      // refs exist to restage. The edit refuses rather than silently dropping
+      // the files (#5109 review, #5274 review).
+      toastApi.info(copy.revisionUnavailableTitle, copy.revisionAttachmentsUnsupported);
+      return;
+    }
+
+    // The selected message's quotes and attachments restage into the surface's
+    // plates (#5109): the plates make the carried context visible and
+    // explicitly removable, and the commit re-keys them onto the branch child
+    // (prepareRevisionSend). The edit refuses while the user has own context
+    // staged, so the plate ends up holding exactly the source context.
+    const staged = stagedContext();
+    if (staged.quotes.length > 0) {
+      toastApi.info(copy.revisionUnavailableTitle, copy.revisionDraftQuoteConflict);
+      return;
+    }
+    if (userMessage.displayText !== undefined && userMessage.displayText !== userMessage.text) {
+      toastApi.info(copy.revisionUnavailableTitle, copy.revisionTransformedTextUnsupported);
+      return;
+    }
+
+    const prompt = userFacingText(userMessage);
+    const copyAttempt = env.acquireCopyAttempt(
+      revisionCopyKey(sessionId, turnId),
+      turnId,
+    );
+    const { originalQuotes, originalAttachments } = stageRevisionSourceContext(
+      staged,
+      sessionId,
+      userMessage,
+    );
+    commitRevisionDraft({
+      sourceSessionId: sessionId,
+      sourceTurnId: copyAttempt.sourceTurnId,
+      copyId: copyAttempt.copyId,
+      copyPhase: copyAttempt.phase,
+      draftSessionId: sessionId,
+      previousComposerText: composerRef.current?.getText() ?? '',
+      originalQuotes,
+      originalAttachments,
+    });
+    composerRef.current?.setText(prompt);
+    composerRef.current?.focus();
+    toastApi.info(copy.revisionStartedTitle, copy.revisionStartedDescription);
+  }
+
+  async function rollbackPreparedRevision(
+    draft: TDraft,
+    revisionSessionId: string,
+    text: string,
+    selectionIsCurrent: () => boolean,
+  ): Promise<void> {
+    composerRef.current?.clearDraft(revisionSessionId);
+    const current = revisionDraftRef.current;
+    if (selectionIsCurrent() && activeIdRef.current === revisionSessionId) {
+      openSessionInChat(draft.sourceSessionId);
+      selectionIsCurrent = captureSelection();
+    }
+    const abandonment = await abandonRevisionCopy(draft);
+    const abandoningDraft = abandonment.draft;
+    let restored: TDraft | undefined;
+    if (current?.copyId === draft.copyId && revisionDraftRef.current === abandoningDraft) {
+      if (abandonment.acknowledged) {
+        const nextAttempt = env.acquireCopyAttempt(
+          revisionCopyKey(draft.sourceSessionId, draft.sourceTurnId),
+          draft.sourceTurnId,
+        );
+        restored = {
+          ...draft,
+          sourceTurnId: nextAttempt.sourceTurnId,
+          copyId: nextAttempt.copyId,
+          copyPhase: nextAttempt.phase,
+          draftSessionId: draft.sourceSessionId,
+        };
+      } else {
+        restored = { ...abandoningDraft, draftSessionId: draft.sourceSessionId };
+      }
+      composerRef.current?.setDraft(draft.sourceSessionId, text);
+      commitRevisionDraft(restored);
+    }
+    if (
+      selectionIsCurrent() && activeIdRef.current === draft.sourceSessionId &&
+      revisionDraftRef.current === restored
+    ) {
+      composerRef.current?.setText(text);
+      composerRef.current?.focus();
+    }
+    await refreshSessions().catch(() => []);
+  }
+
+  async function abandonRevisionCopy(
+    draft: TDraft,
+  ): Promise<{ acknowledged: boolean; draft: TDraft }> {
+    const tracked = env.abandonCopyAttempt(
+      revisionCopyKey(draft.sourceSessionId, draft.sourceTurnId),
+      draft.copyId,
+    );
+    const current = revisionDraftRef.current;
+    const trackedDraft = current?.copyId === draft.copyId ? current : draft;
+    const abandoningDraft =
+      tracked && trackedDraft.copyPhase !== 'abandoning'
+        ? { ...trackedDraft, copyPhase: 'abandoning' as const }
+        : trackedDraft;
+    if (revisionDraftRef.current === trackedDraft && abandoningDraft !== trackedDraft) {
+      commitRevisionDraft(abandoningDraft);
+    }
+    try {
+      // Main acknowledges only after the cleanup intent is durable; physical
+      // removal may finish after this renderer has closed the draft.
+      await env.abandonSessionCopy(draft.sourceSessionId, draft.copyId);
+      env.completeCopyAttempt(revisionCopyKey(draft.sourceSessionId, draft.sourceTurnId), draft.copyId);
+      return { acknowledged: true, draft: abandoningDraft };
+    } catch {
+      // An ambiguous cleanup acknowledgement stays in `abandoning`; this
+      // target may only retry cleanup and can never be copied into again.
+      return { acknowledged: false, draft: abandoningDraft };
+    }
+  }
+
+  async function prepareRevisionSend(text: string): Promise<boolean> {
+    let selectionIsCurrent = captureSelection();
+    let draft = revisionDraftRef.current;
+    if (!draft || activeIdRef.current !== draft.draftSessionId) return false;
+    // A send mixing user-staged context into the restored set cannot carry it
+    // truthfully; it stops here, toasting. An unchanged-text retry goes
+    // through (#5815).
+    const staged = stagedContext();
+    if (revisionSendGate(draft, staged, hasPendingAttachments()) !== 'pass') {
+      toastApi.info(copy.revisionReadyTitle, copy.revisionMixedContextUnsupported);
+      return false;
+    }
+    // A previous attempt already prepared the version; retry normal send there.
+    if (draft.draftSessionId !== draft.sourceSessionId) return true;
+
+    if (draft.copyPhase === 'abandoning') {
+      const abandonment = await abandonRevisionCopy(draft);
+      if (
+        !selectionIsCurrent() || !abandonment.acknowledged ||
+        revisionDraftRef.current !== abandonment.draft ||
+        activeIdRef.current !== draft.sourceSessionId
+      ) {
+        return false;
+      }
+      const nextAttempt = env.acquireCopyAttempt(
+        revisionCopyKey(draft.sourceSessionId, draft.sourceTurnId),
+        draft.sourceTurnId,
+      );
+      draft = {
+        ...draft,
+        copyId: nextAttempt.copyId,
+        copyPhase: nextAttempt.phase,
+      };
+      commitRevisionDraft(draft);
+    }
+
+    const startedDraft =
+      draft.copyPhase === 'started' ? draft : { ...draft, copyPhase: 'started' as const };
+    if (startedDraft !== draft) {
+      if (
+        !env.startCopyAttempt(
+          revisionCopyKey(draft.sourceSessionId, draft.sourceTurnId),
+          draft.copyId,
+        )
+      ) {
+        return false;
+      }
+      commitRevisionDraft(startedDraft);
+    }
+    const sourceSessionId = startedDraft.sourceSessionId;
+    let preparedSessionId: string | undefined;
+    try {
+      const newSession = await env.reviseBeforeTurn(sourceSessionId, {
+        sourceTurnId: startedDraft.sourceTurnId,
+        copyId: startedDraft.copyId,
+      });
+      preparedSessionId = newSession.id;
+      if (!selectionIsCurrent() || revisionDraftRef.current !== startedDraft) {
+        await rollbackPreparedRevision(startedDraft, newSession.id, text, selectionIsCurrent);
+        return false;
+      }
+
+      const prepared = { ...startedDraft, draftSessionId: newSession.id };
+      composerRef.current?.setDraft(newSession.id, text);
+      commitRevisionDraft(prepared);
+      openSessionInChat(newSession.id);
+      selectionIsCurrent = captureSelection();
+      await refreshSessions();
+      if (!selectionIsCurrent() || revisionDraftRef.current !== prepared) {
+        await rollbackPreparedRevision(startedDraft, newSession.id, text, selectionIsCurrent);
+        return false;
+      }
+      // Re-key the plate's *current* quotes onto the branch child: the user
+      // may have removed or re-annotated entries during the edit, and the
+      // replacement must carry the plate as it stands, not the snapshot the
+      // edit started from (#5274 review). Re-keyed only after every rollback
+      // check has passed, so a failed preparation leaves the plate on the
+      // source key.
+      staged.restoreQuotes(newSession.id, staged.quotes);
+      staged.clearQuotes(startedDraft.sourceSessionId);
+      composerRef.current?.focus();
+      toastApi.info(copy.revisionReadyTitle, copy.revisionReadyDescription);
+      return true;
+    } catch (error) {
+      // Rollback itself navigates back to the source Session, so the failure
+      // must be surfaced before it runs — checking after it is always stale.
+      if (selectionIsCurrent()) {
+        if (env.reportSessionWorkspaceUnavailable(error, sourceSessionId)) {
+          return false;
+        }
+        toastApi.error(
+          copy.operationFailedTitle,
+          env.localizedShellErrorMessage(error, copy.operationFailedFallback, uiLocale),
+          undefined,
+          { sessionId: sourceSessionId },
+        );
+      }
+      if (preparedSessionId) {
+        await rollbackPreparedRevision(startedDraft, preparedSessionId, text, selectionIsCurrent);
+      }
+      return false;
+    }
+  }
+
+  async function cancelRevisionDraft(): Promise<void> {
+    let selectionIsCurrent = captureSelection();
+    const draft = revisionDraftRef.current;
+    if (!draft) return;
+    const cleanupSessionId = draft.copyPhase !== 'reserved'
+      ? draft.draftSessionId !== draft.sourceSessionId
+        ? draft.draftSessionId
+        : draft.copyId
+      : undefined;
+    if (cleanupSessionId) await abandonRevisionCopy(draft);
+    else env.completeCopyAttempt(revisionCopyKey(draft.sourceSessionId, draft.sourceTurnId), draft.copyId);
+    commitRevisionDraft(null);
+    // Unstage the edit's staged context under both draft keys (source before
+    // the commit, branch child after); quotes the user added during the edit
+    // are not the edit's, so they survive on the source key (#5274 review).
+    clearRevisionStagedContext(
+      stagedContext(),
+      [draft.sourceSessionId, draft.draftSessionId],
+      draft.originalQuotes,
+    );
+    composerRef.current?.setDraft(draft.sourceSessionId, draft.previousComposerText);
+    if (draft.draftSessionId !== draft.sourceSessionId) {
+      composerRef.current?.clearDraft(draft.draftSessionId);
+    }
+    if (selectionIsCurrent() && activeIdRef.current !== draft.sourceSessionId) {
+      openSessionInChat(draft.sourceSessionId);
+      selectionIsCurrent = captureSelection();
+    }
+    if (cleanupSessionId) {
+      await refreshSessions().catch(() => []);
+    }
+    if (selectionIsCurrent() && activeIdRef.current === draft.sourceSessionId) {
+      composerRef.current?.setText(draft.previousComposerText);
+      composerRef.current?.focus();
+    }
+  }
+
+  return { beginEditUserMessage, prepareRevisionSend, cancelRevisionDraft };
+}
+
+/**
+ * The module-level copy-attempt bookkeeping a surface exports beside the
+ * factory: completion on send, and abandonment with the same ambiguous-
+ * acknowledgement contract as the lifecycle above.
+ */
+export function createTurnRevisionCopyHelpers<
+  Phase,
+  TDraft extends TurnRevisionDraftBase<Phase>,
+>(deps: {
+  completeCopyAttempt(key: RevisionCopyKey, copyId: string): void;
+  abandonCopyAttempt(key: RevisionCopyKey, copyId: string): boolean;
+  abandonSessionCopy(sourceSessionId: string, copyId: string): Promise<void>;
+}): {
+  completeTurnRevisionCopyAttempt(draft: TDraft): void;
+  abandonTurnRevisionCopyAttempt(draft: TDraft): Promise<boolean>;
+} {
+  function completeTurnRevisionCopyAttempt(draft: TDraft): void {
+    deps.completeCopyAttempt(revisionCopyKey(draft.sourceSessionId, draft.sourceTurnId), draft.copyId);
+  }
+
+  async function abandonTurnRevisionCopyAttempt(draft: TDraft): Promise<boolean> {
+    const key = revisionCopyKey(draft.sourceSessionId, draft.sourceTurnId);
+    deps.abandonCopyAttempt(key, draft.copyId);
+    try {
+      await deps.abandonSessionCopy(draft.sourceSessionId, draft.copyId);
+      deps.completeCopyAttempt(key, draft.copyId);
+      return true;
+    } catch {
+      return false;
+    }
+  }
+
+  return { completeTurnRevisionCopyAttempt, abandonTurnRevisionCopyAttempt };
+}
diff --git a/packages/ui/src/use-composer-attachments.ts b/packages/ui/src/use-composer-attachments.ts
index 271fcf2d90..93c4f6542c 100644
--- a/packages/ui/src/use-composer-attachments.ts
+++ b/packages/ui/src/use-composer-attachments.ts
@@ -546,6 +546,10 @@ export function useComposerAttachments(options: {
     updateAttachments(() => ({}));
   }
 
+  /** Clears one draft key's pending attachments. The revision lifecycle uses
+   * this to clean up the source message's refs an edit staged when that edit
+   * is cancelled, under both the source and the branch child keys (#5274
+   * review). */
   return {
     pendingAttachments,
     pendingDirectories,


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org