-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathqueue-state.ts
More file actions
327 lines (284 loc) · 10 KB
/
Copy pathqueue-state.ts
File metadata and controls
327 lines (284 loc) · 10 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
export type QueueLane = "steer" | "followUp";
/** A queued row that executes a Pi command instead of becoming an LLM message. */
export interface QueuedCommand {
kind: "compact" | "reload";
instructions?: string;
}
/**
* Parse row text as a queueable command. Commands are recognised at dispatch
* and render time, so editing a row into or out of command form just works.
*/
export function parseQueuedCommand(text: string): QueuedCommand | undefined {
const trimmed = text.trim();
if (trimmed === "/reload") return { kind: "reload" };
if (trimmed === "/compact") return { kind: "compact" };
if (trimmed.startsWith("/compact ")) {
const instructions = trimmed.slice("/compact ".length).trim();
return { kind: "compact", instructions: instructions || undefined };
}
return undefined;
}
export interface QueuedMessage<TImage = unknown> {
id: string;
lane: QueueLane;
text: string;
images: TImage[];
sequence: number;
}
/**
* Two independent FIFOs presented as one delivery-ordered timeline.
*
* Steering rows always appear before follow-ups because Pi consumes that lane
* first. Sequence is global so queue editing can enter at the most recently
* enqueued row even when that row sits in the middle of the visual timeline.
*/
export class DeliveryQueue<TImage = unknown> {
private items: QueuedMessage<TImage>[] = [];
private nextIdNumber = 1;
private nextSequence = 1;
enqueue(lane: QueueLane, text: string, images: readonly TImage[] = []): QueuedMessage<TImage> {
const prefix = lane === "steer" ? "steer" : "follow-up";
const item = {
id: `${prefix}-${this.nextIdNumber++}`,
lane,
text,
images: [...images],
sequence: this.nextSequence++,
};
this.items.push(item);
return this.copy(item);
}
prepend(item: QueuedMessage<TImage>): void {
const firstInLane = this.items.findIndex((candidate) => candidate.lane === item.lane);
if (firstInLane === -1) this.items.push(this.copy(item));
else this.items.splice(firstInLane, 0, this.copy(item));
}
prependMany(items: readonly QueuedMessage<TImage>[]): void {
for (let index = items.length - 1; index >= 0; index -= 1) {
const item = items[index];
if (item) this.prepend(item);
}
}
update(id: string, text: string, images?: readonly TImage[]): boolean {
const item = this.items.find((candidate) => candidate.id === id);
if (!item) return false;
item.text = text;
if (images) item.images = [...images];
return true;
}
/** Reclassify a row into the other lane, joining that lane's tail. */
moveToLaneTail(id: string, lane: QueueLane): boolean {
const index = this.items.findIndex((item) => item.id === id);
if (index === -1) return false;
const [item] = this.items.splice(index, 1);
if (!item) return false;
item.lane = lane;
this.items.push(item);
return true;
}
remove(id: string): QueuedMessage<TImage> | undefined {
const index = this.items.findIndex((item) => item.id === id);
if (index === -1) return undefined;
const [item] = this.items.splice(index, 1);
return item ? this.copy(item) : undefined;
}
peek(lane: QueueLane): QueuedMessage<TImage> | undefined {
const item = this.items.find((candidate) => candidate.lane === lane);
return item ? this.copy(item) : undefined;
}
shift(lane: QueueLane): QueuedMessage<TImage> | undefined {
const index = this.items.findIndex((item) => item.lane === lane);
if (index === -1) return undefined;
const [item] = this.items.splice(index, 1);
return item ? this.copy(item) : undefined;
}
shiftAll(lane: QueueLane): QueuedMessage<TImage>[] {
const removed = this.items.filter((item) => item.lane === lane).map((item) => this.copy(item));
this.items = this.items.filter((item) => item.lane !== lane);
return removed;
}
/**
* Shift rows from the lane head while the predicate accepts them, preserving
* FIFO order. Stops at (and keeps) the first rejected row, so an `all`-mode
* batch never crosses a command row.
*/
shiftWhile(lane: QueueLane, accept: (item: QueuedMessage<TImage>) => boolean): QueuedMessage<TImage>[] {
const taken: QueuedMessage<TImage>[] = [];
for (;;) {
const index = this.items.findIndex((item) => item.lane === lane);
if (index === -1 || !accept(this.items[index])) break;
const [item] = this.items.splice(index, 1);
if (!item) break;
taken.push(this.copy(item));
}
return taken;
}
get(id: string): QueuedMessage<TImage> | undefined {
const item = this.items.find((candidate) => candidate.id === id);
return item ? this.copy(item) : undefined;
}
previousId(currentId?: string): string | undefined {
const ordered = this.snapshot();
if (ordered.length === 0) return undefined;
if (!currentId) return this.mostRecentId();
const index = ordered.findIndex((item) => item.id === currentId);
if (index <= 0) return ordered.at(-1)?.id;
return ordered[index - 1]?.id;
}
nextId(currentId?: string): string | undefined {
const ordered = this.snapshot();
if (ordered.length === 0) return undefined;
if (!currentId) return this.mostRecentId();
const index = ordered.findIndex((item) => item.id === currentId);
if (index === -1 || index === ordered.length - 1) return ordered[0]?.id;
return ordered[index + 1]?.id;
}
mostRecentId(): string | undefined {
let newest: QueuedMessage<TImage> | undefined;
for (const item of this.items) {
if (!newest || item.sequence > newest.sequence) newest = item;
}
return newest?.id;
}
laneSnapshot(lane: QueueLane): QueuedMessage<TImage>[] {
return this.items.filter((item) => item.lane === lane).map((item) => this.copy(item));
}
snapshot(): QueuedMessage<TImage>[] {
return [...this.laneSnapshot("steer"), ...this.laneSnapshot("followUp")];
}
laneLength(lane: QueueLane): number {
return this.items.filter((item) => item.lane === lane).length;
}
get length(): number {
return this.items.length;
}
/** Restore an in-memory queue snapshot without changing row identity or recency. */
restore(items: readonly QueuedMessage<TImage>[]): void {
const ids = new Set<string>();
let highestIdNumber = 0;
let highestSequence = 0;
const restored: QueuedMessage<TImage>[] = [];
for (const item of items) {
if (ids.has(item.id)) throw new Error(`Duplicate queued row ID: ${item.id}`);
ids.add(item.id);
const idNumber = /-(\d+)$/.exec(item.id)?.[1];
if (idNumber) highestIdNumber = Math.max(highestIdNumber, Number.parseInt(idNumber, 10));
highestSequence = Math.max(highestSequence, item.sequence);
restored.push(this.copy(item));
}
this.items = restored;
this.nextIdNumber = highestIdNumber + 1;
this.nextSequence = highestSequence + 1;
}
clear(): void {
this.items = [];
}
private copy(item: QueuedMessage<TImage>): QueuedMessage<TImage> {
return { ...item, images: [...item.images] };
}
}
interface QueuedMessageDraft<TImage> {
id: string;
text: string;
images: TImage[];
lane: QueueLane;
removed: boolean;
}
export interface EditCommitResult {
updated: number;
removed: number;
moved: number;
}
/** Rollback-safe drafts spanning rows from either delivery lane. */
export class QueueEditSession<TImage = unknown> {
private readonly drafts = new Map<string, QueuedMessageDraft<TImage>>();
private currentId: string;
readonly composerDraft: string;
constructor(item: QueuedMessage<TImage>, composerDraft: string) {
this.currentId = item.id;
this.composerDraft = composerDraft;
this.drafts.set(item.id, this.newDraft(item));
}
private newDraft(item: QueuedMessage<TImage>): QueuedMessageDraft<TImage> {
return { id: item.id, text: item.text, images: [...item.images], lane: item.lane, removed: false };
}
get selectedId(): string {
return this.currentId;
}
get selectedText(): string {
return this.drafts.get(this.currentId)?.text ?? "";
}
capture(text: string, images?: readonly TImage[]): void {
const draft = this.drafts.get(this.currentId);
if (!draft) return;
draft.text = text;
if (images) draft.images = [...images];
}
select(item: QueuedMessage<TImage>, currentText: string, images?: readonly TImage[]): string {
this.capture(currentText, images);
if (!this.drafts.has(item.id)) {
this.drafts.set(item.id, this.newDraft(item));
}
this.currentId = item.id;
return this.selectedText;
}
/** Toggle whether the row is deleted on save. Returns the new mark. */
toggleRemoved(id: string): boolean | undefined {
const draft = this.drafts.get(id);
if (!draft) return undefined;
draft.removed = !draft.removed;
return draft.removed;
}
/** Toggle the row's draft delivery lane. Returns the new lane. */
toggleLane(id: string): QueueLane | undefined {
const draft = this.drafts.get(id);
if (!draft) return undefined;
draft.lane = draft.lane === "steer" ? "followUp" : "steer";
return draft.lane;
}
laneFor(id: string): QueueLane | undefined {
return this.drafts.get(id)?.lane;
}
isRemoved(id: string): boolean {
return this.drafts.get(id)?.removed ?? false;
}
touches(id: string): boolean {
return this.drafts.has(id);
}
touchesLane(queue: DeliveryQueue<TImage>, lane: QueueLane): boolean {
return queue.laneSnapshot(lane).some((item) => this.touches(item.id));
}
textFor(id: string): string | undefined {
return this.drafts.get(id)?.text;
}
imagesFor(id: string): TImage[] | undefined {
const images = this.drafts.get(id)?.images;
return images ? [...images] : undefined;
}
commit(
queue: DeliveryQueue<TImage>,
currentText: string,
images?: readonly TImage[],
): EditCommitResult {
this.capture(currentText, images);
let updated = 0;
let removed = 0;
let moved = 0;
for (const draft of this.drafts.values()) {
if (draft.removed || (!draft.text.trim() && draft.images.length === 0)) {
if (queue.remove(draft.id)) removed += 1;
continue;
}
if (queue.update(draft.id, draft.text, draft.images)) updated += 1;
}
// Apply lane moves in queue order so multi-row moves land at the
// destination tail in the same order the timeline previewed them.
for (const item of queue.snapshot()) {
const draft = this.drafts.get(item.id);
if (draft && !draft.removed && draft.lane !== item.lane) {
if (queue.moveToLaneTail(item.id, draft.lane)) moved += 1;
}
}
return { updated, removed, moved };
}
}