dsh-timeback 0.7.2 → 0.7.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -2
- package/client.js +245 -16
- package/docs/MARKET.md +2 -2
- package/index.js +30 -0
- package/package.json +1 -1
- package/src/registry.js +59 -0
- package/src/service.js +111 -3
- package/src/snapshots.js +59 -21
package/README.md
CHANGED
|
@@ -78,7 +78,8 @@ files: s0 s1 s2 s3 │ └─ C′ (new branch, context
|
|
|
78
78
|
the flat list view for long histories.
|
|
79
79
|
- **Three ways in**: the composer row pill “⏱ 时间回溯”, the clock button in the
|
|
80
80
|
conversation header, and the guide entry in the right sidebar. All three open
|
|
81
|
-
the panel; the panel's first card is the per-workspace
|
|
81
|
+
the panel; the panel's first card is the per-workspace **全选** switch and the
|
|
82
|
+
folder/file selection tree for that workspace.
|
|
82
83
|
- **Model tools**: `timeback_tree`, `timeback_checkpoint`, `timeback_rewind`, so the
|
|
83
84
|
agent can inspect its own checkpoints and self-correct when asked.
|
|
84
85
|
- The map is a pannable/zoomable canvas of cards: a lane per branch Session, one
|
|
@@ -103,7 +104,7 @@ desktop app):
|
|
|
103
104
|
```bash
|
|
104
105
|
# From npm (published: https://www.npmjs.com/package/dsh-timeback)
|
|
105
106
|
dsh plugin --profile web add dsh-timeback
|
|
106
|
-
dsh plugin --profile web add dsh-timeback@0.7.
|
|
107
|
+
dsh plugin --profile web add dsh-timeback@0.7.3 # pin a release
|
|
107
108
|
|
|
108
109
|
# Straight from GitHub (no npm release needed)
|
|
109
110
|
dsh plugin --profile web add github:<owner>/dsh-timeback
|
package/client.js
CHANGED
|
@@ -23,7 +23,7 @@ window.__ModuleLoader__.load({
|
|
|
23
23
|
const REFRESH_MS = 3000
|
|
24
24
|
const MAX_ROWS = 240
|
|
25
25
|
/** Bump together with package.json so a stale browser bundle is obvious. */
|
|
26
|
-
const BUILD = '0.7.
|
|
26
|
+
const BUILD = '0.7.3+sticky'
|
|
27
27
|
/** Set by apply(): opens another Session in the main column. */
|
|
28
28
|
let openSessionBridge = null
|
|
29
29
|
/** Set by apply(): opens the Timeback tab in the right sidebar. */
|
|
@@ -202,6 +202,13 @@ window.__ModuleLoader__.load({
|
|
|
202
202
|
'panel.workspaceEnabled': '已开启此工作区的自动记录',
|
|
203
203
|
'panel.workspaceDisabled': '已关闭此工作区的自动记录',
|
|
204
204
|
'panel.workspaceStillOn': '操作已提交,但该目录仍被其它记录设置覆盖;请在上方已开启列表里取消对应路径。',
|
|
205
|
+
'panel.selectAllHint': '只记录勾选的文件夹和文件',
|
|
206
|
+
'panel.expandFolder': '展开文件夹',
|
|
207
|
+
'panel.collapseFolder': '收起文件夹',
|
|
208
|
+
'panel.selectedCount': '已选择 {selected} / {total} 项(文件夹包含其内部文件)',
|
|
209
|
+
'panel.selectNothing': '没有选择任何路径,不会创建文件快照',
|
|
210
|
+
'panel.pathsLoading': '正在读取工作区文件…',
|
|
211
|
+
'panel.pathsFailed': '读取工作区文件失败:{error}',
|
|
205
212
|
'panel.emptyNotRecording': '此工作区尚未开启记录。勾选上方的「记录此工作区并保存文件快照」后,之后的回合才会保存检查点。',
|
|
206
213
|
'view.tree': '树视图',
|
|
207
214
|
'view.list': '列表视图',
|
|
@@ -428,8 +435,8 @@ window.__ModuleLoader__.load({
|
|
|
428
435
|
'guide.boardTitle': 'Notes board',
|
|
429
436
|
'guide.boardDescription': 'Global Markdown notes: write manually or from the session; rewinds roll them back too.',
|
|
430
437
|
'panel.recording': 'Recording',
|
|
431
|
-
'panel.recordThis': '
|
|
432
|
-
'panel.recordThisHint': '
|
|
438
|
+
'panel.recordThis': 'Select all',
|
|
439
|
+
'panel.recordThisHint': 'Check Select all to record the whole workspace; uncheck folders/files below to record only the selected parts.',
|
|
433
440
|
'panel.recordOff': 'Not recording',
|
|
434
441
|
'panel.recordOn': 'Recording',
|
|
435
442
|
'panel.recordAll': 'Plugin config capture=all records every workspace automatically',
|
|
@@ -442,6 +449,20 @@ window.__ModuleLoader__.load({
|
|
|
442
449
|
'panel.disableThis': 'Turn off',
|
|
443
450
|
'panel.workspaceEnabled': 'Recording enabled for this workspace',
|
|
444
451
|
'panel.workspaceDisabled': 'Recording disabled for this workspace',
|
|
452
|
+
'panel.selectAllHint': '只记录勾选的文件夹和文件',
|
|
453
|
+
'panel.expandFolder': '展开文件夹',
|
|
454
|
+
'panel.collapseFolder': '收起文件夹',
|
|
455
|
+
'panel.selectedCount': '已选择 {selected} / {total} 项(文件夹包含其内部文件)',
|
|
456
|
+
'panel.selectNothing': '没有选择任何路径,不会创建文件快照',
|
|
457
|
+
'panel.pathsLoading': '正在读取工作区文件…',
|
|
458
|
+
'panel.pathsFailed': '读取工作区文件失败:{error}',
|
|
459
|
+
'panel.selectAllHint': 'Only selected folders/files are recorded',
|
|
460
|
+
'panel.expandFolder': 'Expand folder',
|
|
461
|
+
'panel.collapseFolder': 'Collapse folder',
|
|
462
|
+
'panel.selectedCount': '{selected} / {total} selected (a folder includes its contents)',
|
|
463
|
+
'panel.selectNothing': 'No paths selected; no file snapshots will be created',
|
|
464
|
+
'panel.pathsLoading': 'Reading workspace files…',
|
|
465
|
+
'panel.pathsFailed': 'Cannot read workspace files: {error}',
|
|
445
466
|
'panel.emptyNotRecording': 'Recording is off for this workspace. Check “Record this workspace and keep file snapshots” above to save checkpoints from later turns.',
|
|
446
467
|
'view.tree': 'Tree',
|
|
447
468
|
'view.list': 'List',
|
|
@@ -534,6 +555,20 @@ window.__ModuleLoader__.load({
|
|
|
534
555
|
.tb-btn.primary{border-color:var(--dsw-alias-brand-primary-new-colorprimary-new-color,#4176e6);color:var(--dsw-alias-brand-primary-new-colorprimary-new-color,#7aa2ff)}
|
|
535
556
|
.tb-btn.danger{border-color:var(--dsw-alias-state-warning-primary,rgba(240,178,62,.5));color:var(--dsw-alias-state-warning-primary,#f0b23e)}
|
|
536
557
|
.tb-body{flex:1;min-height:120px;overflow:auto;padding:10px 12px 28px;display:flex;flex-direction:column;gap:8px}
|
|
558
|
+
.tb-ws-select{display:flex;flex-direction:column;gap:5px;margin:3px 0 4px}
|
|
559
|
+
.tb-ws-master{display:flex;align-items:center;gap:6px;font-size:12px;color:var(--dsw-alias-label-primary,#e6e6e6)}
|
|
560
|
+
.tb-ws-count{font-size:11px;color:var(--dsw-alias-label-secondary,#9aa0a6)}
|
|
561
|
+
.tb-ws-tree{max-height:230px;overflow:auto;border:1px solid var(--dsw-alias-border-l2,rgba(255,255,255,.14));border-radius:6px;padding:3px;background:var(--dsw-alias-bg-base,#16181d)}
|
|
562
|
+
.tb-ws-node{display:flex;align-items:center;gap:5px;padding:2px 5px;border-radius:4px;font-size:11.5px;color:var(--dsw-alias-label-primary,#e6e6e6);cursor:pointer;white-space:nowrap;user-select:none}
|
|
563
|
+
.tb-ws-node:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(255,255,255,.07))}
|
|
564
|
+
.tb-ws-node.disabled{opacity:.45;cursor:not-allowed}
|
|
565
|
+
.tb-ws-node .tb-ws-folder{opacity:.85}
|
|
566
|
+
.tb-ws-caret{appearance:none;border:0;background:transparent;color:var(--dsw-alias-label-secondary,#9aa0a6);width:14px;height:16px;padding:0;font-size:10px;line-height:1;cursor:pointer;flex:0 0 auto}
|
|
567
|
+
.tb-ws-caret:hover{color:var(--dsw-alias-label-primary,#e6e6e6)}
|
|
568
|
+
.tb-ws-caret-space{width:14px;flex:0 0 auto}
|
|
569
|
+
.tb-ws-name{cursor:default}
|
|
570
|
+
.tb-ws-node.dir .tb-ws-name{cursor:pointer}
|
|
571
|
+
.tb-ws{}
|
|
537
572
|
.tb-ws{border:1px solid var(--dsw-alias-border-l2,rgba(255,255,255,.14));border-radius:9px;padding:8px 10px;background:var(--dsw-alias-bg-layer-1,rgba(255,255,255,.03));display:flex;flex-direction:column;gap:6px}
|
|
538
573
|
.tb-ws-row{display:flex;align-items:flex-start;gap:8px;cursor:pointer}
|
|
539
574
|
.tb-ws-row.disabled{cursor:default;opacity:.65}
|
|
@@ -2409,7 +2444,7 @@ window.__ModuleLoader__.load({
|
|
|
2409
2444
|
),
|
|
2410
2445
|
)
|
|
2411
2446
|
: null,
|
|
2412
|
-
renderWorkspaceSection({ workspace: data?.workspace, gitOff, busy, t, toggleWorkspace }),
|
|
2447
|
+
renderWorkspaceSection({ workspace: data?.workspace, gitOff, busy, t, toggleWorkspace, sessionId, onWorkspaceChanged: () => setTick((value) => value + 1) }),
|
|
2413
2448
|
gitOff ? h('p', { className: 'tb-note' }, t('panel.noGit')) : h('p', { className: 'tb-note' }, t('panel.warning')),
|
|
2414
2449
|
state.error ? h('div', { className: 'tb-feedback err', role: 'alert' }, `${t('panel.error')}: ${state.error}`) : null,
|
|
2415
2450
|
state.loading && !data ? h('div', { className: 'tb-empty' }, t('panel.loading')) : null,
|
|
@@ -2538,8 +2573,202 @@ window.__ModuleLoader__.load({
|
|
|
2538
2573
|
)
|
|
2539
2574
|
}
|
|
2540
2575
|
|
|
2576
|
+
/** 全选 + folder/file checkbox selector for per-workspace snapshots. */
|
|
2577
|
+
function WorkspacePathSelector(props) {
|
|
2578
|
+
const t = typeof props?.t === 'function' ? props.t : (key) => key
|
|
2579
|
+
const sessionId = typeof props?.sessionId === 'string' ? props.sessionId : ''
|
|
2580
|
+
const workspace = props?.workspace || null
|
|
2581
|
+
const cwd = workspace?.cwd || ''
|
|
2582
|
+
const [state, setState] = React.useState({ loading: true, entries: [], excludePaths: [], error: '', saving: false })
|
|
2583
|
+
const [expanded, setExpanded] = React.useState({})
|
|
2584
|
+
const masterRef = React.useRef(null)
|
|
2585
|
+
const workspaceEnabled = workspace?.enabled === true
|
|
2586
|
+
const selectable = workspace?.mode === 'workspace' && workspace?.exists !== false && Boolean(cwd)
|
|
2587
|
+
|
|
2588
|
+
const load = async () => {
|
|
2589
|
+
if (!sessionId && !cwd) return
|
|
2590
|
+
setState((previous) => ({ ...previous, loading: true, error: '' }))
|
|
2591
|
+
try {
|
|
2592
|
+
const body = await request('action', {
|
|
2593
|
+
method: 'POST',
|
|
2594
|
+
body: { action: 'workspace-tree', ...(sessionId ? { sessionId } : {}), ...(cwd ? { cwd } : {}) },
|
|
2595
|
+
})
|
|
2596
|
+
setState({
|
|
2597
|
+
loading: false,
|
|
2598
|
+
entries: Array.isArray(body.entries) ? body.entries : [],
|
|
2599
|
+
excludePaths: Array.isArray(body.excludePaths) ? body.excludePaths : [],
|
|
2600
|
+
error: '',
|
|
2601
|
+
saving: false,
|
|
2602
|
+
})
|
|
2603
|
+
} catch (error) {
|
|
2604
|
+
setState((previous) => ({ ...previous, loading: false, error: error?.message || String(error) }))
|
|
2605
|
+
}
|
|
2606
|
+
}
|
|
2607
|
+
|
|
2608
|
+
React.useEffect(() => {
|
|
2609
|
+
load()
|
|
2610
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
2611
|
+
}, [sessionId, cwd, workspaceEnabled])
|
|
2612
|
+
|
|
2613
|
+
React.useEffect(() => {
|
|
2614
|
+
if (!masterRef.current) return
|
|
2615
|
+
const excluded = (entry) => state.excludePaths.some((value) => entry.path === value || entry.path.startsWith(`${value}/`))
|
|
2616
|
+
const selected = state.entries.filter((entry) => !excluded(entry)).length
|
|
2617
|
+
masterRef.current.indeterminate = workspaceEnabled && state.excludePaths.length > 0 && selected > 0
|
|
2618
|
+
}, [state.excludePaths, state.entries, workspaceEnabled])
|
|
2619
|
+
|
|
2620
|
+
const savePaths = async (excludePaths) => {
|
|
2621
|
+
if (state.saving) return
|
|
2622
|
+
setState((previous) => ({ ...previous, saving: true, error: '' }))
|
|
2623
|
+
try {
|
|
2624
|
+
const body = await request('action', {
|
|
2625
|
+
method: 'POST',
|
|
2626
|
+
body: {
|
|
2627
|
+
action: 'set-workspace-paths',
|
|
2628
|
+
...(sessionId ? { sessionId } : {}),
|
|
2629
|
+
...(cwd ? { cwd } : {}),
|
|
2630
|
+
excludePaths,
|
|
2631
|
+
},
|
|
2632
|
+
})
|
|
2633
|
+
const nextExcludes = Array.isArray(body.workspace?.excludePaths) ? body.workspace.excludePaths : excludePaths
|
|
2634
|
+
setState((previous) => ({ ...previous, excludePaths: nextExcludes, saving: false }))
|
|
2635
|
+
if (typeof props?.onChanged === 'function') props.onChanged(body.workspace)
|
|
2636
|
+
} catch (error) {
|
|
2637
|
+
setState((previous) => ({ ...previous, saving: false, error: error?.message || String(error) }))
|
|
2638
|
+
}
|
|
2639
|
+
}
|
|
2640
|
+
|
|
2641
|
+
const setEnabled = async (enabled) => {
|
|
2642
|
+
if (state.saving) return
|
|
2643
|
+
setState((previous) => ({ ...previous, saving: true, error: '' }))
|
|
2644
|
+
try {
|
|
2645
|
+
await request('action', {
|
|
2646
|
+
method: 'POST',
|
|
2647
|
+
body: {
|
|
2648
|
+
action: 'set-workspace',
|
|
2649
|
+
...(sessionId ? { sessionId } : {}),
|
|
2650
|
+
...(cwd ? { cwd } : {}),
|
|
2651
|
+
enabled,
|
|
2652
|
+
},
|
|
2653
|
+
})
|
|
2654
|
+
if (enabled) {
|
|
2655
|
+
await savePaths([])
|
|
2656
|
+
} else {
|
|
2657
|
+
setState((previous) => ({ ...previous, saving: false }))
|
|
2658
|
+
if (typeof props?.onChanged === 'function') props.onChanged(null)
|
|
2659
|
+
}
|
|
2660
|
+
} catch (error) {
|
|
2661
|
+
setState((previous) => ({ ...previous, saving: false, error: error?.message || String(error) }))
|
|
2662
|
+
}
|
|
2663
|
+
}
|
|
2664
|
+
|
|
2665
|
+
const toggleEntry = async (entry, checked) => {
|
|
2666
|
+
if (state.excludePaths.includes(entry.path)) {
|
|
2667
|
+
await savePaths(state.excludePaths.filter((value) => value !== entry.path))
|
|
2668
|
+
} else {
|
|
2669
|
+
const next = state.excludePaths
|
|
2670
|
+
.filter((value) => value !== entry.path && !value.startsWith(`${entry.path}/`))
|
|
2671
|
+
.concat(checked ? [] : [entry.path])
|
|
2672
|
+
await savePaths(next)
|
|
2673
|
+
}
|
|
2674
|
+
}
|
|
2675
|
+
|
|
2676
|
+
const toggleExpand = (folderPath) => {
|
|
2677
|
+
setExpanded((previous) => ({ ...previous, [folderPath]: !previous[folderPath] }))
|
|
2678
|
+
}
|
|
2679
|
+
const hiddenByCollapse = (entry) => {
|
|
2680
|
+
const segments = entry.path.split('/')
|
|
2681
|
+
for (let index = 1; index < segments.length; index += 1) {
|
|
2682
|
+
const ancestor = segments.slice(0, index).join('/')
|
|
2683
|
+
if (!expanded[ancestor]) return true
|
|
2684
|
+
}
|
|
2685
|
+
return false
|
|
2686
|
+
}
|
|
2687
|
+
const visibleEntries = state.entries.filter((entry) => !hiddenByCollapse(entry))
|
|
2688
|
+
const entries = state.entries
|
|
2689
|
+
const excludes = state.excludePaths
|
|
2690
|
+
const excludedByAncestor = (entry) => excludes.some((value) => entry.path.startsWith(`${value}/`))
|
|
2691
|
+
const selectedCount = entries.filter((entry) => !excludedByAncestor(entry) && !excludes.includes(entry.path)).length
|
|
2692
|
+
const masterDisabled = !selectable || state.loading || state.saving
|
|
2693
|
+
return h(
|
|
2694
|
+
'div',
|
|
2695
|
+
{ className: 'tb-ws-select' },
|
|
2696
|
+
h(
|
|
2697
|
+
'label',
|
|
2698
|
+
{ className: 'tb-ws-master' },
|
|
2699
|
+
h('input', {
|
|
2700
|
+
ref: masterRef,
|
|
2701
|
+
type: 'checkbox',
|
|
2702
|
+
checked: workspaceEnabled && excludes.length === 0,
|
|
2703
|
+
disabled: masterDisabled,
|
|
2704
|
+
'aria-label': t('panel.recordThis'),
|
|
2705
|
+
onChange: (event) => setEnabled(event.target.checked),
|
|
2706
|
+
}),
|
|
2707
|
+
h('span', null, t('panel.recordThis')),
|
|
2708
|
+
h('span', { className: 'tb-ws-count' }, t('panel.selectAllHint')),
|
|
2709
|
+
),
|
|
2710
|
+
state.loading
|
|
2711
|
+
? h('span', { className: 'tb-ws-hint' }, t('panel.pathsLoading'))
|
|
2712
|
+
: state.error
|
|
2713
|
+
? h('span', { className: 'tb-ws-hint err' }, format(t('panel.pathsFailed'), { error: state.error }))
|
|
2714
|
+
: [
|
|
2715
|
+
h(
|
|
2716
|
+
'span',
|
|
2717
|
+
{ className: 'tb-ws-count' },
|
|
2718
|
+
format(t('panel.selectedCount'), { selected: selectedCount, total: entries.length }),
|
|
2719
|
+
workspaceEnabled && selectedCount === 0 ? ` · ${t('panel.selectNothing')}` : '',
|
|
2720
|
+
),
|
|
2721
|
+
h(
|
|
2722
|
+
'div',
|
|
2723
|
+
{ className: 'tb-ws-tree' },
|
|
2724
|
+
...visibleEntries.map((entry) => {
|
|
2725
|
+
const inherited = excludedByAncestor(entry)
|
|
2726
|
+
const excluded = excludes.includes(entry.path)
|
|
2727
|
+
const checked = !inherited && !excluded
|
|
2728
|
+
const disabled = inherited || !workspaceEnabled || state.saving
|
|
2729
|
+
const depth = entry.path.split('/').length - 1
|
|
2730
|
+
const isDir = entry.type === 'dir'
|
|
2731
|
+
const open = expanded[entry.path] === true
|
|
2732
|
+
return h(
|
|
2733
|
+
'div',
|
|
2734
|
+
{ key: entry.path, className: `tb-ws-node${isDir ? ' dir' : ''}${disabled ? ' disabled' : ''}`, title: entry.path, style: { paddingLeft: 5 + depth * 14 } },
|
|
2735
|
+
isDir
|
|
2736
|
+
? h(
|
|
2737
|
+
'button',
|
|
2738
|
+
{
|
|
2739
|
+
type: 'button',
|
|
2740
|
+
className: 'tb-ws-caret',
|
|
2741
|
+
title: open ? t('panel.collapseFolder') : t('panel.expandFolder'),
|
|
2742
|
+
'aria-expanded': open,
|
|
2743
|
+
onClick: () => toggleExpand(entry.path),
|
|
2744
|
+
},
|
|
2745
|
+
open ? '▾' : '▸',
|
|
2746
|
+
)
|
|
2747
|
+
: h('span', { className: 'tb-ws-caret-space' }),
|
|
2748
|
+
h('input', {
|
|
2749
|
+
type: 'checkbox',
|
|
2750
|
+
checked,
|
|
2751
|
+
disabled,
|
|
2752
|
+
onChange: (event) => toggleEntry(entry, event.target.checked),
|
|
2753
|
+
}),
|
|
2754
|
+
h('span', { className: 'tb-ws-folder' }, isDir ? '📁' : '📄'),
|
|
2755
|
+
h(
|
|
2756
|
+
'span',
|
|
2757
|
+
{
|
|
2758
|
+
className: 'tb-ws-name',
|
|
2759
|
+
onClick: isDir ? () => toggleExpand(entry.path) : undefined,
|
|
2760
|
+
},
|
|
2761
|
+
entry.path,
|
|
2762
|
+
),
|
|
2763
|
+
)
|
|
2764
|
+
}),
|
|
2765
|
+
),
|
|
2766
|
+
],
|
|
2767
|
+
)
|
|
2768
|
+
}
|
|
2769
|
+
|
|
2541
2770
|
/** Draw the per-workspace recording switch and the enabled-workspace list. */
|
|
2542
|
-
function renderWorkspaceSection({ workspace, gitOff, busy, t, toggleWorkspace }) {
|
|
2771
|
+
function renderWorkspaceSection({ workspace, gitOff, busy, t, toggleWorkspace, sessionId, onWorkspaceChanged }) {
|
|
2543
2772
|
if (!workspace) return null
|
|
2544
2773
|
const cwd = workspace.cwd
|
|
2545
2774
|
const mode = workspace.mode
|
|
@@ -2558,17 +2787,8 @@ window.__ModuleLoader__.load({
|
|
|
2558
2787
|
'div',
|
|
2559
2788
|
{ className: 'tb-ws' },
|
|
2560
2789
|
h(
|
|
2561
|
-
'
|
|
2562
|
-
{ className:
|
|
2563
|
-
h('input', {
|
|
2564
|
-
type: 'checkbox',
|
|
2565
|
-
checked,
|
|
2566
|
-
disabled: !canToggle,
|
|
2567
|
-
'aria-label': t('panel.recordThis'),
|
|
2568
|
-
onChange: (event) => {
|
|
2569
|
-
if (canToggle) toggleWorkspace(event.target.checked)
|
|
2570
|
-
},
|
|
2571
|
-
}),
|
|
2790
|
+
'div',
|
|
2791
|
+
{ className: 'tb-ws-row', title: reason },
|
|
2572
2792
|
h(
|
|
2573
2793
|
'span',
|
|
2574
2794
|
{ className: 'tb-ws-text' },
|
|
@@ -2577,6 +2797,14 @@ window.__ModuleLoader__.load({
|
|
|
2577
2797
|
h('span', { className: 'tb-ws-hint' }, reason),
|
|
2578
2798
|
),
|
|
2579
2799
|
),
|
|
2800
|
+
mode === 'workspace' && cwd
|
|
2801
|
+
? h(WorkspacePathSelector, {
|
|
2802
|
+
sessionId,
|
|
2803
|
+
workspace,
|
|
2804
|
+
t,
|
|
2805
|
+
onChanged: typeof onWorkspaceChanged === 'function' ? onWorkspaceChanged : undefined,
|
|
2806
|
+
})
|
|
2807
|
+
: null,
|
|
2580
2808
|
mode === 'workspace' && workspace.enabledWorkspaces?.length > 0
|
|
2581
2809
|
? h(
|
|
2582
2810
|
'div',
|
|
@@ -4999,6 +5227,7 @@ window.__ModuleLoader__.load({
|
|
|
4999
5227
|
window.__TIMEBACK_TEST__.stripMarkdown = stripMarkdown
|
|
5000
5228
|
window.__TIMEBACK_TEST__.boardEdgePath = boardEdgePath
|
|
5001
5229
|
window.__TIMEBACK_TEST__.MarkdownEditor = MarkdownEditor
|
|
5230
|
+
window.__TIMEBACK_TEST__.WorkspacePathSelector = WorkspacePathSelector
|
|
5002
5231
|
window.__TIMEBACK_TEST__.markdownToEditorHtml = markdownToEditorHtml
|
|
5003
5232
|
window.__TIMEBACK_TEST__.domToMarkdown = domToMarkdown
|
|
5004
5233
|
}
|
package/docs/MARKET.md
CHANGED
|
@@ -78,12 +78,12 @@ dshmarket;要让所有人的 dshmarket 搜到,必须走下一节的公共目
|
|
|
78
78
|
|
|
79
79
|
## 4. npm(已发布 0.6.0)
|
|
80
80
|
|
|
81
|
-
`dsh-timeback@0.7.
|
|
81
|
+
`dsh-timeback@0.7.3` 已发布到官方 npm(<https://www.npmjs.com/package/dsh-timeback>),
|
|
82
82
|
用户可以直接安装/固定版本:
|
|
83
83
|
|
|
84
84
|
```bash
|
|
85
85
|
dsh plugin --profile web add dsh-timeback
|
|
86
|
-
dsh plugin --profile web add dsh-timeback@0.7.
|
|
86
|
+
dsh plugin --profile web add dsh-timeback@0.7.3
|
|
87
87
|
```
|
|
88
88
|
|
|
89
89
|
awesome 目录 CI 会从 npm 自动补充映射,之后市场安装和更新会走 registry。发布流程参考:
|
package/index.js
CHANGED
|
@@ -284,6 +284,8 @@ export function apply(ctx, rawConfig) {
|
|
|
284
284
|
'checkpoint',
|
|
285
285
|
'status',
|
|
286
286
|
'set-workspace',
|
|
287
|
+
'set-workspace-paths',
|
|
288
|
+
'workspace-tree',
|
|
287
289
|
'workspaces',
|
|
288
290
|
'prune',
|
|
289
291
|
'notes-list',
|
|
@@ -368,6 +370,34 @@ export function apply(ctx, rawConfig) {
|
|
|
368
370
|
)
|
|
369
371
|
return
|
|
370
372
|
}
|
|
373
|
+
if (action === 'workspace-tree') {
|
|
374
|
+
writeJson(
|
|
375
|
+
res,
|
|
376
|
+
200,
|
|
377
|
+
await service.listWorkspaceTree({
|
|
378
|
+
sessionId: typeof body.sessionId === 'string' && body.sessionId !== '' ? body.sessionId : undefined,
|
|
379
|
+
cwd: typeof body.cwd === 'string' && body.cwd !== '' ? body.cwd : undefined,
|
|
380
|
+
}),
|
|
381
|
+
req,
|
|
382
|
+
)
|
|
383
|
+
return
|
|
384
|
+
}
|
|
385
|
+
if (action === 'set-workspace-paths') {
|
|
386
|
+
writeJson(
|
|
387
|
+
res,
|
|
388
|
+
200,
|
|
389
|
+
{
|
|
390
|
+
ok: true,
|
|
391
|
+
...(await service.setWorkspacePaths({
|
|
392
|
+
sessionId: typeof body.sessionId === 'string' && body.sessionId !== '' ? body.sessionId : undefined,
|
|
393
|
+
cwd: typeof body.cwd === 'string' && body.cwd !== '' ? body.cwd : undefined,
|
|
394
|
+
excludePaths: Array.isArray(body.excludePaths) ? body.excludePaths : [],
|
|
395
|
+
})),
|
|
396
|
+
},
|
|
397
|
+
req,
|
|
398
|
+
)
|
|
399
|
+
return
|
|
400
|
+
}
|
|
371
401
|
if (action === 'board-canvas') {
|
|
372
402
|
writeJson(res, 200, await service.saveBoardCanvas(body.canvas ?? {}), req)
|
|
373
403
|
return
|
package/package.json
CHANGED
package/src/registry.js
CHANGED
|
@@ -36,6 +36,30 @@ export function workspaceContains(root, cwd) {
|
|
|
36
36
|
return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative))
|
|
37
37
|
}
|
|
38
38
|
|
|
39
|
+
/** Normalize user-picked excluded paths: repo-relative, POSIX, ancestor-collapsed. */
|
|
40
|
+
export function normalizeExcludePaths(list) {
|
|
41
|
+
if (!Array.isArray(list)) return []
|
|
42
|
+
const seen = new Set()
|
|
43
|
+
const paths = []
|
|
44
|
+
for (const raw of list.slice(0, 1000)) {
|
|
45
|
+
if (typeof raw !== 'string' || raw === '') continue
|
|
46
|
+
const normalized = raw.replace(/\\/g, '/').replace(/^\.\//, '').replace(/\/+$/, '')
|
|
47
|
+
if (!isSafeExclude(normalized)) continue
|
|
48
|
+
if (seen.has(normalized)) continue
|
|
49
|
+
seen.add(normalized)
|
|
50
|
+
paths.push(normalized)
|
|
51
|
+
}
|
|
52
|
+
// A parent exclusion already covers descendants.
|
|
53
|
+
return paths.filter((candidate) => !paths.some((other) => other !== candidate && (candidate === other || candidate.startsWith(`${other}/`)))).sort()
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Whether a workspace-relative exclusion path is safe to pass to git. */
|
|
57
|
+
function isSafeExclude(value) {
|
|
58
|
+
if (!value || value.startsWith('/') || value.startsWith(':')) return false
|
|
59
|
+
if (/^[A-Za-z]:[\\/]/.test(value)) return false
|
|
60
|
+
return !value.split('/').some((segment) => segment === '..' || segment === '')
|
|
61
|
+
}
|
|
62
|
+
|
|
39
63
|
/** One registry failure with a stable code for the UI. */
|
|
40
64
|
export class RegistryError extends Error {
|
|
41
65
|
constructor(message, code = 'registry/failed') {
|
|
@@ -241,6 +265,38 @@ export class CheckpointRegistry {
|
|
|
241
265
|
.sort((left, right) => left.path.localeCompare(right.path))
|
|
242
266
|
}
|
|
243
267
|
|
|
268
|
+
/**
|
|
269
|
+
* Recording selection for the enabled workspace root covering `cwd`.
|
|
270
|
+
* @param cwd - absolute directory.
|
|
271
|
+
* @returns {{root: string|null, excludePaths: string[]}}
|
|
272
|
+
*/
|
|
273
|
+
workspaceSelection(cwd) {
|
|
274
|
+
const key = workspaceKey(cwd)
|
|
275
|
+
let root = null
|
|
276
|
+
for (const workspacePath of Object.keys(this.state?.workspaces ?? {})) {
|
|
277
|
+
if (!workspaceContains(workspacePath, key)) continue
|
|
278
|
+
if (root === null || workspacePath.length > root.length) root = workspacePath
|
|
279
|
+
}
|
|
280
|
+
if (root === null) return { root: null, excludePaths: [] }
|
|
281
|
+
return { root, excludePaths: [...(this.state?.workspaces?.[root]?.excludePaths ?? [])] }
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* Persist which paths of an enabled workspace are excluded from snapshots.
|
|
286
|
+
* @param cwd - absolute directory.
|
|
287
|
+
* @param excludePaths - workspace-relative paths to exclude (empty = all).
|
|
288
|
+
* @returns {Promise<{path: string, excludePaths: string[]}>}
|
|
289
|
+
*/
|
|
290
|
+
async setWorkspaceExcludePaths(cwd, excludePaths) {
|
|
291
|
+
await this.open()
|
|
292
|
+
const key = workspaceKey(cwd)
|
|
293
|
+
this.state.workspaces ||= {}
|
|
294
|
+
if (!this.state.workspaces[key]) this.state.workspaces[key] = { enabledAt: this.now() }
|
|
295
|
+
this.state.workspaces[key].excludePaths = normalizeExcludePaths(excludePaths)
|
|
296
|
+
await this.flush()
|
|
297
|
+
return { path: key, excludePaths: [...this.state.workspaces[key].excludePaths] }
|
|
298
|
+
}
|
|
299
|
+
|
|
244
300
|
/**
|
|
245
301
|
* The most specific recording policy that covers `cwd`: the longest matching
|
|
246
302
|
* enabled root or explicitly disabled subdirectory.
|
|
@@ -355,6 +411,9 @@ function normalizeState(parsed) {
|
|
|
355
411
|
}
|
|
356
412
|
if (!record || typeof record !== 'object') map[workspacePath] = map === state.workspaces ? { enabledAt: Date.now() } : { disabledAt: Date.now() }
|
|
357
413
|
}
|
|
414
|
+
for (const record of Object.values(state.workspaces)) {
|
|
415
|
+
record.excludePaths = normalizeExcludePaths(record.excludePaths)
|
|
416
|
+
}
|
|
358
417
|
}
|
|
359
418
|
// A path cannot be both enabled and excluded; latest write wins on load.
|
|
360
419
|
for (const workspacePath of Object.keys(state.excluded)) {
|
package/src/service.js
CHANGED
|
@@ -147,6 +147,25 @@ export class TimebackService {
|
|
|
147
147
|
return this.registry.isWorkspaceEnabled(await this.canonicalDir(cwd))
|
|
148
148
|
}
|
|
149
149
|
|
|
150
|
+
/**
|
|
151
|
+
* Translate the workspace-root selection onto one capture directory.
|
|
152
|
+
* @param cwd - directory whose tree is snapshotted.
|
|
153
|
+
* @returns {Promise<{root: string|null, excludePaths: string[], excludedAll: boolean}>}
|
|
154
|
+
*/
|
|
155
|
+
async selectionFor(cwd) {
|
|
156
|
+
await this.registry.open()
|
|
157
|
+
const selection = this.registry.workspaceSelection(cwd)
|
|
158
|
+
if (!selection.root || selection.excludePaths.length === 0) return { ...selection, excludedAll: false }
|
|
159
|
+
const relative = path.relative(selection.root, await this.canonicalDir(cwd)).split(path.sep).join('/')
|
|
160
|
+
if (relative === '' || relative === '.') return { ...selection, excludedAll: false }
|
|
161
|
+
const translated = []
|
|
162
|
+
for (const excluded of selection.excludePaths) {
|
|
163
|
+
if (excluded === relative || relative.startsWith(`${excluded}/`)) return { ...selection, excludePaths: [], excludedAll: true }
|
|
164
|
+
if (excluded.startsWith(`${relative}/`)) translated.push(excluded.slice(relative.length + 1))
|
|
165
|
+
}
|
|
166
|
+
return { ...selection, excludePaths: translated, excludedAll: false }
|
|
167
|
+
}
|
|
168
|
+
|
|
150
169
|
/**
|
|
151
170
|
* Describe the workspace of one directory for the panel.
|
|
152
171
|
* @param cwd - absolute directory, or null when the session has none.
|
|
@@ -164,15 +183,87 @@ export class TimebackService {
|
|
|
164
183
|
}
|
|
165
184
|
root = this.registry.workspaceRootFor(await this.canonicalDir(cwd))
|
|
166
185
|
}
|
|
186
|
+
const selection = cwd ? this.registry.workspaceSelection(await this.canonicalDir(cwd)) : { root: null, excludePaths: [] }
|
|
167
187
|
return {
|
|
168
188
|
cwd: cwd ?? null,
|
|
169
189
|
exists,
|
|
170
190
|
root,
|
|
191
|
+
selectionRoot: selection.root,
|
|
171
192
|
mode: this.captureMode,
|
|
172
193
|
enabled: await this.recordingEnabled(cwd),
|
|
194
|
+
excludePaths: [...selection.excludePaths],
|
|
173
195
|
enabledWorkspaces: this.captureMode === 'workspace' ? this.registry.workspaces() : [],
|
|
174
|
-
|
|
196
|
+
// Only show opt-outs that actually override an enabled parent workspace;
|
|
197
|
+
// a plain "recording is off" workspace is the default state, not an
|
|
198
|
+
// interesting subdirectory override.
|
|
199
|
+
excludedWorkspaces:
|
|
200
|
+
this.captureMode === 'workspace'
|
|
201
|
+
? this.registry.excludedWorkspaces().filter((entry) =>
|
|
202
|
+
this.registry.workspaces().some((root) => root.path !== entry.path && workspaceContains(root.path, entry.path)),
|
|
203
|
+
)
|
|
204
|
+
: [],
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* List the files/directories the user can choose for one workspace.
|
|
210
|
+
* @param input - `{ sessionId?, cwd? }`.
|
|
211
|
+
* @returns {Promise<object>} flat tree plus the current selection.
|
|
212
|
+
*/
|
|
213
|
+
async listWorkspaceTree(input) {
|
|
214
|
+
await this.start()
|
|
215
|
+
const cwd = await this.resolveWorkspace(input ?? {})
|
|
216
|
+
const selection = this.registry.workspaceSelection(await this.canonicalDir(cwd))
|
|
217
|
+
const root = selection.root ?? cwd
|
|
218
|
+
const skip = new Set(['.git', 'node_modules', '.venv', 'venv', '__pycache__', '.pytest_cache', '.cache'])
|
|
219
|
+
const entries = []
|
|
220
|
+
const walk = async (dir, prefix, depth) => {
|
|
221
|
+
if (depth > 10 || entries.length >= 2000) return
|
|
222
|
+
let items
|
|
223
|
+
try {
|
|
224
|
+
items = await fs.readdir(dir, { withFileTypes: true })
|
|
225
|
+
} catch {
|
|
226
|
+
return
|
|
227
|
+
}
|
|
228
|
+
items.sort((left, right) => Number(right.isDirectory()) - Number(left.isDirectory()) || left.name.localeCompare(right.name))
|
|
229
|
+
for (const item of items) {
|
|
230
|
+
if (entries.length >= 2000) return
|
|
231
|
+
if (skip.has(item.name)) continue
|
|
232
|
+
const relative = prefix === '' ? item.name : `${prefix}/${item.name}`
|
|
233
|
+
if (item.isDirectory()) {
|
|
234
|
+
entries.push({ path: relative, type: 'dir' })
|
|
235
|
+
await walk(path.join(dir, item.name), relative, depth + 1)
|
|
236
|
+
} else {
|
|
237
|
+
entries.push({ path: relative, type: 'file' })
|
|
238
|
+
}
|
|
239
|
+
}
|
|
175
240
|
}
|
|
241
|
+
await walk(root, '', 0)
|
|
242
|
+
return { ok: true, cwd, root, excludePaths: [...selection.excludePaths], entries }
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* Persist the files/directories selected for snapshots.
|
|
247
|
+
* @param input - `{ sessionId?, cwd?, excludePaths }`.
|
|
248
|
+
* @returns {Promise<object>} the updated workspace state.
|
|
249
|
+
*/
|
|
250
|
+
async setWorkspacePaths(input) {
|
|
251
|
+
await this.start()
|
|
252
|
+
const resolved = await this.resolveWorkspace(input ?? {})
|
|
253
|
+
if (this.captureMode !== 'workspace') {
|
|
254
|
+
throw new TimebackError(
|
|
255
|
+
this.captureMode === 'off'
|
|
256
|
+
? '插件配置 capture=off 已关闭自动记录;请修改插件配置后再开启'
|
|
257
|
+
: '插件配置 capture=all 已对所有工作区开启记录,无需单独勾选',
|
|
258
|
+
'timeback/capture-mode-fixed',
|
|
259
|
+
)
|
|
260
|
+
}
|
|
261
|
+
await this.registry.open()
|
|
262
|
+
const root = this.registry.workspaceRootFor(await this.canonicalDir(resolved)) ?? resolved
|
|
263
|
+
await this.registry.setWorkspaceEnabled(root, true)
|
|
264
|
+
const saved = await this.registry.setWorkspaceExcludePaths(root, input?.excludePaths)
|
|
265
|
+
const workspace = await this.workspaceStatus(resolved)
|
|
266
|
+
return { workspace, workspaces: workspace.enabledWorkspaces, ...saved }
|
|
176
267
|
}
|
|
177
268
|
|
|
178
269
|
/** Persist the reason a workspace could not be snapshotted for this Session. */
|
|
@@ -315,14 +406,21 @@ export class TimebackService {
|
|
|
315
406
|
if (!cwd) return null
|
|
316
407
|
const checkpointId = `cp-${randomUUID()}`
|
|
317
408
|
await this.registry.ensureSession({ sessionId: record.sessionId, cwd })
|
|
409
|
+
const selection = await this.selectionFor(cwd)
|
|
410
|
+
if (selection.excludedAll) return null
|
|
318
411
|
const snapshot = await this.store.capture({
|
|
319
412
|
cwd,
|
|
320
413
|
sessionId: record.sessionId,
|
|
321
414
|
checkpointId,
|
|
322
415
|
previousTree: record.beforeCheckpoint?.snapshot?.tree ?? record.lastTree,
|
|
416
|
+
excludePaths: selection.excludePaths,
|
|
323
417
|
signal: this.lifetime?.signal,
|
|
324
418
|
})
|
|
325
|
-
const result = {
|
|
419
|
+
const result = {
|
|
420
|
+
checkpointId,
|
|
421
|
+
snapshot: { tree: snapshot.tree, cwd: snapshot.cwd, repoId: snapshot.repoId, excludePaths: selection.excludePaths },
|
|
422
|
+
files: snapshot.files,
|
|
423
|
+
}
|
|
326
424
|
record.afterSnapshot = result
|
|
327
425
|
return result
|
|
328
426
|
})().catch((error) => {
|
|
@@ -341,11 +439,18 @@ export class TimebackService {
|
|
|
341
439
|
const sessionId = String(input.session.id)
|
|
342
440
|
await this.registry.ensureSession({ sessionId, cwd: input.cwd })
|
|
343
441
|
const checkpointId = `cp-${randomUUID()}`
|
|
442
|
+
const selection = Array.isArray(input.excludePaths)
|
|
443
|
+
? { ...(await this.selectionFor(input.cwd)), excludePaths: input.excludePaths, excludedAll: false }
|
|
444
|
+
: await this.selectionFor(input.cwd)
|
|
445
|
+
if (selection.excludedAll) {
|
|
446
|
+
throw new TimebackError('当前工作区没有选中任何要记录的路径', 'timeback/selection-empty')
|
|
447
|
+
}
|
|
344
448
|
const snapshot = await this.store.capture({
|
|
345
449
|
cwd: input.cwd,
|
|
346
450
|
sessionId,
|
|
347
451
|
checkpointId,
|
|
348
452
|
previousTree: input.previousTree,
|
|
453
|
+
excludePaths: selection.excludePaths,
|
|
349
454
|
signal: this.lifetime?.signal,
|
|
350
455
|
})
|
|
351
456
|
const checkpoint = await this.registry.addCheckpoint(sessionId, {
|
|
@@ -355,7 +460,7 @@ export class TimebackService {
|
|
|
355
460
|
seq: input.seq,
|
|
356
461
|
label: input.label,
|
|
357
462
|
prompt: input.prompt,
|
|
358
|
-
snapshot: { tree: snapshot.tree, cwd: snapshot.cwd, repoId: snapshot.repoId },
|
|
463
|
+
snapshot: { tree: snapshot.tree, cwd: snapshot.cwd, repoId: snapshot.repoId, excludePaths: selection.excludePaths },
|
|
359
464
|
files: snapshot.files,
|
|
360
465
|
boardVersion: this.notes?.version ?? null,
|
|
361
466
|
})
|
|
@@ -583,6 +688,7 @@ export class TimebackService {
|
|
|
583
688
|
const workingSession = this.liveSession(sessionId)
|
|
584
689
|
if (!workingSession) throw new TimebackError('源会话未打开,无法获取当前工作区状态;请先打开该会话再回退文件', 'timeback/source-closed')
|
|
585
690
|
const record = this.records.get(sessionId)
|
|
691
|
+
const checkpointSelection = Array.isArray(checkpoint.snapshot?.excludePaths) ? checkpoint.snapshot.excludePaths : []
|
|
586
692
|
try {
|
|
587
693
|
safety = await this.capture({
|
|
588
694
|
session: workingSession,
|
|
@@ -593,6 +699,7 @@ export class TimebackService {
|
|
|
593
699
|
label: null,
|
|
594
700
|
prompt: null,
|
|
595
701
|
previousTree: record?.lastTree ?? null,
|
|
702
|
+
excludePaths: checkpointSelection,
|
|
596
703
|
})
|
|
597
704
|
} catch (error) {
|
|
598
705
|
const wrapped = this.toUserError(error)
|
|
@@ -603,6 +710,7 @@ export class TimebackService {
|
|
|
603
710
|
cwd,
|
|
604
711
|
targetTree: checkpoint.snapshot.tree,
|
|
605
712
|
currentTree: safety?.snapshot?.tree,
|
|
713
|
+
excludePaths: checkpointSelection,
|
|
606
714
|
deleteExtra: this.config.restoreDeletesExtra,
|
|
607
715
|
signal: this.lifetime?.signal,
|
|
608
716
|
})
|
package/src/snapshots.js
CHANGED
|
@@ -45,6 +45,28 @@ function isSafeRelative(relative) {
|
|
|
45
45
|
return !relative.split(/[\\/]/).some((segment) => segment === '..' || segment === '')
|
|
46
46
|
}
|
|
47
47
|
|
|
48
|
+
/** Keep only work-tree-relative paths that are safe as literal git pathspecs. */
|
|
49
|
+
function sanitizeExcludePaths(list) {
|
|
50
|
+
if (!Array.isArray(list)) return []
|
|
51
|
+
const out = []
|
|
52
|
+
const seen = new Set()
|
|
53
|
+
for (const raw of list) {
|
|
54
|
+
if (typeof raw !== 'string') continue
|
|
55
|
+
const value = raw.replace(/\\/g, '/').replace(/^\.\//, '').replace(/\/+$/, '')
|
|
56
|
+
if (!isSafeRelative(value) || value.startsWith(':') || seen.has(value)) continue
|
|
57
|
+
seen.add(value)
|
|
58
|
+
out.push(value)
|
|
59
|
+
}
|
|
60
|
+
return out.filter((candidate) => !out.some((other) => other !== candidate && candidate.startsWith(`${other}/`))).sort()
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Literal pathspecs restricting a git operation to the selected paths. */
|
|
64
|
+
function selectionPathspecs(excludePaths) {
|
|
65
|
+
const excludes = sanitizeExcludePaths(excludePaths)
|
|
66
|
+
if (excludes.length === 0) return null
|
|
67
|
+
return ['.', ...excludes.map((value) => `:(exclude,literal)${value}`)]
|
|
68
|
+
}
|
|
69
|
+
|
|
48
70
|
/** Hard cap a list of paths. */
|
|
49
71
|
function capPaths(paths) {
|
|
50
72
|
return paths.length <= PATH_LIST_LIMIT ? paths : paths.slice(0, PATH_LIST_LIMIT)
|
|
@@ -189,13 +211,16 @@ export class SnapshotStore {
|
|
|
189
211
|
* consume time and disk.
|
|
190
212
|
* @returns {Promise<{ok: boolean, files?: number, reason?: string}>}
|
|
191
213
|
*/
|
|
192
|
-
async probeWorkspace(repo, signal) {
|
|
193
|
-
const
|
|
214
|
+
async probeWorkspace(repo, signal, excludePaths = []) {
|
|
215
|
+
const excludes = sanitizeExcludePaths(excludePaths)
|
|
216
|
+
const cacheKey = `${repo.id}:${excludes.join('|')}`
|
|
217
|
+
const cached = this.probes.get(cacheKey)
|
|
194
218
|
if (cached) return cached
|
|
195
219
|
const env = { GIT_INDEX_FILE: path.join(repo.gitDir, 'probe.index') }
|
|
196
220
|
let verdict
|
|
197
221
|
try {
|
|
198
|
-
const
|
|
222
|
+
const pathspecs = selectionPathspecs(excludes)
|
|
223
|
+
const dryRun = await this.git(repo, ['--work-tree', repo.cwd, 'add', '-A', '--ignore-errors', '--dry-run', '--', ...(pathspecs ?? ['.'])], {
|
|
199
224
|
env,
|
|
200
225
|
signal,
|
|
201
226
|
timeoutMs: this.probeTimeoutMs,
|
|
@@ -214,8 +239,8 @@ export class SnapshotStore {
|
|
|
214
239
|
} finally {
|
|
215
240
|
await fs.rm(path.join(repo.gitDir, 'probe.index'), { force: true }).catch(() => {})
|
|
216
241
|
}
|
|
217
|
-
this.probes.set(
|
|
218
|
-
if (!verdict.ok) {
|
|
242
|
+
this.probes.set(cacheKey, verdict)
|
|
243
|
+
if (!verdict.ok && excludes.length === 0) {
|
|
219
244
|
this.blocked.set(repo.cwd, verdict)
|
|
220
245
|
this.logger?.warn?.(
|
|
221
246
|
`timeback: refusing to snapshot ${repo.cwd}: ${verdict.reason}` +
|
|
@@ -248,20 +273,31 @@ export class SnapshotStore {
|
|
|
248
273
|
* @param signal - cancellation.
|
|
249
274
|
* @returns {Promise<string>} tree object id.
|
|
250
275
|
*/
|
|
251
|
-
async treeOfHead(repo, signal) {
|
|
276
|
+
async treeOfHead(repo, signal, excludePaths = []) {
|
|
252
277
|
await this.clearStaleLock(repo.gitDir)
|
|
253
|
-
const
|
|
254
|
-
|
|
255
|
-
//
|
|
256
|
-
|
|
257
|
-
if (
|
|
258
|
-
|
|
278
|
+
const pathspecs = selectionPathspecs(excludePaths)
|
|
279
|
+
// A selection needs a fresh index, otherwise files outside the selection
|
|
280
|
+
// would survive from the previous full capture.
|
|
281
|
+
const indexPath = pathspecs ? path.join(repo.gitDir, 'index.filtered') : path.join(repo.gitDir, 'index')
|
|
282
|
+
if (pathspecs) await fs.rm(indexPath, { force: true })
|
|
283
|
+
const env = { GIT_INDEX_FILE: indexPath }
|
|
284
|
+
try {
|
|
285
|
+
const args = ['--work-tree', repo.cwd, 'add', '-A', '--ignore-errors']
|
|
286
|
+
if (pathspecs) args.push('--', ...pathspecs)
|
|
287
|
+
const add = await this.git(repo, args, { env, signal })
|
|
288
|
+
// Exit code 1 means individual unreadable entries were skipped; the tree
|
|
289
|
+
// built from everything else is still usable.
|
|
290
|
+
if (add.exitCode !== 0 && add.exitCode !== 1) {
|
|
291
|
+
throw new SnapshotError(`快照失败(git add):${add.stderr.trim()}`, 'snapshot/add-failed')
|
|
292
|
+
}
|
|
293
|
+
const write = await this.git(repo, ['write-tree'], { env, signal })
|
|
294
|
+
if (write.exitCode !== 0) throw new SnapshotError(`快照失败(write-tree):${write.stderr.trim()}`, 'snapshot/tree-failed')
|
|
295
|
+
const tree = write.stdout.trim()
|
|
296
|
+
if (!/^[0-9a-f]{40,64}$/.test(tree)) throw new SnapshotError('快照失败:git 返回了无效的 tree id', 'snapshot/tree-invalid')
|
|
297
|
+
return tree
|
|
298
|
+
} finally {
|
|
299
|
+
if (pathspecs) await fs.rm(indexPath, { force: true }).catch(() => {})
|
|
259
300
|
}
|
|
260
|
-
const write = await this.git(repo, ['write-tree'], { env, signal })
|
|
261
|
-
if (write.exitCode !== 0) throw new SnapshotError(`快照失败(write-tree):${write.stderr.trim()}`, 'snapshot/tree-failed')
|
|
262
|
-
const tree = write.stdout.trim()
|
|
263
|
-
if (!/^[0-9a-f]{40,64}$/.test(tree)) throw new SnapshotError('快照失败:git 返回了无效的 tree id', 'snapshot/tree-invalid')
|
|
264
|
-
return tree
|
|
265
301
|
}
|
|
266
302
|
|
|
267
303
|
/**
|
|
@@ -273,7 +309,8 @@ export class SnapshotStore {
|
|
|
273
309
|
return this.exclusive(async () => {
|
|
274
310
|
await this.available()
|
|
275
311
|
const repo = await this.ensureRepo(options.cwd, options.signal)
|
|
276
|
-
const
|
|
312
|
+
const excludePaths = sanitizeExcludePaths(options.excludePaths)
|
|
313
|
+
const blocked = excludePaths.length === 0 ? this.blocked.get(repo.cwd) : undefined
|
|
277
314
|
if (blocked) {
|
|
278
315
|
throw new SnapshotError(
|
|
279
316
|
`工作区过大,未创建文件快照(${blocked.reason})。可在插件配置里提高 maxFiles 或添加 exclude 规则。`,
|
|
@@ -281,7 +318,7 @@ export class SnapshotStore {
|
|
|
281
318
|
{ files: blocked.files ?? null, maxFiles: this.maxFiles },
|
|
282
319
|
)
|
|
283
320
|
}
|
|
284
|
-
const probe = await this.probeWorkspace(repo, options.signal)
|
|
321
|
+
const probe = await this.probeWorkspace(repo, options.signal, excludePaths)
|
|
285
322
|
if (!probe.ok) {
|
|
286
323
|
throw new SnapshotError(
|
|
287
324
|
`工作区过大,未创建文件快照(${probe.reason})。可在插件配置里提高 maxFiles 或添加 exclude 规则。`,
|
|
@@ -289,7 +326,7 @@ export class SnapshotStore {
|
|
|
289
326
|
{ files: probe.files ?? null, maxFiles: this.maxFiles },
|
|
290
327
|
)
|
|
291
328
|
}
|
|
292
|
-
const tree = await this.treeOfHead(repo, options.signal)
|
|
329
|
+
const tree = await this.treeOfHead(repo, options.signal, excludePaths)
|
|
293
330
|
const ref = `refs/timeback/${refComponent(options.sessionId)}/${refComponent(options.checkpointId)}`
|
|
294
331
|
const updated = await this.git(repo, ['update-ref', ref, tree], { signal: options.signal })
|
|
295
332
|
if (updated.exitCode !== 0) {
|
|
@@ -383,7 +420,8 @@ export class SnapshotStore {
|
|
|
383
420
|
if (type.exitCode !== 0 || type.stdout.trim() !== 'tree') {
|
|
384
421
|
throw new SnapshotError('目标文件快照不存在或已损坏', 'snapshot/target-missing')
|
|
385
422
|
}
|
|
386
|
-
const
|
|
423
|
+
const excludePaths = sanitizeExcludePaths(options.excludePaths)
|
|
424
|
+
const currentTree = options.currentTree ?? (await this.treeOfHead(repo, options.signal, excludePaths))
|
|
387
425
|
if (currentTree === options.targetTree) {
|
|
388
426
|
return { noop: true, restored: 0, deleted: 0, skipped: 0, gitlinks: 0, failed: [], restoredPaths: [], deletedPaths: [] }
|
|
389
427
|
}
|