@celljs/ta-changes 0.0.0-stage → 4.8.0

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.
@@ -0,0 +1,14 @@
1
+ import { join } from 'node:path';
2
+ import type { TaExtensionHost, TaPackageService } from '@celljs/ta-protocol';
3
+ import { BlobStore } from './blob-store';
4
+ import { DefaultChangesService } from './changes-service';
5
+
6
+ /**
7
+ * The server side of the package (`pi.host`): it keeps the contents of the files replies changed, under
8
+ * `<agentDir>/changes/`, and takes the changes of a reply back for the page through the session's pi extension.
9
+ */
10
+ export default function activate(host: TaExtensionHost): TaPackageService {
11
+ const blobs = new BlobStore(join(host.agentDir, 'changes'));
12
+ void blobs.prune().catch(() => undefined);
13
+ return new DefaultChangesService(host, blobs);
14
+ }
@@ -0,0 +1,59 @@
1
+ const EN = {
2
+ filesChanged: '{count} files changed',
3
+ fileChanged: '1 file changed',
4
+ undo: 'Undo the changes of this reply',
5
+ undoing: 'Taking back…',
6
+ created: 'new',
7
+ conflictTitle: 'Files changed again since',
8
+ conflictMessage: '{files} changed after this reply. Undoing writes them back as they were before it, and the later changes are lost.',
9
+ overwrite: 'Undo anyway',
10
+ skipped: 'Not taken back, as their contents were not kept: {files}',
11
+ nothing: 'These files are already as they were before this reply.',
12
+ busy: 'Ta is still working in this conversation; undo once it stops.',
13
+ closed: 'This conversation is not open in the Ta service; open it again and retry.',
14
+ missing: 'This reply is not in the conversation any more.',
15
+ failed: 'Could not undo: {message}',
16
+ revertNote: 'Took back the changes to {count} files',
17
+ revertNoteOne: 'Took back the changes to 1 file',
18
+ diffTitle: '{name} (changes)',
19
+ binary: 'A binary file: no diff to show.',
20
+ large: 'The file is too large: its contents before and after were not kept.',
21
+ gone: 'The kept contents were cleaned up: no diff to show.',
22
+ loading: 'Loading…',
23
+ };
24
+
25
+ type Words = typeof EN;
26
+
27
+ const ZH: Words = {
28
+ filesChanged: '{count} 个文件已更改',
29
+ fileChanged: '1 个文件已更改',
30
+ undo: '撤销本轮改动',
31
+ undoing: '正在撤销…',
32
+ created: '新建',
33
+ conflictTitle: '有文件在这之后又改过',
34
+ conflictMessage: '{files} 在这一轮之后又被修改过。撤销会把它们恢复成这一轮之前的样子,之后的修改会丢失。',
35
+ overwrite: '仍然撤销',
36
+ skipped: '这些文件没有保存内容,未能撤销:{files}',
37
+ nothing: '这些文件已经是这一轮之前的样子了。',
38
+ busy: 'Ta 还在这个对话里工作,等它停下再撤销。',
39
+ closed: 'Ta 服务里没有打开这个对话,重新打开后再试。',
40
+ missing: '这一轮已经不在对话里了。',
41
+ failed: '撤销失败:{message}',
42
+ revertNote: '已撤销 {count} 个文件的改动',
43
+ revertNoteOne: '已撤销 1 个文件的改动',
44
+ diffTitle: '{name}(本轮改动)',
45
+ binary: '二进制文件,不显示差异。',
46
+ large: '文件太大,没有保存改动前后的内容。',
47
+ gone: '保存的内容已被清理,无法显示差异。',
48
+ loading: '加载中…',
49
+ };
50
+
51
+ export namespace ChangesWords {
52
+ export function of(language: string): Words {
53
+ return language === 'zh-CN' ? ZH : EN;
54
+ }
55
+
56
+ export function format(text: string, values: Record<string, string | number>): string {
57
+ return text.replace(/\{(\w+)\}/g, (whole, key: string) => (key in values ? String(values[key]) : whole));
58
+ }
59
+ }
@@ -0,0 +1,26 @@
1
+ import type { WebExtensionAPI } from '@celljs/ta-web/lib/browser/extension/web-extension-api';
2
+ import { ChangesBar, RevertNote } from './card';
3
+ import { REVERT_TYPE } from './changes-protocol';
4
+ import { bindPage, Latest, Reverted } from './page';
5
+ import { bind } from './react';
6
+ import { injectStyle } from './style';
7
+
8
+ /**
9
+ * Above the message box, the files the last reply that changed any changed: how many, the lines added and removed, the diff of each in the
10
+ * workbench, and a button that takes them back. The pi extension (extension.ts) records them and the
11
+ * host (host.ts) keeps their contents; this only shows them.
12
+ */
13
+ export default function activate(pi: WebExtensionAPI): () => void {
14
+ bind(pi.React);
15
+ bindPage(pi);
16
+ const removeStyle = injectStyle();
17
+ const stopWatching = Reverted.watch();
18
+ Latest.watch();
19
+ pi.ui.setWidget('changes', ChangesBar);
20
+ pi.registerMessageRenderer(REVERT_TYPE, RevertNote);
21
+ return () => {
22
+ stopWatching();
23
+ pi.ui.setWidget('changes', undefined);
24
+ removeStyle();
25
+ };
26
+ }
@@ -0,0 +1,25 @@
1
+ import { describe, expect, it } from 'bun:test';
2
+ import { LineDiff } from './line-diff';
3
+
4
+ describe('LineDiff', () => {
5
+ it('counts lines as git diff --stat does', () => {
6
+ expect(LineDiff.count('a\nb\nc\n', 'a\nB\nc\n')).toEqual({ added: 1, removed: 1 });
7
+ expect(LineDiff.count('', 'a\nb\n')).toEqual({ added: 2, removed: 0 });
8
+ expect(LineDiff.count('a\nb\n', '')).toEqual({ added: 0, removed: 2 });
9
+ expect(LineDiff.count('a\nb\nc\nd\n', 'a\nx\nb\nd\ny\n')).toEqual({ added: 2, removed: 1 });
10
+ expect(LineDiff.count('same\n', 'same\n')).toEqual({ added: 0, removed: 0 });
11
+ });
12
+
13
+ it('finds the fewest edits when lines move', () => {
14
+ expect(LineDiff.count('1\n2\n3\n4\n5\n', '2\n3\n4\n5\n1\n')).toEqual({ added: 1, removed: 1 });
15
+ expect(LineDiff.count('a\nb\na\nb\n', 'b\na\nb\na\n')).toEqual({ added: 1, removed: 1 });
16
+ });
17
+
18
+ it('counts texts that differ in too many places as replaced, without the cost', () => {
19
+ const before = Array.from({ length: 6000 }, (_, index) => `old ${index}`).join('\n');
20
+ const after = Array.from({ length: 5000 }, (_, index) => `new ${index}`).join('\n');
21
+ const started = performance.now();
22
+ expect(LineDiff.count(before, after)).toEqual({ added: 5000, removed: 6000 });
23
+ expect(performance.now() - started).toBeLessThan(2000);
24
+ });
25
+ });
@@ -0,0 +1,65 @@
1
+ /** Lines added and removed between two texts, as `git diff --stat` counts them. */
2
+ export namespace LineDiff {
3
+ /** Beyond this many edits the texts count as replaced: the counts then say every line in between changed. */
4
+ export const MAX_EDITS = 4000;
5
+
6
+ export function lines(text: string): string[] {
7
+ if (!text) {
8
+ return [];
9
+ }
10
+ const lines = text.split('\n');
11
+ if (lines[lines.length - 1] === '') {
12
+ lines.pop();
13
+ }
14
+ return lines;
15
+ }
16
+
17
+ export function count(before: string, after: string): { added: number; removed: number } {
18
+ const a = lines(before);
19
+ const b = lines(after);
20
+ // The lines both start and end with are no edits: only those in between go to Myers' algorithm.
21
+ let start = 0;
22
+ while (start < a.length && start < b.length && a[start] === b[start]) {
23
+ start++;
24
+ }
25
+ let endA = a.length;
26
+ let endB = b.length;
27
+ while (endA > start && endB > start && a[endA - 1] === b[endB - 1]) {
28
+ endA--;
29
+ endB--;
30
+ }
31
+ const n = endA - start;
32
+ const m = endB - start;
33
+ if (!n || !m) {
34
+ return { added: m, removed: n };
35
+ }
36
+ const edits = distance(a.slice(start, endA), b.slice(start, endB), Math.min(n + m, MAX_EDITS));
37
+ if (edits === undefined) {
38
+ return { added: m, removed: n };
39
+ }
40
+ // Each edit adds or removes a line, and the added minus the removed are m - n.
41
+ return { added: (edits + m - n) / 2, removed: (edits - m + n) / 2 };
42
+ }
43
+
44
+ /** The fewest lines to add and remove to make `a` into `b` (Myers, 1986); undefined when more than `max`. */
45
+ function distance(a: string[], b: string[], max: number): number | undefined {
46
+ const offset = max + 1;
47
+ const furthest = new Int32Array(2 * max + 3);
48
+ for (let edits = 0; edits <= max; edits++) {
49
+ for (let diagonal = -edits; diagonal <= edits; diagonal += 2) {
50
+ const down = diagonal === -edits || (diagonal !== edits && furthest[offset + diagonal - 1] < furthest[offset + diagonal + 1]);
51
+ let x = down ? furthest[offset + diagonal + 1] : furthest[offset + diagonal - 1] + 1;
52
+ let y = x - diagonal;
53
+ while (x < a.length && y < b.length && a[x] === b[y]) {
54
+ x++;
55
+ y++;
56
+ }
57
+ furthest[offset + diagonal] = x;
58
+ if (x >= a.length && y >= b.length) {
59
+ return edits;
60
+ }
61
+ }
62
+ }
63
+ return undefined;
64
+ }
65
+ }
@@ -0,0 +1,107 @@
1
+ import type { WebExtensionAPI, WebIcon } from '@celljs/ta-web/lib/browser/extension/web-extension-api';
2
+ import { CHANGES_TYPE, type ChangeSet, REVERTED_KEY } from './changes-protocol';
3
+ import { ChangesWords } from './i18n';
4
+ import { React } from './react';
5
+
6
+ /** The API ta gave the web extension when it started. */
7
+ export let pi: WebExtensionAPI;
8
+
9
+ export function bindPage(api: WebExtensionAPI): void {
10
+ pi = api;
11
+ }
12
+
13
+ /** The words of the page's language, with `{name}` filled in. */
14
+ export function t(key: keyof ReturnType<typeof ChangesWords.of>, values: Record<string, string | number> = {}): string {
15
+ return ChangesWords.format(ChangesWords.of(pi.ui.language)[key], values);
16
+ }
17
+
18
+ /** An icon of the page by its lucide name; a blank one when the page does not have it. */
19
+ export function icon(name: string): WebIcon {
20
+ return pi.ui.icons[name] ?? (() => null);
21
+ }
22
+
23
+ export function message(error: unknown): string {
24
+ return error instanceof Error ? error.message : String(error);
25
+ }
26
+
27
+ /** The change sets taken back, from the package's data on the server: the same in every browser. */
28
+ export namespace Reverted {
29
+ let ids = new Set<string>();
30
+ let loading = false;
31
+ const listeners = new Set<() => void>();
32
+
33
+ function load(): Promise<void> {
34
+ return pi.storage.get<string[]>(REVERTED_KEY).then(value => {
35
+ ids = new Set(Array.isArray(value) ? value : []);
36
+ for (const listener of listeners) {
37
+ listener();
38
+ }
39
+ });
40
+ }
41
+
42
+ /** Starts listening; stops when the extension unloads. */
43
+ export function watch(): () => void {
44
+ return pi.storage.onChange(keys => {
45
+ if (keys.includes(REVERTED_KEY)) {
46
+ void load();
47
+ }
48
+ });
49
+ }
50
+
51
+ /** A React hook: whether the change set was taken back. */
52
+ export function use(id: string): boolean {
53
+ const [, setVersion] = React.useState(0);
54
+ React.useEffect(() => {
55
+ const listener = () => setVersion(version => version + 1);
56
+ listeners.add(listener);
57
+ if (!loading) {
58
+ loading = true;
59
+ load().catch(() => {
60
+ loading = false;
61
+ });
62
+ }
63
+ return () => {
64
+ listeners.delete(listener);
65
+ };
66
+ }, []);
67
+ return ids.has(id);
68
+ }
69
+
70
+ /** Taken back by this page: shown at once, before the server's data says so. */
71
+ export function add(id: string): void {
72
+ ids = new Set([...ids, id]);
73
+ for (const listener of listeners) {
74
+ listener();
75
+ }
76
+ }
77
+ }
78
+
79
+ /** The change sets Ta sends in the conversation shown, and when the conversation was replaced (a fork, a jump in its tree). */
80
+ export namespace Latest {
81
+ type Listener = (set: ChangeSet | 'replaced') => void;
82
+ const listeners = new Set<Listener>();
83
+
84
+ function tell(value: ChangeSet | 'replaced'): void {
85
+ for (const listener of listeners) {
86
+ listener(value);
87
+ }
88
+ }
89
+
90
+ /** Starts listening; stops when the extension unloads (pi.on). */
91
+ export function watch(): void {
92
+ pi.on('message_end', event => {
93
+ const message = event.message as { role?: string; customType?: string; details?: ChangeSet };
94
+ if (message.role === 'custom' && message.customType === CHANGES_TYPE && message.details?.files) {
95
+ tell(message.details);
96
+ }
97
+ });
98
+ pi.on('session_replaced', () => tell('replaced'));
99
+ }
100
+
101
+ export function subscribe(listener: Listener): () => void {
102
+ listeners.add(listener);
103
+ return () => {
104
+ listeners.delete(listener);
105
+ };
106
+ }
107
+ }
@@ -0,0 +1,11 @@
1
+ import type * as ReactModule from 'react';
2
+
3
+ /**
4
+ * The React of the page, which a web extension cannot import: `activate` binds it before anything
5
+ * renders. The JSX of this package compiles to `React.createElement` (tsconfig.json).
6
+ */
7
+ export let React: typeof ReactModule;
8
+
9
+ export function bind(react: typeof ReactModule): void {
10
+ React = react;
11
+ }
@@ -0,0 +1,124 @@
1
+ import { describe, expect, it } from 'bun:test';
2
+ import type { TaSessionFiles } from '@celljs/ta-protocol';
3
+ import { ChangeRecorder, hash, revert } from './recorder';
4
+
5
+ const encode = (text: string) => new TextEncoder().encode(text);
6
+ const decode = (data: Uint8Array | undefined) => (data ? new TextDecoder().decode(data) : undefined);
7
+
8
+ /** Files in memory, and blobs kept by hash. */
9
+ function fixture(initial: Record<string, string> = {}) {
10
+ const disk = new Map<string, Uint8Array>(Object.entries(initial).map(([path, text]) => [path, encode(text)]));
11
+ const blobs = new Map<string, Uint8Array>();
12
+ const files: TaSessionFiles = {
13
+ resolve: path => (path.startsWith('/') ? path : `/work/${path}`),
14
+ read: async path => disk.get(path),
15
+ write: async (path, data) => {
16
+ disk.set(path, data);
17
+ },
18
+ remove: async path => {
19
+ disk.delete(path);
20
+ },
21
+ };
22
+ const service = {
23
+ store: async (data: Uint8Array) => {
24
+ const name = hash(data);
25
+ blobs.set(name, data);
26
+ return name;
27
+ },
28
+ load: async (name: string) => blobs.get(name),
29
+ };
30
+ return { disk, blobs, files, service, text: (path: string) => decode(disk.get(path)) };
31
+ }
32
+
33
+ describe('ChangeRecorder', () => {
34
+ it('keeps each file as it was before its first write in a reply, and lists what changed when the reply ends', async () => {
35
+ const { disk, files, service, blobs } = fixture({ '/work/a.ts': 'one\ntwo\n', '/work/same.ts': 'same\n' });
36
+ const recorder = new ChangeRecorder(files, service);
37
+ await recorder.before('/work/a.ts');
38
+ disk.set('/work/a.ts', encode('one\n2\n'));
39
+ // A second write in the same reply does not move what it was before.
40
+ await recorder.before('/work/a.ts');
41
+ disk.set('/work/a.ts', encode('one\n2\nthree\n'));
42
+ await recorder.before('/work/new.ts');
43
+ disk.set('/work/new.ts', encode('hello\n'));
44
+ // Written with what was there: no change.
45
+ await recorder.before('/work/same.ts');
46
+ const set = await recorder.finish('/work');
47
+ expect(set?.root).toBe('/work');
48
+ expect(set?.files).toEqual([
49
+ { path: '/work/a.ts', added: 2, removed: 1, before: hash(encode('one\ntwo\n')), after: hash(encode('one\n2\nthree\n')) },
50
+ { path: '/work/new.ts', added: 1, removed: 0, after: hash(encode('hello\n')) },
51
+ ]);
52
+ expect(blobs.size).toBe(3);
53
+ // The next reply starts afresh.
54
+ expect(await recorder.finish('/work')).toBeUndefined();
55
+ });
56
+
57
+ it('takes what a file held from whoever writes it, when they say', async () => {
58
+ const { disk, files, service } = fixture({ '/work/a.ts': 'already written\n' });
59
+ const recorder = new ChangeRecorder(files, service);
60
+ await recorder.before('/work/a.ts', 'before\n');
61
+ await recorder.before('/work/new.ts', null);
62
+ disk.set('/work/new.ts', encode('new\n'));
63
+ // Only the first word of a reply counts.
64
+ await recorder.before('/work/a.ts', 'later\n');
65
+ const set = await recorder.finish('/work');
66
+ expect(set?.files.map(file => [file.path, file.added, file.removed, file.before === hash(encode('before\n')), file.before])).toEqual([
67
+ ['/work/a.ts', 1, 1, true, hash(encode('before\n'))],
68
+ ['/work/new.ts', 1, 0, false, undefined],
69
+ ]);
70
+ });
71
+
72
+ it('counts no lines of binary files and keeps no contents of large ones', async () => {
73
+ const { disk, files, service, blobs } = fixture({ '/work/logo.png': '\u0000png' });
74
+ const recorder = new ChangeRecorder(files, service);
75
+ await recorder.before('/work/logo.png');
76
+ disk.set('/work/logo.png', new Uint8Array([0, 1, 2]));
77
+ await recorder.before('/work/big.txt');
78
+ disk.set('/work/big.txt', new Uint8Array(5 * 1024 * 1024).fill(97));
79
+ const set = await recorder.finish('/work');
80
+ expect(set?.files[0]).toMatchObject({ path: '/work/logo.png', added: 0, removed: 0, binary: true });
81
+ expect(set?.files[1]).toEqual({ path: '/work/big.txt', added: 1, removed: 0, large: true });
82
+ expect(blobs.size).toBe(2);
83
+ });
84
+ });
85
+
86
+ describe('revert', () => {
87
+ async function changed() {
88
+ const fx = fixture({ '/work/a.ts': 'before\n' });
89
+ const recorder = new ChangeRecorder(fx.files, fx.service);
90
+ await recorder.before('/work/a.ts');
91
+ fx.disk.set('/work/a.ts', encode('after\n'));
92
+ await recorder.before('/work/new.ts');
93
+ fx.disk.set('/work/new.ts', encode('new\n'));
94
+ const set = (await recorder.finish('/work'))!;
95
+ return { ...fx, set };
96
+ }
97
+
98
+ it('writes the files back and removes those the reply created', async () => {
99
+ const { set, files, service, text, disk } = await changed();
100
+ expect(await revert(set, files, service, false)).toEqual({ reverted: ['/work/a.ts', '/work/new.ts'], conflicts: [], skipped: [] });
101
+ expect(text('/work/a.ts')).toBe('before\n');
102
+ expect(disk.has('/work/new.ts')).toBe(false);
103
+ // Taken back already: nothing to do.
104
+ expect(await revert(set, files, service, false)).toEqual({ reverted: [], conflicts: [], skipped: [] });
105
+ });
106
+
107
+ it('touches nothing when a file changed again since, unless forced', async () => {
108
+ const { set, files, service, text, disk } = await changed();
109
+ disk.set('/work/a.ts', encode('edited by hand\n'));
110
+ expect(await revert(set, files, service, false)).toEqual({ reverted: [], conflicts: ['/work/a.ts'], skipped: [] });
111
+ expect(text('/work/a.ts')).toBe('edited by hand\n');
112
+ expect(disk.has('/work/new.ts')).toBe(true);
113
+ expect((await revert(set, files, service, true)).reverted).toEqual(['/work/a.ts', '/work/new.ts']);
114
+ expect(text('/work/a.ts')).toBe('before\n');
115
+ });
116
+
117
+ it('skips files whose contents are gone or were never kept', async () => {
118
+ const { set, files, service, blobs, text } = await changed();
119
+ blobs.delete(set.files[0].before!);
120
+ const large = { ...set, files: [...set.files, { path: '/work/big.txt', added: 1, removed: 0, large: true }] };
121
+ expect(await revert(large, files, service, false)).toEqual({ reverted: ['/work/new.ts'], conflicts: [], skipped: ['/work/big.txt', '/work/a.ts'] });
122
+ expect(text('/work/a.ts')).toBe('after\n');
123
+ });
124
+ });
@@ -0,0 +1,114 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import type { TaSessionFiles } from '@celljs/ta-protocol';
3
+ import { type ChangedFile, type ChangeSet, type ChangesService, MAX_KEPT_BYTES, type RevertResult } from './changes-protocol';
4
+ import { ChangesUtil } from './changes-util';
5
+ import { LineDiff } from './line-diff';
6
+
7
+ /** The SHA-256 of bytes, in hex: the name of what the host keeps. */
8
+ export function hash(data: Uint8Array): string {
9
+ return createHash('sha256').update(data).digest('hex');
10
+ }
11
+
12
+ /**
13
+ * The files a reply changes: before a tool writes a file the first time in the reply, what is there;
14
+ * when the reply ends, what changed, its contents before and after kept by the host.
15
+ */
16
+ export class ChangeRecorder {
17
+ protected befores = new Map<string, Promise<Uint8Array | undefined>>();
18
+
19
+ constructor(
20
+ protected readonly files: Pick<TaSessionFiles, 'read'>,
21
+ protected readonly service: Pick<ChangesService, 'store'>,
22
+ ) {}
23
+
24
+ /**
25
+ * Before a tool writes `path` (resolved): its contents, the first time in this reply. `known`: what it
26
+ * held, when whoever writes said (a diff of another agent; null: no file), instead of reading it.
27
+ */
28
+ async before(path: string, known?: string | null): Promise<void> {
29
+ if (!this.befores.has(path)) {
30
+ this.befores.set(path, known === undefined ? this.files.read(path) : Promise.resolve(known === null ? undefined : new TextEncoder().encode(known)));
31
+ }
32
+ await this.befores.get(path)?.catch(() => undefined);
33
+ }
34
+
35
+ /** The reply ended: what it changed, if anything; the next one starts afresh. */
36
+ async finish(root: string): Promise<ChangeSet | undefined> {
37
+ const befores = this.befores;
38
+ this.befores = new Map();
39
+ const files: ChangedFile[] = [];
40
+ for (const [path, read] of befores) {
41
+ try {
42
+ const file = await this.compare(path, await read, await this.files.read(path));
43
+ if (file) {
44
+ files.push(file);
45
+ }
46
+ } catch {
47
+ // A file that cannot be read is left out: nothing about it would be right.
48
+ }
49
+ }
50
+ return files.length ? { id: randomUUID(), root, files } : undefined;
51
+ }
52
+
53
+ protected async compare(path: string, before: Uint8Array | undefined, after: Uint8Array | undefined): Promise<ChangedFile | undefined> {
54
+ if (before === after || (before && after && Buffer.compare(before, after) === 0)) {
55
+ return undefined;
56
+ }
57
+ const binary = !ChangesUtil.isText(before) || !ChangesUtil.isText(after);
58
+ const decoder = new TextDecoder();
59
+ const counts = binary ? { added: 0, removed: 0 } : LineDiff.count(before ? decoder.decode(before) : '', after ? decoder.decode(after) : '');
60
+ const file: ChangedFile = { path, ...counts };
61
+ if (binary) {
62
+ file.binary = true;
63
+ }
64
+ if ((before?.length ?? 0) > MAX_KEPT_BYTES || (after?.length ?? 0) > MAX_KEPT_BYTES) {
65
+ file.large = true;
66
+ return file;
67
+ }
68
+ if (before) {
69
+ file.before = await this.service.store(before);
70
+ }
71
+ if (after) {
72
+ file.after = await this.service.store(after);
73
+ }
74
+ return file;
75
+ }
76
+ }
77
+
78
+ /** Takes the changes of a reply back: each file as it was before it, unless it changed again since. */
79
+ export async function revert(set: ChangeSet, files: TaSessionFiles, service: Pick<ChangesService, 'load'>, force: boolean): Promise<RevertResult> {
80
+ const result: RevertResult = { reverted: [], conflicts: [], skipped: [] };
81
+ const pending: ChangedFile[] = [];
82
+ for (const file of set.files) {
83
+ if (file.large) {
84
+ result.skipped.push(file.path);
85
+ continue;
86
+ }
87
+ const current = await files.read(file.path);
88
+ const now = current && hash(current);
89
+ if (now === file.before) {
90
+ continue;
91
+ }
92
+ if (now !== file.after) {
93
+ result.conflicts.push(file.path);
94
+ }
95
+ pending.push(file);
96
+ }
97
+ if (result.conflicts.length && !force) {
98
+ return result;
99
+ }
100
+ for (const file of pending) {
101
+ if (file.before === undefined) {
102
+ await files.remove(file.path);
103
+ } else {
104
+ const data = await service.load(file.before);
105
+ if (!data) {
106
+ result.skipped.push(file.path);
107
+ continue;
108
+ }
109
+ await files.write(file.path, data);
110
+ }
111
+ result.reverted.push(file.path);
112
+ }
113
+ return result;
114
+ }
@@ -0,0 +1,40 @@
1
+ /** The styles of the package; only the --ta-* variables of the page, so they follow its theme. */
2
+ export const STYLE = `
3
+ .tcg { position: relative; display: flex; justify-content: center; }
4
+ .tcg-pill { display: inline-flex; align-items: center; gap: 8px; height: 32px; padding: 0 14px; border: 1px solid var(--ta-border-muted); border-radius: 999px; background: var(--ta-raised); color: var(--ta-text); font: inherit; font-size: 13px; cursor: pointer; transition: background 120ms, border-color 120ms, transform 120ms var(--ta-ease); }
5
+ .tcg-pill:hover { background: var(--ta-hover); border-color: var(--ta-border); }
6
+ .tcg-pill:active { transform: scale(.98); }
7
+ .tcg-pill[aria-expanded='true'] { border-color: var(--ta-border); }
8
+ .tcg-stat { display: inline-flex; gap: 6px; font-variant-numeric: tabular-nums; font-size: 12.5px; }
9
+ .tcg-add { color: var(--ta-green); }
10
+ .tcg-del { color: var(--ta-red); }
11
+ .tcg-card { position: absolute; bottom: calc(100% + 8px); left: 50%; z-index: 20; width: min(100%, 560px); transform: translateX(-50%); border: 1px solid var(--ta-border-muted); border-radius: 14px; background: var(--ta-card); box-shadow: var(--ta-shadow-pop); overflow: hidden; animation: tcg-in 160ms var(--ta-ease); }
12
+ @keyframes tcg-in { from { opacity: 0; transform: translate(-50%, 4px); } }
13
+ .tcg-files { max-height: 280px; overflow: auto; padding: 4px 0; }
14
+ .tcg-file { display: flex; align-items: baseline; gap: 8px; width: 100%; padding: 8px 16px; border: 0; background: none; color: inherit; font: inherit; font-size: 13.5px; text-align: left; cursor: pointer; }
15
+ .tcg-file:hover { background: var(--ta-hover); }
16
+ .tcg-file:disabled { cursor: default; }
17
+ .tcg-file:disabled:hover { background: none; }
18
+ .tcg-name { flex: none; max-width: 60%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
19
+ .tcg-dir { flex: 1; min-width: 0; overflow: hidden; color: var(--ta-muted); font-size: 12.5px; text-overflow: ellipsis; white-space: nowrap; }
20
+ .tcg-tag { flex: none; padding: 0 6px; border-radius: 6px; background: var(--ta-chip); color: var(--ta-muted); font-size: 11px; line-height: 17px; }
21
+ .tcg-file .tcg-stat { flex: none; margin-left: auto; }
22
+ .tcg-foot { border-top: 1px solid var(--ta-border-muted); padding: 4px; }
23
+ .tcg-undo { display: flex; align-items: center; gap: 8px; width: 100%; padding: 8px 12px; border: 0; border-radius: 10px; background: none; color: var(--ta-secondary); font: inherit; font-size: 13.5px; text-align: left; cursor: pointer; }
24
+ .tcg-undo:hover { background: var(--ta-hover); color: var(--ta-text); }
25
+ .tcg-undo:disabled { color: var(--ta-muted); cursor: default; background: none; }
26
+ .tcg-note { display: flex; align-items: center; justify-content: center; gap: 6px; margin: 2px 0; color: var(--ta-muted); font-size: 12.5px; }
27
+ .tcg-diff { display: flex; flex-direction: column; height: 100%; min-height: 0; }
28
+ .tcg-diff-head { display: flex; align-items: center; gap: 10px; flex: none; height: 32px; padding: 0 12px; border-bottom: 1px solid var(--ta-border-muted); color: var(--ta-muted); font-size: 12px; }
29
+ .tcg-diff-path { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
30
+ .tcg-diff-body { flex: 1; min-height: 0; }
31
+ .tcg-diff-empty { padding: 24px; color: var(--ta-muted); font-size: 13px; text-align: center; }
32
+ `;
33
+
34
+ export function injectStyle(): () => void {
35
+ const element = document.createElement('style');
36
+ element.dataset.taPackage = 'ta-changes';
37
+ element.textContent = STYLE;
38
+ document.head.appendChild(element);
39
+ return () => element.remove();
40
+ }