DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
feat(turnrewind): pending plans carry outcome status for the card to poll
yingtianlan654cb72ccd9a
diff --git a/plugins/dsh-tauri-turnrewind/lib/client.js b/plugins/dsh-tauri-turnrewind/lib/client.jsindex 8230df68..31521cb0 100644--- a/plugins/dsh-tauri-turnrewind/lib/client.js+++ b/plugins/dsh-tauri-turnrewind/lib/client.js@@ -207,6 +207,38 @@ globalThis.__ModuleLoader__.load({const [expanded, setExpanded] = React.useState(hasDiff)const [submitted, setSubmitted] = React.useState(null)const [submitError, setSubmitError] = React.useState(null)+ const [resultText, setResultText] = React.useState(null)++ // The confirm route executes server-side and records the outcome on the+ // plan row; poll until the result lands so the card shows it in place.+ React.useEffect(() => {+ if (submitted !== 'confirm' || !parsed.planId)+ return+ let stop = false+ const timer = setInterval(async () => {+ if (stop)+ return+ try {+ const res = await fetch(`/api/turnrewind/status?planId=${encodeURIComponent(parsed.planId)}`)+ const payload = await res.json().catch(() => ({}))+ if (stop || res.ok === false)+ return+ if (payload.status === 'applied') {+ setResultText(payload.resultText ?? '已执行')+ clearInterval(timer)+ }+ else if (payload.status === 'cancelled') {+ setSubmitted('cancel')+ clearInterval(timer)+ }+ }+ catch {}+ }, 1500)+ return () => {+ stop = true+ clearInterval(timer)+ }+ }, [submitted, parsed.planId])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)@@ -230,9 +262,14 @@ globalThis.__ModuleLoader__.load({const cancelLabel = submitted === 'cancel' ? '已取消' : '✕ 取消'const hint = submitError? `执行确认失败:${submitError}`- : submitted === 'confirm'- ? '已提交,执行结果见下方新的 undo 卡片'- : submitted === 'cancel' ? '已取消' : '执行将恢复下方文件到本轮改动前'+ : resultText || (submitted === 'confirm'+ ? '已提交,等待执行结果…'+ : submitted === 'cancel' ? '已取消' : '执行将恢复下方文件到本轮改动前')+ const hintColor = submitError+ ? 'var(--dsw-alias-state-error-primary, #f85149)'+ : resultText+ ? 'var(--dsw-alias-state-success-primary, #3fb950)'+ : 'var(--dsw-alias-label-tertiary, #8b8b8b)'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%' },@@ -276,7 +313,7 @@ globalThis.__ModuleLoader__.load({children: cancelLabel,}),jsx('span', { style: { flex: 1 } }),- jsx('span', { style: { color: submitError ? 'var(--dsw-alias-state-error-primary, #f85149)' : 'var(--dsw-alias-label-tertiary, #8b8b8b)', fontSize: 11.5, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }, children: hint }),+ jsx('span', { style: { color: hintColor, fontSize: 11.5, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }, children: hint }),],}): null,diff --git a/plugins/dsh-tauri-turnrewind/lib/core/ledger.js b/plugins/dsh-tauri-turnrewind/lib/core/ledger.jsindex dcfa2d30..71aadf27 100644--- a/plugins/dsh-tauri-turnrewind/lib/core/ledger.js+++ b/plugins/dsh-tauri-turnrewind/lib/core/ledger.js@@ -57,6 +57,8 @@ const SCHEMA = `workspace_key TEXT NOT NULL,turn_id TEXT NOT NULL,paths_json TEXT NOT NULL,+ status TEXT NOT NULL DEFAULT 'pending',+ result_text TEXT,created_at TEXT NOT NULL,expires_at TEXT NOT NULL);@@ -92,6 +94,18 @@ export function openLedger(rootDir) {catch {// Column already exists.}+ try {+ db.exec('ALTER TABLE pending_plans ADD COLUMN status TEXT NOT NULL DEFAULT \'pending\'')+ }+ catch {+ // Column already exists.+ }+ try {+ db.exec('ALTER TABLE pending_plans ADD COLUMN result_text TEXT')+ }+ catch {+ // 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@@ -103,9 +117,14 @@ export function openLedger(rootDir) {// ignored preview can never apply hours later against a changed workspace.// ------------------------------------------------------------------const PENDING_PLAN_TTL_MS = 5 * 60 * 1000+const PENDING_PLAN_RESULT_TTL_MS = 30 * 60 * 1000export function purgeExpiredPendingPlans(db) {- db.prepare('DELETE FROM pending_plans WHERE expires_at < ?').run(new Date().toISOString())+ const now = new Date().toISOString()+ // Unacted plans die at their 5-minute mark; settled plans linger for the+ // client card to poll their outcome, then get cleaned up too.+ db.prepare('DELETE FROM pending_plans WHERE status = \'pending\' AND expires_at < ?').run(now)+ db.prepare('DELETE FROM pending_plans WHERE status <> \'pending\' AND created_at < ?').run(new Date(Date.now() - PENDING_PLAN_RESULT_TTL_MS).toISOString())}export function createPendingPlan(db, plan) {@@ -132,7 +151,7 @@ export function createPendingPlan(db, plan) {export function getPendingPlan(db, planId, sessionId, workspaceKey) {const row = db.prepare(`SELECT * FROM pending_plans- WHERE plan_id = ? AND session_id = ? AND workspace_key = ?+ WHERE plan_id = ? AND session_id = ? AND workspace_key = ? AND status = 'pending'`).get(planId, sessionId, workspaceKey)if (row === undefined)return undefined@@ -167,12 +186,34 @@ export function deletePendingPlan(db, planId, sessionId, workspaceKey) {}/** Dismissal from the ✕ button: workspace key is unknown client-side. */-export function cancelPendingPlan(db, planId, sessionId) {- const result = db.prepare('DELETE FROM pending_plans WHERE plan_id = ? AND session_id = ?')- .run(planId, sessionId)+export function markPendingPlanCancelled(db, planId, sessionId) {+ const result = db.prepare(`+ UPDATE pending_plans SET status = 'cancelled'+ WHERE plan_id = ? AND session_id = ? AND status = 'pending'+ `).run(planId, sessionId)return result.changes > 0}+/** Outcome written by the confirm route so the client card can poll it. */+export function markPendingPlanApplied(db, planId, sessionId, message) {+ db.prepare(`+ UPDATE pending_plans SET status = 'applied', result_text = ?+ WHERE plan_id = ? AND session_id = ? AND status = 'pending'+ `).run(message, planId, sessionId)+}++/** Poll face for the client card: undefined once purged, else the outcome. */+export function getPendingPlanStatus(db, planId) {+ const row = db.prepare('SELECT status, result_text, expires_at FROM pending_plans WHERE plan_id = ?').get(planId)+ if (row === undefined)+ return undefined+ if (row.status === 'pending' && row.expires_at < new Date().toISOString()) {+ db.prepare('DELETE FROM pending_plans WHERE plan_id = ? AND status = \'pending\'').run(planId)+ return undefined+ }+ return { status: row.status, resultText: row.result_text }+}+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 4f296774..7b2cee75 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 { cancelPendingPlan, claimRewindNotices, completeRedoWithNotice, completeUndoWithNotice, createOperation, createPendingPlan, deletePendingPlan, failTurn, getLatestAppliedUndo, getLatestSnapshotRef, getLatestTurnSummary, getPendingPlan, getPendingPlanRow, getTurn, insertTurn, listReversibleTurns, markTurnSnapshotMissing, openLedger, recordSkippedTurn, registerWorkspace, settleInterruptedTurn, settleNoopTurn, settleOperation, settleTurn, skipTurn } from './core/ledger.js'+import { claimRewindNotices, completeRedoWithNotice, completeUndoWithNotice, createOperation, createPendingPlan, failTurn, getLatestAppliedUndo, getLatestSnapshotRef, getLatestTurnSummary, getPendingPlan, getPendingPlanRow, getPendingPlanStatus, getTurn, insertTurn, listReversibleTurns, markPendingPlanApplied, markPendingPlanCancelled, markTurnSnapshotMissing, openLedger, recordSkippedTurn, registerWorkspace, settleInterruptedTurn, settleNoopTurn, settleOperation, settleTurn, skipTurn } from './core/ledger.js'import { classifyUndo } from './core/planner.js'const name = 'dsh-tauri-turnrewind'@@ -462,10 +462,10 @@ 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.+ // Pending-plan lifecycle: --cancel marks a parked plan cancelled; --confirm+ // validates it and falls through to execution below.if (parsed.cancel) {- const removed = deletePendingPlan(runtime.db, parsed.turnId, invocation.agent.session.id, workspaceKey)+ const removed = markPendingPlanCancelled(runtime.db, parsed.turnId, invocation.agent.session.id)return { kind: 'success', text: removed ? 'Pending undo cancelled.' : 'No pending undo plan matched (it may have expired or already run).' }}@@ -554,9 +554,6 @@ async function applyUndo(runtime, active, invocation) {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.` }- // Take the plan before writing: a double-click confirm finds the row gone.- if (parsed.confirm)- deletePendingPlan(runtime.db, parsed.turnId, invocation.agent.session.id, workspaceKey)try {const text = await executeUndoRestore(runtime, {sessionId: invocation.agent.session.id,@@ -566,6 +563,8 @@ async function applyUndo(runtime, active, invocation) {entries,skipConflicts: parsed.skipConflicts,})+ if (parsed.confirm)+ markPendingPlanApplied(runtime.db, parsed.turnId, invocation.agent.session.id, text)return { kind: 'success', text }}catch (error) {@@ -636,14 +635,13 @@ function apply(ctx, config = {}) {return [409, { error: 'the planned turn\u0027s snapshot data no longer exists — run /undo again' }]const paths = await snapshotDiff(planRuntime.store, target.before_ref, target.after_ref)if (paths.length === 0) {- deletePendingPlan(ledger, planId, sessionId, row.workspace_key)+ markPendingPlanApplied(ledger, planId, sessionId, 'No file changes were recorded for this turn.')return [200, { ok: true, message: 'No file changes were recorded for this turn.' }]}const entries = await buildPlanEntries(planRuntime, planRuntime.workspaceDir, target, paths)const conflicts = entries.filter(entry => entry.conflict)if (conflicts.length > 0)return [409, { error: `the workspace changed since the preview (${conflicts.length} conflicted file(s)) — run /undo again to refresh the plan` }]- deletePendingPlan(ledger, planId, sessionId, row.workspace_key)const message = await executeUndoRestore(planRuntime, {sessionId,workspaceKey: row.workspace_key,@@ -652,6 +650,7 @@ function apply(ctx, config = {}) {entries,skipConflicts: false,})+ markPendingPlanApplied(ledger, planId, sessionId, message)return [200, { ok: true, message }]}finally {@@ -665,13 +664,25 @@ function apply(ctx, config = {}) {const sessionId = String(body.sessionId ?? '')if (planId === '' || sessionId === '')return [400, { error: 'planId and sessionId are required' }]- const removed = cancelPendingPlan(ledger, planId, sessionId)+ const removed = markPendingPlanCancelled(ledger, planId, sessionId)return [200, { ok: true, message: removed ? 'Pending undo cancelled.' : 'No pending plan matched (it may have expired).' }]}+ function statusRoute(body, req) {+ const url = new URL(req.url ?? '/', 'http://localhost')+ const planId = String(url.searchParams.get('planId') ?? '')+ if (planId === '')+ return [400, { error: 'planId is required' }]+ const status = getPendingPlanStatus(ledger, planId)+ if (status === undefined)+ return [404, { error: 'plan expired or already applied — run /undo again' }]+ return [200, status]+ }+const routes = [jsonRoute('/api/turnrewind/confirm', confirmRoute, { mutate: true }),jsonRoute('/api/turnrewind/cancel', cancelRoute, { mutate: true }),+ jsonRoute('/api/turnrewind/status', statusRoute),]const disposers = routes.map(route => ctx.webServer.register(route))return () => disposers.map(dispose => dispose())