@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.
- package/README.en.md +21 -0
- package/README.md +20 -2
- package/extension/index.mjs +296 -0
- package/host/index.mjs +309 -0
- package/package.json +44 -4
- package/web/index.js +460 -0
- package/web-src/blob-store.spec.ts +33 -0
- package/web-src/blob-store.ts +68 -0
- package/web-src/card.tsx +164 -0
- package/web-src/changes-protocol.ts +85 -0
- package/web-src/changes-service.spec.ts +61 -0
- package/web-src/changes-service.ts +75 -0
- package/web-src/changes-util.spec.ts +33 -0
- package/web-src/changes-util.ts +44 -0
- package/web-src/diff-tab.tsx +60 -0
- package/web-src/extension.ts +143 -0
- package/web-src/host.ts +14 -0
- package/web-src/i18n.ts +59 -0
- package/web-src/index.tsx +26 -0
- package/web-src/line-diff.spec.ts +25 -0
- package/web-src/line-diff.ts +65 -0
- package/web-src/page.ts +107 -0
- package/web-src/react.ts +11 -0
- package/web-src/recorder.spec.ts +124 -0
- package/web-src/recorder.ts +114 -0
- package/web-src/style.ts +40 -0
package/web-src/card.tsx
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import type { WebCustomMessage } from '@celljs/ta-web/lib/browser/extension/web-extension-api';
|
|
2
|
+
import type { ChangeSet, RevertDetails, RevertResult } from './changes-protocol';
|
|
3
|
+
import { ChangesUtil } from './changes-util';
|
|
4
|
+
import { openDiff } from './diff-tab';
|
|
5
|
+
import { message as errorMessage, icon, Latest, pi, Reverted, t } from './page';
|
|
6
|
+
import { React } from './react';
|
|
7
|
+
|
|
8
|
+
function Stat({ added, removed }: { added: number; removed: number }) {
|
|
9
|
+
return (
|
|
10
|
+
<span className="tcg-stat">
|
|
11
|
+
<span className="tcg-add">+{added}</span>
|
|
12
|
+
<span className="tcg-del">−{removed}</span>
|
|
13
|
+
</span>
|
|
14
|
+
);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function names(paths: string[], root: string): string {
|
|
18
|
+
return paths.map(path => ChangesUtil.relative(path, root)).join(', ');
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Takes the changes back, asking first when files changed again since; says what came of it. */
|
|
22
|
+
async function undo(sessionId: string, set: ChangeSet): Promise<boolean> {
|
|
23
|
+
let result = await pi.callHost<RevertResult>('revert', sessionId, set.id, false);
|
|
24
|
+
if (result.conflicts.length && !result.refused) {
|
|
25
|
+
const go = await pi.ui.confirm(t('conflictTitle'), t('conflictMessage', { files: names(result.conflicts, set.root) }), {
|
|
26
|
+
confirmLabel: t('overwrite'),
|
|
27
|
+
danger: true,
|
|
28
|
+
});
|
|
29
|
+
if (!go) {
|
|
30
|
+
return false;
|
|
31
|
+
}
|
|
32
|
+
result = await pi.callHost<RevertResult>('revert', sessionId, set.id, true);
|
|
33
|
+
}
|
|
34
|
+
if (result.refused) {
|
|
35
|
+
pi.ui.notify(t(result.refused), 'warning');
|
|
36
|
+
return false;
|
|
37
|
+
}
|
|
38
|
+
if (result.skipped.length) {
|
|
39
|
+
pi.ui.notify(t('skipped', { files: names(result.skipped, set.root) }), 'warning');
|
|
40
|
+
} else if (!result.reverted.length) {
|
|
41
|
+
pi.ui.notify(t('nothing'));
|
|
42
|
+
}
|
|
43
|
+
return true;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The last change set of the conversation shown: asked of the host when it is shown, then as Ta sends them. */
|
|
47
|
+
function useLatest(sessionId: string | undefined): ChangeSet | undefined {
|
|
48
|
+
const [latest, setLatest] = React.useState<{ sessionId: string; set?: ChangeSet }>();
|
|
49
|
+
React.useEffect(() => {
|
|
50
|
+
if (!sessionId) {
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
let live = true;
|
|
54
|
+
const ask = () =>
|
|
55
|
+
pi.callHost<ChangeSet | null>('latest', sessionId).then(
|
|
56
|
+
set => live && setLatest({ sessionId, set: set ?? undefined }),
|
|
57
|
+
() => live && setLatest({ sessionId }),
|
|
58
|
+
);
|
|
59
|
+
// Events come from the conversation shown, which is this one while the effect lasts.
|
|
60
|
+
const stop = Latest.subscribe(value => (value === 'replaced' ? void ask() : setLatest({ sessionId, set: value })));
|
|
61
|
+
void ask();
|
|
62
|
+
return () => {
|
|
63
|
+
live = false;
|
|
64
|
+
stop();
|
|
65
|
+
};
|
|
66
|
+
}, [sessionId]);
|
|
67
|
+
return latest && latest.sessionId === sessionId ? latest.set : undefined;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Above the message box, the files the last reply that changed any changed: a pill with how many and the
|
|
72
|
+
* lines added and removed; it opens a card above it with each file (a click shows its diff in the
|
|
73
|
+
* workbench) and a button that takes them back. Gone once they were taken back.
|
|
74
|
+
*/
|
|
75
|
+
export function ChangesBar() {
|
|
76
|
+
const sessionId = pi.ui.useSessionId();
|
|
77
|
+
const set = useLatest(sessionId);
|
|
78
|
+
const reverted = Reverted.use(set?.id ?? '');
|
|
79
|
+
const [open, setOpen] = React.useState(false);
|
|
80
|
+
const [busy, setBusy] = React.useState(false);
|
|
81
|
+
const root = React.useRef<HTMLDivElement>(null);
|
|
82
|
+
React.useEffect(() => setOpen(false), [set?.id]);
|
|
83
|
+
React.useEffect(() => {
|
|
84
|
+
if (!open) {
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
const close = (event: Event) => {
|
|
88
|
+
if (event instanceof KeyboardEvent ? event.key === 'Escape' : !root.current?.contains(event.target as Node)) {
|
|
89
|
+
setOpen(false);
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
document.addEventListener('pointerdown', close, true);
|
|
93
|
+
document.addEventListener('keydown', close);
|
|
94
|
+
return () => {
|
|
95
|
+
document.removeEventListener('pointerdown', close, true);
|
|
96
|
+
document.removeEventListener('keydown', close);
|
|
97
|
+
};
|
|
98
|
+
}, [open]);
|
|
99
|
+
if (!sessionId || !set?.files?.length || reverted) {
|
|
100
|
+
return null;
|
|
101
|
+
}
|
|
102
|
+
const totals = ChangesUtil.totals(set.files);
|
|
103
|
+
const Undo = icon('Undo2');
|
|
104
|
+
const run = async () => {
|
|
105
|
+
if (busy) {
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
setBusy(true);
|
|
109
|
+
try {
|
|
110
|
+
if (await undo(sessionId, set)) {
|
|
111
|
+
Reverted.add(set.id);
|
|
112
|
+
setOpen(false);
|
|
113
|
+
}
|
|
114
|
+
} catch (error) {
|
|
115
|
+
pi.ui.notify(t('failed', { message: errorMessage(error) }), 'error');
|
|
116
|
+
} finally {
|
|
117
|
+
setBusy(false);
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
return (
|
|
121
|
+
<div className="tcg" ref={root}>
|
|
122
|
+
{open && (
|
|
123
|
+
<div className="tcg-card" role="dialog">
|
|
124
|
+
<div className="tcg-files">
|
|
125
|
+
{set.files.map(file => {
|
|
126
|
+
const { name, dir } = ChangesUtil.place(file.path, set.root);
|
|
127
|
+
return (
|
|
128
|
+
<button key={file.path} type="button" className="tcg-file" title={file.path} onClick={() => openDiff(set, file)}>
|
|
129
|
+
<span className="tcg-name">{name}</span>
|
|
130
|
+
{dir && <span className="tcg-dir">{dir}</span>}
|
|
131
|
+
{file.before === undefined && !file.large && <span className="tcg-tag">{t('created')}</span>}
|
|
132
|
+
<Stat added={file.added} removed={file.removed} />
|
|
133
|
+
</button>
|
|
134
|
+
);
|
|
135
|
+
})}
|
|
136
|
+
</div>
|
|
137
|
+
<div className="tcg-foot">
|
|
138
|
+
<button type="button" className="tcg-undo" disabled={busy} onClick={() => void run()}>
|
|
139
|
+
<Undo size={15} />
|
|
140
|
+
{busy ? t('undoing') : t('undo')}
|
|
141
|
+
</button>
|
|
142
|
+
</div>
|
|
143
|
+
</div>
|
|
144
|
+
)}
|
|
145
|
+
<button type="button" className="tcg-pill" aria-expanded={open} onClick={() => setOpen(!open)}>
|
|
146
|
+
<span>{set.files.length === 1 ? t('fileChanged') : t('filesChanged', { count: set.files.length })}</span>
|
|
147
|
+
<Stat added={totals.added} removed={totals.removed} />
|
|
148
|
+
</button>
|
|
149
|
+
</div>
|
|
150
|
+
);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** After the user took the changes of a reply back: one quiet line. */
|
|
154
|
+
export function RevertNote({ message }: { message: WebCustomMessage }) {
|
|
155
|
+
const details = message.details as RevertDetails | undefined;
|
|
156
|
+
const count = details?.files?.length ?? 0;
|
|
157
|
+
const Undo = icon('Undo2');
|
|
158
|
+
return (
|
|
159
|
+
<div className="tcg-note">
|
|
160
|
+
<Undo size={13} />
|
|
161
|
+
{count === 1 ? t('revertNoteOne') : t('revertNote', { count })}
|
|
162
|
+
</div>
|
|
163
|
+
);
|
|
164
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/** The `name` of this package's package.json: how its pi extension asks for its host. */
|
|
2
|
+
export const NAME = '@celljs/ta-changes';
|
|
3
|
+
|
|
4
|
+
/** TA_HOST_EVENT of @celljs/ta-protocol, which the bundles of this package do not import. */
|
|
5
|
+
export const TA_HOST_EVENT = 'ta:host';
|
|
6
|
+
/** TA_FILE_WRITE_EVENT of @celljs/ta-protocol: another agent's tools are about to change a file. */
|
|
7
|
+
export const TA_FILE_WRITE_EVENT = 'ta:file-write';
|
|
8
|
+
|
|
9
|
+
/** The custom message that follows a reply that changed files: what it changed. Not shown in the conversation: the latest is above the message box. */
|
|
10
|
+
export const CHANGES_TYPE = 'ta-changes';
|
|
11
|
+
/** The custom message that tells Ta the user took the changes of a reply back. */
|
|
12
|
+
export const REVERT_TYPE = 'ta-changes-revert';
|
|
13
|
+
|
|
14
|
+
/** The key of the package's data that lists the change sets taken back. */
|
|
15
|
+
export const REVERTED_KEY = 'reverted';
|
|
16
|
+
/** How many of them the list keeps, the latest. */
|
|
17
|
+
export const REVERTED_KEPT = 1000;
|
|
18
|
+
|
|
19
|
+
/** Files larger than this are counted, but their contents are not kept: no diff, no taking back. */
|
|
20
|
+
export const MAX_KEPT_BYTES = 4 * 1024 * 1024;
|
|
21
|
+
|
|
22
|
+
/** A file a reply changed. */
|
|
23
|
+
export interface ChangedFile {
|
|
24
|
+
/** Where the tools wrote it, in the session's execution environment. */
|
|
25
|
+
path: string;
|
|
26
|
+
added: number;
|
|
27
|
+
removed: number;
|
|
28
|
+
/** The hash of its contents before the reply; none: the reply created it. */
|
|
29
|
+
before?: string;
|
|
30
|
+
/** The hash of its contents after the reply. */
|
|
31
|
+
after?: string;
|
|
32
|
+
/** Not text: no lines are counted, no diff is shown. */
|
|
33
|
+
binary?: boolean;
|
|
34
|
+
/** Too large to keep ({@link MAX_KEPT_BYTES}): it cannot be taken back. */
|
|
35
|
+
large?: boolean;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** The `details` of a {@link CHANGES_TYPE} message. */
|
|
39
|
+
export interface ChangeSet {
|
|
40
|
+
id: string;
|
|
41
|
+
/** The directory of the session, in its execution environment: paths show relative to it. */
|
|
42
|
+
root: string;
|
|
43
|
+
files: ChangedFile[];
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The `details` of a {@link REVERT_TYPE} message. */
|
|
47
|
+
export interface RevertDetails {
|
|
48
|
+
id: string;
|
|
49
|
+
files: string[];
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** What taking a change set back did. */
|
|
53
|
+
export interface RevertResult {
|
|
54
|
+
/** Files written back, or removed when the reply created them. */
|
|
55
|
+
reverted: string[];
|
|
56
|
+
/** Files changed again since the reply: nothing was written while there are some, unless forced. */
|
|
57
|
+
conflicts: string[];
|
|
58
|
+
/** Files that cannot be taken back: too large to have been kept, or their contents are gone. */
|
|
59
|
+
skipped: string[];
|
|
60
|
+
/** Nothing was done: Ta still works in the conversation, it is not open in ta serve, or the reply is not in it. */
|
|
61
|
+
refused?: 'busy' | 'closed' | 'missing';
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** What the pi extension of a session gives the host, to take back the changes of its replies. */
|
|
65
|
+
export interface ChangesSession {
|
|
66
|
+
revert(id: string, force: boolean): Promise<RevertResult>;
|
|
67
|
+
/** The last change set on the branch of the conversation. */
|
|
68
|
+
latest(): ChangeSet | undefined;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** The host of the package (`pi.host`): it keeps the contents of changed files, and finds the session of a change set. */
|
|
72
|
+
export interface ChangesService {
|
|
73
|
+
/** Keeps the bytes of a file; answers their hash. */
|
|
74
|
+
store(data: Uint8Array): Promise<string>;
|
|
75
|
+
/** The bytes kept under a hash; undefined when they are gone. */
|
|
76
|
+
load(hash: string): Promise<Uint8Array | undefined>;
|
|
77
|
+
/** A session of `ta serve` (its pi session id) that can take its change sets back, until it ends. */
|
|
78
|
+
attach(piSessionId: string, session: ChangesSession): () => void;
|
|
79
|
+
/** For the page: the text of a file kept under a hash; null when it is gone. */
|
|
80
|
+
read(hash: string): Promise<string | null>;
|
|
81
|
+
/** For the page: the last change set of the session the page shows (TaSessionInfo.sessionId); null when there is none, or it is not open. */
|
|
82
|
+
latest(sessionId: string): Promise<ChangeSet | null>;
|
|
83
|
+
/** For the page: takes back a change set of the session the page shows (TaSessionInfo.sessionId). */
|
|
84
|
+
revert(sessionId: string, id: string, force?: boolean): Promise<RevertResult>;
|
|
85
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { describe, expect, it } from 'bun:test';
|
|
2
|
+
import { mkdtempSync } from 'node:fs';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import type { TaSessionInfo } from '@celljs/ta-protocol';
|
|
6
|
+
import { BlobStore } from './blob-store';
|
|
7
|
+
import { NAME, REVERTED_KEY, type RevertResult } from './changes-protocol';
|
|
8
|
+
import { DefaultChangesService } from './changes-service';
|
|
9
|
+
|
|
10
|
+
function service(result: RevertResult = { reverted: ['/a'], conflicts: [], skipped: [] }) {
|
|
11
|
+
const data = new Map<string, unknown>();
|
|
12
|
+
const host = {
|
|
13
|
+
listSessions: async () => [{ sessionId: 'ta-1', piSessionId: 'pi-1' } as TaSessionInfo],
|
|
14
|
+
getExtensionData: async (name: string, key: string) => data.get(`${name}:${key}`),
|
|
15
|
+
setExtensionData: async (name: string, key: string, value: unknown) => {
|
|
16
|
+
data.set(`${name}:${key}`, value);
|
|
17
|
+
},
|
|
18
|
+
};
|
|
19
|
+
const calls: [string, boolean][] = [];
|
|
20
|
+
const changes = new DefaultChangesService(host, new BlobStore(mkdtempSync(join(tmpdir(), 'ta-changes-service-'))));
|
|
21
|
+
const detach = changes.attach('pi-1', {
|
|
22
|
+
revert: async (id, force) => {
|
|
23
|
+
calls.push([id, force]);
|
|
24
|
+
return result;
|
|
25
|
+
},
|
|
26
|
+
latest: () => ({ id: 'set-2', root: '/', files: [] }),
|
|
27
|
+
});
|
|
28
|
+
return { changes, calls, detach, reverted: () => data.get(`${NAME}:${REVERTED_KEY}`) };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
describe('DefaultChangesService', () => {
|
|
32
|
+
it('takes back the changes of the session the page shows, and remembers it', async () => {
|
|
33
|
+
const { changes, calls, reverted } = service();
|
|
34
|
+
expect((await changes.revert('ta-1', 'set-1')).reverted).toEqual(['/a']);
|
|
35
|
+
expect(calls).toEqual([['set-1', false]]);
|
|
36
|
+
expect(reverted()).toEqual(['set-1']);
|
|
37
|
+
await changes.revert('ta-1', 'set-1');
|
|
38
|
+
expect(reverted()).toEqual(['set-1']);
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it('remembers nothing while files conflict, and refuses for a session it does not have', async () => {
|
|
42
|
+
const { changes, reverted, detach } = service({ reverted: [], conflicts: ['/a'], skipped: [] });
|
|
43
|
+
expect((await changes.revert('ta-1', 'set-1')).conflicts).toEqual(['/a']);
|
|
44
|
+
expect(reverted()).toBeUndefined();
|
|
45
|
+
await changes.revert('ta-1', 'set-1', true);
|
|
46
|
+
expect(reverted()).toEqual(['set-1']);
|
|
47
|
+
expect((await changes.revert('ta-2', 'set-1')).refused).toBe('closed');
|
|
48
|
+
expect((await changes.latest('ta-1'))?.id).toBe('set-2');
|
|
49
|
+
expect(await changes.latest('ta-2')).toBeNull();
|
|
50
|
+
detach();
|
|
51
|
+
expect((await changes.revert('ta-1', 'set-1')).refused).toBe('closed');
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
it('reads kept contents for the page by their hash only', async () => {
|
|
55
|
+
const { changes } = service();
|
|
56
|
+
const name = await changes.store(new TextEncoder().encode('text'));
|
|
57
|
+
expect(await changes.read(name)).toBe('text');
|
|
58
|
+
expect(await changes.read('f'.repeat(64))).toBeNull();
|
|
59
|
+
await expect(changes.read('../x')).rejects.toThrow('is not the hash');
|
|
60
|
+
});
|
|
61
|
+
});
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import type { TaExtensionHost } from '@celljs/ta-protocol';
|
|
2
|
+
import { BlobStore } from './blob-store';
|
|
3
|
+
import { type ChangeSet, type ChangesService, type ChangesSession, NAME, REVERTED_KEPT, REVERTED_KEY, type RevertResult } from './changes-protocol';
|
|
4
|
+
|
|
5
|
+
/** The host of the package under ta serve: see {@link ChangesService}. */
|
|
6
|
+
export class DefaultChangesService implements ChangesService {
|
|
7
|
+
protected readonly sessions = new Map<string, ChangesSession>();
|
|
8
|
+
|
|
9
|
+
constructor(
|
|
10
|
+
protected readonly host: Pick<TaExtensionHost, 'listSessions' | 'getExtensionData' | 'setExtensionData'>,
|
|
11
|
+
protected readonly blobs: BlobStore,
|
|
12
|
+
) {}
|
|
13
|
+
|
|
14
|
+
dispose(): void {
|
|
15
|
+
this.sessions.clear();
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
store(data: Uint8Array): Promise<string> {
|
|
19
|
+
return this.blobs.store(data);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
load(hash: string): Promise<Uint8Array | undefined> {
|
|
23
|
+
return this.blobs.load(hash);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
attach(piSessionId: string, session: ChangesSession): () => void {
|
|
27
|
+
this.sessions.set(piSessionId, session);
|
|
28
|
+
return () => {
|
|
29
|
+
if (this.sessions.get(piSessionId) === session) {
|
|
30
|
+
this.sessions.delete(piSessionId);
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async read(hash: string): Promise<string | null> {
|
|
36
|
+
if (!BlobStore.isHash(hash)) {
|
|
37
|
+
throw new Error(`${String(hash)} is not the hash of kept contents.`);
|
|
38
|
+
}
|
|
39
|
+
const data = await this.blobs.load(hash);
|
|
40
|
+
return data ? new TextDecoder().decode(data) : null;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async latest(sessionId: string): Promise<ChangeSet | null> {
|
|
44
|
+
return (await this.session(sessionId))?.latest() ?? null;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
async revert(sessionId: string, id: string, force = false): Promise<RevertResult> {
|
|
48
|
+
if (typeof id !== 'string') {
|
|
49
|
+
throw new Error('revert takes the id of a session and the id of a change set.');
|
|
50
|
+
}
|
|
51
|
+
const session = await this.session(sessionId);
|
|
52
|
+
if (!session) {
|
|
53
|
+
return { reverted: [], conflicts: [], skipped: [], refused: 'closed' };
|
|
54
|
+
}
|
|
55
|
+
const result = await session.revert(id, force === true);
|
|
56
|
+
if (!result.refused && (force || !result.conflicts.length)) {
|
|
57
|
+
await this.markReverted(id);
|
|
58
|
+
}
|
|
59
|
+
return result;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
protected async session(sessionId: string): Promise<ChangesSession | undefined> {
|
|
63
|
+
if (typeof sessionId !== 'string') {
|
|
64
|
+
throw new Error(`${String(sessionId)} is not the id of a session.`);
|
|
65
|
+
}
|
|
66
|
+
const info = (await this.host.listSessions()).find(candidate => candidate.sessionId === sessionId);
|
|
67
|
+
return info && this.sessions.get(info.piSessionId);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
protected async markReverted(id: string): Promise<void> {
|
|
71
|
+
const value = await this.host.getExtensionData(NAME, REVERTED_KEY);
|
|
72
|
+
const ids = Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string' && item !== id) : [];
|
|
73
|
+
await this.host.setExtensionData(NAME, REVERTED_KEY, [...ids, id].slice(-REVERTED_KEPT));
|
|
74
|
+
}
|
|
75
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { describe, expect, it } from 'bun:test';
|
|
2
|
+
import { ChangesUtil } from './changes-util';
|
|
3
|
+
|
|
4
|
+
describe('ChangesUtil', () => {
|
|
5
|
+
it('places a file by its name and its directory, relative to the session', () => {
|
|
6
|
+
expect(ChangesUtil.place('/work/app/src/a.ts', '/work/app')).toEqual({ name: 'a.ts', dir: 'src' });
|
|
7
|
+
expect(ChangesUtil.place('/work/app/a.ts', '/work/app/')).toEqual({ name: 'a.ts', dir: '' });
|
|
8
|
+
expect(ChangesUtil.place('/tmp/report.html', '/work/app')).toEqual({ name: 'report.html', dir: '/tmp' });
|
|
9
|
+
expect(ChangesUtil.place('/a.ts', '/work')).toEqual({ name: 'a.ts', dir: '/' });
|
|
10
|
+
expect(ChangesUtil.place('/work/apple/a.ts', '/work/app')).toEqual({ name: 'a.ts', dir: '/work/apple' });
|
|
11
|
+
expect(ChangesUtil.place('C:\\work\\src\\a.ts', 'C:\\work')).toEqual({ name: 'a.ts', dir: 'src' });
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
it('tells text from binary as git does', () => {
|
|
15
|
+
expect(ChangesUtil.isText(new TextEncoder().encode('hello'))).toBe(true);
|
|
16
|
+
expect(ChangesUtil.isText(undefined)).toBe(true);
|
|
17
|
+
expect(ChangesUtil.isText(new Uint8Array([137, 80, 0, 1]))).toBe(false);
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
it('sums the lines and says what changed in words', () => {
|
|
21
|
+
const set = {
|
|
22
|
+
id: 'x',
|
|
23
|
+
root: '/work',
|
|
24
|
+
files: [
|
|
25
|
+
{ path: '/work/a.ts', added: 3, removed: 1, before: 'h1', after: 'h2' },
|
|
26
|
+
{ path: '/work/b.ts', added: 2, removed: 0, after: 'h3' },
|
|
27
|
+
],
|
|
28
|
+
};
|
|
29
|
+
expect(ChangesUtil.totals(set.files)).toEqual({ added: 5, removed: 1 });
|
|
30
|
+
expect(ChangesUtil.summary(set)).toBe('Changed 2 files: a.ts (+3 -1), b.ts (new, +2 -0)');
|
|
31
|
+
expect(ChangesUtil.revertNote(['/work/a.ts'], '/work')).toContain(': a.ts. Read them again');
|
|
32
|
+
});
|
|
33
|
+
});
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { ChangedFile, ChangeSet } from './changes-protocol';
|
|
2
|
+
|
|
3
|
+
export namespace ChangesUtil {
|
|
4
|
+
/** Text has no NUL byte in its first 8 KB, as git decides. */
|
|
5
|
+
export function isText(data: Uint8Array | undefined): boolean {
|
|
6
|
+
return !data?.subarray(0, 8000).includes(0);
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export function totals(files: ChangedFile[]): { added: number; removed: number } {
|
|
10
|
+
return files.reduce((sum, file) => ({ added: sum.added + file.added, removed: sum.removed + file.removed }), { added: 0, removed: 0 });
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** A path for people: relative to the session's directory when it is inside, else whole. */
|
|
14
|
+
export function relative(path: string, root: string): string {
|
|
15
|
+
const base = root.replace(/[\\/]+$/, '');
|
|
16
|
+
if (base && path.length > base.length && path.startsWith(base) && /[\\/]/.test(path[base.length])) {
|
|
17
|
+
return path.slice(base.length + 1);
|
|
18
|
+
}
|
|
19
|
+
return path;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** The name of a file and the directory it is in, as the list of changes shows them; `dir` is empty at the root. */
|
|
23
|
+
export function place(path: string, root: string): { name: string; dir: string } {
|
|
24
|
+
const shown = relative(path, root);
|
|
25
|
+
const index = Math.max(shown.lastIndexOf('/'), shown.lastIndexOf('\\'));
|
|
26
|
+
return index < 0 ? { name: shown, dir: '' } : { name: shown.slice(index + 1), dir: shown.slice(0, index) || shown.slice(0, 1) };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** The text of the message, for whoever reads the session without the web client (pi's terminal, an export). */
|
|
30
|
+
export function summary(set: ChangeSet): string {
|
|
31
|
+
const files = set.files.map(
|
|
32
|
+
file => `${relative(file.path, set.root)} (${file.before === undefined && !file.large ? 'new, ' : ''}+${file.added} -${file.removed})`,
|
|
33
|
+
);
|
|
34
|
+
return `Changed ${set.files.length === 1 ? '1 file' : `${set.files.length} files`}: ${files.join(', ')}`;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** What Ta reads after the user took the changes of a reply back. */
|
|
38
|
+
export function revertNote(paths: string[], root: string): string {
|
|
39
|
+
return (
|
|
40
|
+
'The user took back the changes you made to these files in one of your earlier replies; they are as they were before that reply: ' +
|
|
41
|
+
`${paths.map(path => relative(path, root)).join(', ')}. Read them again before you change them.`
|
|
42
|
+
);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import type { ChangedFile, ChangeSet } from './changes-protocol';
|
|
2
|
+
import { ChangesUtil } from './changes-util';
|
|
3
|
+
import { icon, message, pi, t } from './page';
|
|
4
|
+
import { React } from './react';
|
|
5
|
+
|
|
6
|
+
/** Opens the diff of a file of a reply in the workbench, as a preview tab. */
|
|
7
|
+
export function openDiff(set: ChangeSet, file: ChangedFile): void {
|
|
8
|
+
const { name } = ChangesUtil.place(file.path, set.root);
|
|
9
|
+
pi.ui.openEditor(
|
|
10
|
+
{
|
|
11
|
+
id: `ta-changes:${set.id}:${file.path}`,
|
|
12
|
+
title: () => t('diffTitle', { name }),
|
|
13
|
+
icon: icon('FileDiff'),
|
|
14
|
+
render: () => <DiffTab set={set} file={file} />,
|
|
15
|
+
},
|
|
16
|
+
{ preview: true },
|
|
17
|
+
);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
async function text(hash: string | undefined): Promise<string | null> {
|
|
21
|
+
return hash ? pi.callHost<string | null>('read', hash) : '';
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function DiffTab({ set, file }: { set: ChangeSet; file: ChangedFile }) {
|
|
25
|
+
const [texts, setTexts] = React.useState<{ before: string; after: string } | { error: string }>();
|
|
26
|
+
React.useEffect(() => {
|
|
27
|
+
if (file.binary || file.large) {
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
let live = true;
|
|
31
|
+
Promise.all([text(file.before), text(file.after)]).then(
|
|
32
|
+
([before, after]) => live && setTexts(before === null || after === null ? { error: t('gone') } : { before, after }),
|
|
33
|
+
error => live && setTexts({ error: message(error) }),
|
|
34
|
+
);
|
|
35
|
+
return () => {
|
|
36
|
+
live = false;
|
|
37
|
+
};
|
|
38
|
+
}, [file]);
|
|
39
|
+
const empty = file.binary ? t('binary') : file.large ? t('large') : !texts ? t('loading') : 'error' in texts ? texts.error : undefined;
|
|
40
|
+
return (
|
|
41
|
+
<div className="tcg-diff">
|
|
42
|
+
<div className="tcg-diff-head">
|
|
43
|
+
<span className="tcg-diff-path" title={file.path}>
|
|
44
|
+
{ChangesUtil.relative(file.path, set.root)}
|
|
45
|
+
</span>
|
|
46
|
+
<span className="tcg-stat">
|
|
47
|
+
<span className="tcg-add">+{file.added}</span>
|
|
48
|
+
<span className="tcg-del">−{file.removed}</span>
|
|
49
|
+
</span>
|
|
50
|
+
</div>
|
|
51
|
+
<div className="tcg-diff-body">
|
|
52
|
+
{empty !== undefined || !texts || 'error' in texts ? (
|
|
53
|
+
<div className="tcg-diff-empty">{empty}</div>
|
|
54
|
+
) : (
|
|
55
|
+
<pi.ui.DiffEditor path={file.path} original={texts.before} modified={texts.after} />
|
|
56
|
+
)}
|
|
57
|
+
</div>
|
|
58
|
+
</div>
|
|
59
|
+
);
|
|
60
|
+
}
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import type { TaSessionFiles } from '@celljs/ta-protocol';
|
|
2
|
+
import {
|
|
3
|
+
CHANGES_TYPE,
|
|
4
|
+
type ChangeSet,
|
|
5
|
+
type ChangesService,
|
|
6
|
+
NAME,
|
|
7
|
+
REVERT_TYPE,
|
|
8
|
+
type RevertDetails,
|
|
9
|
+
type RevertResult,
|
|
10
|
+
TA_FILE_WRITE_EVENT,
|
|
11
|
+
TA_HOST_EVENT,
|
|
12
|
+
} from './changes-protocol';
|
|
13
|
+
import { ChangesUtil } from './changes-util';
|
|
14
|
+
import { ChangeRecorder, revert } from './recorder';
|
|
15
|
+
|
|
16
|
+
/** Under ta serve the host answers at once; `ta` alone has nobody to answer, and nothing shows the changes. */
|
|
17
|
+
const HOST_WAIT_MS = 1000;
|
|
18
|
+
/** The tools that write files, with the file in `path`. */
|
|
19
|
+
const WRITING_TOOLS = new Set(['edit', 'write']);
|
|
20
|
+
|
|
21
|
+
/** The little of pi's extension API this uses. */
|
|
22
|
+
interface Entry {
|
|
23
|
+
type: string;
|
|
24
|
+
customType?: string;
|
|
25
|
+
details?: unknown;
|
|
26
|
+
}
|
|
27
|
+
interface Context {
|
|
28
|
+
isIdle(): boolean;
|
|
29
|
+
sessionManager: { getSessionId(): string; getEntries(): Entry[]; getBranch(): Entry[] };
|
|
30
|
+
}
|
|
31
|
+
interface Message {
|
|
32
|
+
role: string;
|
|
33
|
+
customType?: string;
|
|
34
|
+
}
|
|
35
|
+
interface Pi {
|
|
36
|
+
events: { emit(event: string, data: unknown): void; on(event: string, handler: (data: unknown) => void): unknown };
|
|
37
|
+
on(event: string, handler: (event: never, ctx: never) => unknown): unknown;
|
|
38
|
+
sendMessage(message: { customType: string; content: string; display: boolean; details: unknown }): void;
|
|
39
|
+
}
|
|
40
|
+
interface Reached {
|
|
41
|
+
files: TaSessionFiles;
|
|
42
|
+
service: ChangesService;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* The pi extension: before edit or write change a file the first time in a reply, or another coding
|
|
47
|
+
* agent says its tools will (TA_FILE_WRITE_EVENT), it keeps what is there; when the reply ends, a message lists what changed (CHANGES_TYPE), which the web extension
|
|
48
|
+
* shows above the message box. Ta does not read that message. It takes a reply's changes back when the page asks, through the host.
|
|
49
|
+
*/
|
|
50
|
+
export default function activate(pi: Pi): void {
|
|
51
|
+
let reached: Promise<Reached | undefined> | undefined;
|
|
52
|
+
let recorder: ChangeRecorder | undefined;
|
|
53
|
+
let detach: (() => void) | undefined;
|
|
54
|
+
/** Set with the recorder: the event of another agent's writes is answered at once, without waiting for the host. */
|
|
55
|
+
let reachedFiles: TaSessionFiles | undefined;
|
|
56
|
+
const reach = () =>
|
|
57
|
+
(reached ??= new Promise(resolve => {
|
|
58
|
+
const timer = setTimeout(() => resolve(undefined), HOST_WAIT_MS);
|
|
59
|
+
pi.events.emit(TA_HOST_EVENT, {
|
|
60
|
+
name: NAME,
|
|
61
|
+
resolve: (answer: { service?: unknown; files?: TaSessionFiles }) => {
|
|
62
|
+
clearTimeout(timer);
|
|
63
|
+
resolve(answer.service && answer.files ? { service: answer.service as ChangesService, files: answer.files } : undefined);
|
|
64
|
+
},
|
|
65
|
+
});
|
|
66
|
+
}));
|
|
67
|
+
|
|
68
|
+
pi.on('session_start', async (_event: unknown, ctx: Context) => {
|
|
69
|
+
const found = await reach();
|
|
70
|
+
if (!found) {
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
recorder = new ChangeRecorder(found.files, found.service);
|
|
74
|
+
reachedFiles = found.files;
|
|
75
|
+
detach?.();
|
|
76
|
+
detach = found.service.attach(ctx.sessionManager.getSessionId(), {
|
|
77
|
+
revert: (id, force) => takeBack(ctx, found, id, force),
|
|
78
|
+
latest: () => changeSets(ctx.sessionManager.getBranch()).at(-1),
|
|
79
|
+
});
|
|
80
|
+
});
|
|
81
|
+
pi.on('session_shutdown', () => {
|
|
82
|
+
detach?.();
|
|
83
|
+
detach = undefined;
|
|
84
|
+
});
|
|
85
|
+
pi.on('tool_call', async (event: { toolName: string; input?: { path?: unknown } }) => {
|
|
86
|
+
const path = event.input?.path;
|
|
87
|
+
if (recorder && WRITING_TOOLS.has(event.toolName) && typeof path === 'string' && path) {
|
|
88
|
+
const found = await reach();
|
|
89
|
+
if (found) {
|
|
90
|
+
await recorder.before(found.files.resolve(path));
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
});
|
|
94
|
+
// Another coding agent writes with its own tools (ta-agents): it says so, before the write if it can.
|
|
95
|
+
pi.events.on(TA_FILE_WRITE_EVENT, data => {
|
|
96
|
+
const file = data as { path?: unknown; before?: unknown } | undefined;
|
|
97
|
+
if (recorder && reachedFiles && typeof file?.path === 'string' && file.path) {
|
|
98
|
+
const before = typeof file.before === 'string' || file.before === null ? file.before : undefined;
|
|
99
|
+
void recorder.before(reachedFiles.resolve(file.path), before);
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
pi.on('agent_settled', async () => {
|
|
103
|
+
const found = recorder && (await reach());
|
|
104
|
+
const set = found && (await recorder?.finish(found.files.resolve('.')));
|
|
105
|
+
if (set) {
|
|
106
|
+
pi.sendMessage({ customType: CHANGES_TYPE, content: ChangesUtil.summary(set), display: false, details: set });
|
|
107
|
+
}
|
|
108
|
+
});
|
|
109
|
+
// The list is for the user: Ta knows what it changed from its own calls.
|
|
110
|
+
pi.on('context', (event: { messages: Message[] }) => {
|
|
111
|
+
const messages = event.messages.filter(message => !(message.role === 'custom' && message.customType === CHANGES_TYPE));
|
|
112
|
+
return messages.length === event.messages.length ? undefined : { messages };
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
async function takeBack(ctx: Context, found: Reached, id: string, force: boolean): Promise<RevertResult> {
|
|
116
|
+
if (!ctx.isIdle()) {
|
|
117
|
+
return { reverted: [], conflicts: [], skipped: [], refused: 'busy' };
|
|
118
|
+
}
|
|
119
|
+
const set = find(ctx, id);
|
|
120
|
+
if (!set) {
|
|
121
|
+
return { reverted: [], conflicts: [], skipped: [], refused: 'missing' };
|
|
122
|
+
}
|
|
123
|
+
const result = await revert(set, found.files, found.service, force);
|
|
124
|
+
if (result.reverted.length) {
|
|
125
|
+
const details: RevertDetails = { id, files: result.reverted };
|
|
126
|
+
pi.sendMessage({ customType: REVERT_TYPE, content: ChangesUtil.revertNote(result.reverted, set.root), display: true, details });
|
|
127
|
+
}
|
|
128
|
+
return result;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function find(ctx: Context, id: string): ChangeSet | undefined {
|
|
133
|
+
return changeSets(ctx.sessionManager.getEntries()).find(set => set.id === id);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function changeSets(entries: Entry[]): ChangeSet[] {
|
|
137
|
+
return entries.flatMap(entry => {
|
|
138
|
+
const details = entry.details as Partial<ChangeSet> | undefined;
|
|
139
|
+
return entry.type === 'custom_message' && entry.customType === CHANGES_TYPE && typeof details?.id === 'string' && Array.isArray(details.files)
|
|
140
|
+
? [details as ChangeSet]
|
|
141
|
+
: [];
|
|
142
|
+
});
|
|
143
|
+
}
|