DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
feat(turnrewind): two-phase /undo with in-card confirm buttons
yingtianlan18ab321a5793
diff --git a/plugins/dsh-tauri-turnrewind/lib/client.js b/plugins/dsh-tauri-turnrewind/lib/client.jsindex f3c8ef45..44e71a5b 100644--- a/plugins/dsh-tauri-turnrewind/lib/client.js+++ b/plugins/dsh-tauri-turnrewind/lib/client.js@@ -22,12 +22,15 @@ globalThis.__ModuleLoader__.load({const jsx = jsxRuntime.jsxconst jsxs = jsxRuntime.jsxs- const inject = ['slots', 'sessions', 'locale']+ const inject = ['slots', 'sessions', 'locale', 'connection']+ // The ✓ button submits the confirm/cancel command line back through the+ // host's prompt RPC; assigned from apply() once the ctx is available.+ let submitLine = null// ------------------------------------------------------------------// /undo output parsing: the command prints a structured plain-text plan- // (summary line, indented file list, per-file unified diff sections).- // Parse it once so the card can render badge, list and colored diffs.+ // (summary line, indented file list, per-file unified diff sections)+ // plus a trailing machine-readable `plan <id>` confirmation row.// ------------------------------------------------------------------function isFileSeparator(raw) {return /^--- (?!a\/)(?!b\/)\S/.test(raw)@@ -35,11 +38,18 @@ globalThis.__ModuleLoader__.load({function parseUndoOutput(raw) {const lines = (raw ?? '').split('\n')- const result = { summary: lines[0] ?? '', files: [], dividers: [] }+ const result = { summary: lines[0] ?? '', files: [], dividers: [], planId: undefined }let current = nulllet inDiffs = falsefor (let i = 1; i < lines.length; i++) {const line = lines[i]+ const planRow = /^plan ([0-9a-f-]+)$/.exec(line)+ if (planRow) {+ result.planId = planRow[1]+ continue+ }+ if (/^Send \/undo --(?:confirm|cancel)/.test(line))+ continueif (/^(?:Undo will apply|Conflicts \()/.test(line)) {inDiffs = trueresult.dividers.push(line)@@ -194,9 +204,25 @@ globalThis.__ModuleLoader__.load({const hasDiff = withDiff.length > 0const summary = parsed.summary || (state === 'error' ? '失败' : state === 'running' ? '运行中' : '完成')const [expanded, setExpanded] = React.useState(hasDiff)+ const [submitted, setSubmitted] = React.useState(null)const titleColor = state === 'error' ? 'var(--dsw-alias-state-error-primary, #f85149)' : 'var(--dsw-alias-label-primary, #cccccc)'const showBody = expanded && (hasDiff || parsed.files.length > 0)+ // Buttons only on a pending preview (plan id present, command finished).+ const actionable = parsed.planId !== undefined && state === 'ok'++ function submit(kind) {+ if (submitted || !parsed.planId)+ return+ const line = kind === 'confirm'+ ? `/undo --confirm ${parsed.planId}`+ : `/undo --cancel ${parsed.planId}`+ const sent = submitLine ? submitLine(line) : false+ setSubmitted(sent ? kind : 'failed')+ }++ const confirmLabel = submitted === 'confirm' ? '已确认,执行中…' : '✓ 执行撤销'+ const cancelLabel = submitted === 'cancel' ? '已取消' : '✕ 取消'return jsxs('div', {style: { border: `1px solid ${DIFF_COLORS.border}`, background: 'var(--dsw-alias-bg-layer-1, transparent)', borderRadius: 12, margin: '4px 0 4px 4px', overflow: 'hidden', maxWidth: '100%' },@@ -221,6 +247,29 @@ globalThis.__ModuleLoader__.load({jsx('span', { children: file.path }),] }, file.path)) }): null,+ actionable+ ? jsxs('div', {+ style: { display: 'flex', alignItems: 'center', gap: 10, borderTop: `1px solid ${DIFF_COLORS.border}`, padding: '8px 12px' },+ children: [+ jsx('button', {+ type: 'button',+ onClick() { submit('confirm') },+ disabled: submitted !== null,+ style: { background: 'var(--dsw-alias-button-primary-fill, #4f46e5)', color: 'var(--dsw-alias-label-primary-foreground, #ffffff)', border: 'none', borderRadius: 8, padding: '5px 16px', fontSize: 12.5 },+ children: confirmLabel,+ }),+ jsx('button', {+ type: 'button',+ onClick() { submit('cancel') },+ disabled: submitted !== null,+ style: { background: 'transparent', color: submitted === 'cancel' ? 'var(--dsw-alias-label-tertiary, #8b8b8b)' : 'var(--dsw-alias-state-error-primary, #f85149)', border: '1px solid var(--dsw-alias-border-l2, #30363d)', borderRadius: 8, padding: '5px 16px', fontSize: 12.5 },+ children: cancelLabel,+ }),+ jsx('span', { style: { flex: 1 } }),+ jsx('span', { style: { color: 'var(--dsw-alias-label-tertiary, #8b8b8b)', fontSize: 11.5 }, children: submitted === 'failed' ? '发送失败,请手动输入 /undo --confirm' : '执行将恢复下方文件到本轮改动前' }),+ ],+ })+ : null,],})}@@ -404,6 +453,26 @@ globalThis.__ModuleLoader__.load({// Read through the service store, not the ctx.sessions property proxy:// the host session service merges a different member under the same name.const sessions = ctx.get('sessions')+ // The ✓ button sends the confirm/cancel command line as a user prompt on+ // the current session — the same path the input box uses. The host+ // parses it server-side and executes the parked pending plan.+ submitLine = (line) => {+ try {+ const sessionId = sessions.list.getSnapshot().current+ if (sessionId === undefined)+ return false+ const connection = ctx.get('connection')+ const api = connection?.api ?? connection?.remote?.api+ if (typeof api?.sessions?.prompt !== 'function')+ return false+ api.sessions.prompt({ sessionId, mode: 'queue', content: line })+ return true+ }+ catch (error) {+ console.error('[turnrewind] failed to submit undo confirmation:', error)+ return false+ }+ }function checkOnce() {const state = sessions.list.getSnapshot()diff --git a/plugins/dsh-tauri-turnrewind/lib/core/ledger.js b/plugins/dsh-tauri-turnrewind/lib/core/ledger.jsindex 59ca4089..8d71af90 100644--- a/plugins/dsh-tauri-turnrewind/lib/core/ledger.js+++ b/plugins/dsh-tauri-turnrewind/lib/core/ledger.js@@ -51,6 +51,15 @@ const SCHEMA = `claimed_at TEXT);CREATE INDEX IF NOT EXISTS rewind_notices_session_idx ON rewind_notices(session_id, status, created_at);+ CREATE TABLE IF NOT EXISTS pending_plans (+ plan_id TEXT PRIMARY KEY,+ session_id TEXT NOT NULL,+ workspace_key TEXT NOT NULL,+ turn_id TEXT NOT NULL,+ paths_json TEXT NOT NULL,+ created_at TEXT NOT NULL,+ expires_at TEXT NOT NULL+ );`export function openLedger(rootDir) {@@ -84,9 +93,63 @@ export function openLedger(rootDir) {// Column already exists.}db.exec(`UPDATE turns SET status = 'abandoned', reversible = 0, error = 'plugin restarted during active turn' WHERE status = 'active'`)+ purgeExpiredPendingPlans(db)return db}+// ------------------------------------------------------------------+// Pending undo plans: /undo parks a confirmed-ready plan here; the client's+// ✓ button runs `/undo --confirm <plan-id>` to execute it. Rows expire so an+// ignored preview can never apply hours later against a changed workspace.+// ------------------------------------------------------------------+const PENDING_PLAN_TTL_MS = 5 * 60 * 1000++export function purgeExpiredPendingPlans(db) {+ db.prepare('DELETE FROM pending_plans WHERE expires_at < ?').run(new Date().toISOString())+}++export function createPendingPlan(db, plan) {+ db.exec('BEGIN')+ try {+ // One live plan per session+workspace: a newer preview replaces the older.+ db.prepare('DELETE FROM pending_plans WHERE session_id = ? AND workspace_key = ?')+ .run(plan.sessionId, plan.workspaceKey)+ const planId = randomUUID().slice(0, 8)+ const createdAt = new Date().toISOString()+ db.prepare(`+ INSERT INTO pending_plans(plan_id, session_id, workspace_key, turn_id, paths_json, created_at, expires_at)+ VALUES (?, ?, ?, ?, ?, ?, ?)+ `).run(planId, plan.sessionId, plan.workspaceKey, plan.turnId, JSON.stringify(plan.paths), createdAt, new Date(Date.now() + PENDING_PLAN_TTL_MS).toISOString())+ db.exec('COMMIT')+ return planId+ }+ catch (error) {+ db.exec('ROLLBACK')+ throw error+ }+}++export function getPendingPlan(db, planId, sessionId, workspaceKey) {+ const row = db.prepare(`+ SELECT * FROM pending_plans+ WHERE plan_id = ? AND session_id = ? AND workspace_key = ?+ `).get(planId, sessionId, workspaceKey)+ if (row === undefined)+ return undefined+ if (row.expires_at < new Date().toISOString()) {+ db.prepare('DELETE FROM pending_plans WHERE plan_id = ?').run(planId)+ return undefined+ }+ return { turnId: row.turn_id, paths: JSON.parse(row.paths_json), createdAt: row.created_at }+}++export function deletePendingPlan(db, planId, sessionId, workspaceKey) {+ const result = db.prepare(`+ DELETE FROM pending_plans WHERE plan_id = ? AND session_id = ? AND workspace_key = ?+ `).run(planId, sessionId, workspaceKey)+ return result.changes > 0+}+export function registerWorkspace(db, workspaceKey, workspacePath, snapshotRepo) {db.prepare(`INSERT INTO workspaces(workspace_key, workspace_path, snapshot_repo, created_at)diff --git a/plugins/dsh-tauri-turnrewind/lib/index.js b/plugins/dsh-tauri-turnrewind/lib/index.jsindex 0d79b388..f5b06fa4 100644--- a/plugins/dsh-tauri-turnrewind/lib/index.js+++ b/plugins/dsh-tauri-turnrewind/lib/index.js@@ -5,7 +5,7 @@ import process from 'node:process'import { createDialogProjection } from './core/dialog-projection.js'import { captureSnapshot, classifyPathChange, createSnapshotStore, currentState, diffAgainstDisk, gitAvailable, gitRef, probeWorkspace, restorePath, snapshotDiff, snapshotFileDiff, stateAt } from './core/git-snapshot.js'import { assessWorkspace, defaultBudget } from './core/guard.js'-import { claimRewindNotices, completeRedoWithNotice, completeUndoWithNotice, createOperation, failTurn, getLatestAppliedUndo, getLatestSnapshotRef, getLatestTurnSummary, getTurn, insertTurn, listReversibleTurns, markTurnSnapshotMissing, openLedger, recordSkippedTurn, registerWorkspace, settleInterruptedTurn, settleNoopTurn, settleOperation, settleTurn, skipTurn } from './core/ledger.js'+import { claimRewindNotices, completeRedoWithNotice, completeUndoWithNotice, createOperation, createPendingPlan, deletePendingPlan, failTurn, getLatestAppliedUndo, getLatestSnapshotRef, getLatestTurnSummary, getPendingPlan, getTurn, insertTurn, listReversibleTurns, markTurnSnapshotMissing, openLedger, recordSkippedTurn, registerWorkspace, settleInterruptedTurn, settleNoopTurn, settleOperation, settleTurn, skipTurn } from './core/ledger.js'import { classifyUndo } from './core/planner.js'const name = 'dsh-tauri-turnrewind'@@ -56,6 +56,8 @@ function parseUndoInput(rawInput) {let skipConflicts = falselet force = falselet redo = false+ let confirm = false+ let cancel = falsefor (const part of parts) {if (part === '--dry-run') {dryRun = true@@ -72,6 +74,12 @@ function parseUndoInput(rawInput) {else if (part === '--redo') {redo = true}+ else if (part === '--confirm') {+ confirm = true+ }+ else if (part === '--cancel') {+ cancel = true+ }else if (part === '--subtree') {return { error: 'Recursive subtree undo is not available in the MVP.' }}@@ -79,14 +87,20 @@ function parseUndoInput(rawInput) {turnId = part}else {- return { error: 'Usage: /undo [turn-id] [--dry-run|--preview] [--skip-conflicts|--force] or /undo --redo' }+ return { error: 'Usage: /undo [--preview] | /undo --confirm <plan-id> | /undo --cancel <plan-id> | /undo <turn-id> --force' }}}if (skipConflicts && force)return { error: '--skip-conflicts and --force are mutually exclusive.' }- if (redo && (turnId !== undefined || dryRun || preview || skipConflicts || force))+ if (redo && (turnId !== undefined || dryRun || preview || skipConflicts || force || confirm || cancel))return { error: '--redo cannot be combined with a turn id or other options.' }- return { turnId, dryRun, preview, skipConflicts, force, redo }+ if ((confirm || cancel) && (dryRun || preview || skipConflicts || force))+ return { error: '--confirm/--cancel cannot be combined with preview or conflict-override flags.' }+ if (confirm && cancel)+ return { error: '--confirm and --cancel are mutually exclusive.' }+ if ((confirm || cancel) && turnId === undefined)+ return { error: confirm ? 'Usage: /undo --confirm <plan-id>' : 'Usage: /undo --cancel <plan-id>' }+ return { turnId, dryRun, preview, skipConflicts, force, redo, confirm, cancel }}function assertSessionOwner(target, agent) {@@ -350,8 +364,24 @@ async function applyUndo(runtime, active, invocation) {if (parsed.redo)return applyRedo(runtime, invocation, workspaceDir, workspaceKey)+ // Pending-plan lifecycle: --cancel drops a parked plan; --confirm validates+ // it and falls through to execution below.+ if (parsed.cancel) {+ const removed = deletePendingPlan(runtime.db, parsed.turnId, invocation.agent.session.id, workspaceKey)+ return { kind: 'success', text: removed ? 'Pending undo cancelled.' : 'No pending undo plan matched (it may have expired or already run).' }+ }+let target- if (parsed.turnId) {+ let pendingPlan+ if (parsed.confirm) {+ pendingPlan = getPendingPlan(runtime.db, parsed.turnId, invocation.agent.session.id, workspaceKey)+ if (!pendingPlan)+ return { kind: 'error', text: `No pending undo plan ${parsed.turnId} for this session (it expired after 5 minutes, was replaced by a newer preview, or already ran). Run /undo again to preview a fresh plan.` }+ target = getTurn(runtime.db, pendingPlan.turnId)+ if (!target || !await turnRefsExist(runtime.store, target))+ return { kind: 'error', text: 'The pending plan\u0027s snapshot data no longer exists. Run /undo again to preview a fresh plan.' }+ }+ else if (parsed.turnId) {target = getTurn(runtime.db, parsed.turnId)if (target && !await turnRefsExist(runtime.store, target)) {return {@@ -395,14 +425,35 @@ async function applyUndo(runtime, active, invocation) {const entries = await buildPlanEntries(runtime, workspaceDir, target, paths)const conflicts = entries.filter(entry => entry.conflict)+ const directExecute = parsed.force || parsed.skipConflicts// Read-only plan/preview: never touch disk.- if (parsed.dryRun || parsed.preview)+ if (parsed.dryRun)return { kind: 'success', text: await formatPlan(runtime, target, entries, parsed) }- // Default policy refuses to overwrite anything it cannot attribute.- if (conflicts.length > 0 && !parsed.skipConflicts && !parsed.force)- return { kind: 'error', text: await formatPlan(runtime, target, entries, parsed) }+ // Bare /undo and --preview park a pending plan; execution waits for the+ // ✓ button (which sends /undo --confirm <plan-id>) so the user cannot+ // accidentally skip the preview.+ if (!directExecute && !parsed.confirm) {+ const planText = await formatPlan(runtime, target, entries, parsed)+ if (conflicts.length > 0)+ return { kind: parsed.preview ? 'success' : 'error', text: planText }+ const planId = createPendingPlan(runtime.db, {+ sessionId: invocation.agent.session.id,+ workspaceKey,+ turnId: target.turn_id,+ paths,+ })+ return {+ kind: 'success',+ text: `${planText}\nplan ${planId}\nSend /undo --confirm ${planId} to apply, or /undo --cancel ${planId} to dismiss.`,+ }+ }++ // Confirmed execution: re-verify nothing changed on disk since the+ // preview before overwriting anything.+ if (parsed.confirm && conflicts.length > 0)+ return { kind: 'error', text: `The workspace changed since the preview (${conflicts.length} conflicted file(s)). Run /undo again to refresh the plan; use --force/--skip-conflicts deliberately if needed.` }const operationId = randomUUID()const beforeRef = `refs/turnrewind/operation-${operationId}`diff --git a/plugins/dsh-tauri-turnrewind/test/lifecycle.test.js b/plugins/dsh-tauri-turnrewind/test/lifecycle.test.jsindex a29d998a..4f435182 100644--- a/plugins/dsh-tauri-turnrewind/test/lifecycle.test.js+++ b/plugins/dsh-tauri-turnrewind/test/lifecycle.test.js@@ -40,6 +40,15 @@ async function setupTurn() {return { root, workspace, db, runtime, active: new Map(), invocation }}+/** Bare /undo now parks a pending plan; execute it like the ✓ button would. */+async function undoWithConfirm(runtime, active, invocation) {+ const preview = await applyUndo(runtime, active, invocation())+ assert.equal(preview.kind, 'success')+ const planId = /plan ([0-9a-f-]+)/u.exec(preview.text)?.[1]+ assert.ok(planId, 'preview must carry a pending plan id')+ return applyUndo(runtime, active, invocation(`--confirm ${planId}`))+}+it('plans, previews, and applies conflict policies', async () => {const { root, workspace, db, runtime, active, invocation } = await setupTurn()try {@@ -100,7 +109,7 @@ it('forces a restore over a conflicted file', async () => {it('round-trips undo and redo', async () => {const { root, workspace, db, runtime, active, invocation } = await setupTurn()try {- const undo = await applyUndo(runtime, active, invocation())+ const undo = await undoWithConfirm(runtime, active, invocation)assert.equal(undo.kind, 'success')assert.equal(await readFile(join(workspace, 'a.txt'), 'utf8'), 'v1\n')await assert.rejects(stat(join(workspace, 'c.txt')))@@ -113,7 +122,7 @@ it('round-trips undo and redo', async () => {assert.equal(getTurn(db, 'session:1').status, 'settled')// The turn is reversible again after the redo.- const undoAgain = await applyUndo(runtime, active, invocation())+ const undoAgain = await undoWithConfirm(runtime, active, invocation)assert.equal(undoAgain.kind, 'success')assert.equal(await readFile(join(workspace, 'a.txt'), 'utf8'), 'v1\n')@@ -131,7 +140,7 @@ it('round-trips undo and redo', async () => {it('blocks redo when the disk changed after the undo', async () => {const { root, workspace, db, runtime, active, invocation } = await setupTurn()try {- const undo = await applyUndo(runtime, active, invocation())+ const undo = await undoWithConfirm(runtime, active, invocation)assert.equal(undo.kind, 'success')await writeFile(join(workspace, 'a.txt'), 'edited-after-undo\n')const redo = await applyUndo(runtime, active, invocation('--redo'))