akanjs 3.1.0-rc.11 → 3.1.0-rc.13

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.
@@ -18,6 +18,8 @@ export interface CodeAgentSessionInfo {
18
18
  contextTokens: number | undefined;
19
19
  /** Absent when the model does no reasoning at all, which is not reasoning turned `off`. */
20
20
  effort: CodeAgentEffort | undefined;
21
+ /** Percent of the window that starts a compaction; absent leaves the engine's own, later threshold. */
22
+ autoCompactAt: number | undefined;
21
23
  /** Absent until the session has been asked something. */
22
24
  name: string | undefined;
23
25
  /** `await` keeps a question inside its turn; `suspend` ends the turn (`awaiting`) and the answer opens a new one. */
@@ -186,6 +188,8 @@ export type CodeAgentCommand =
186
188
  | { type: "abort" }
187
189
  | { type: "compact"; instructions?: string }
188
190
  | { type: "set_model"; provider: string; modelId: string }
191
+ /** `percent` in steps of 10; absent, or 100, restores the default. */
192
+ | { type: "set_auto_compact"; percent?: number }
189
193
  | { type: "fork"; entryId: string }
190
194
  | { type: "new_session" }
191
195
  /** Current state, plus every frame after `sinceSeq` when one is given. */
@@ -231,8 +235,11 @@ export const codeAgentEventLabel = (event: CodeAgentEventBody): string => {
231
235
  `session ${event.info.sessionId}`,
232
236
  event.info.model?.name ?? "no model",
233
237
  event.info.contextTokens ? `${Math.round(event.info.contextTokens / 1000)}k ctx` : "unknown ctx",
238
+ event.info.autoCompactAt ? `compacts at ${event.info.autoCompactAt}%` : "",
234
239
  event.info.profile,
235
- ].join(" · ");
240
+ ]
241
+ .filter((part) => !!part)
242
+ .join(" · ");
236
243
  case "turn_start":
237
244
  return "turn start";
238
245
  case "turn_end":
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "akanjs",
3
- "version": "3.1.0-rc.11",
3
+ "version": "3.1.0-rc.13",
4
4
  "sourceType": "module",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -94,8 +94,15 @@ export class CascadeRunner {
94
94
  await service.__removeMany({ id: documentQueryHelper.oneOf(ids) });
95
95
  return;
96
96
  }
97
+
98
+ const live = new Set<string>();
99
+ for (let start = 0; start < ids.length; start += drainSize) {
100
+ const chunk = ids.slice(start, start + drainSize);
101
+ for (const id of await service.__listIds({ id: documentQueryHelper.oneOf(chunk) })) live.add(id);
102
+ }
97
103
 
98
104
  for (const id of ids) {
105
+ if (!live.has(id)) continue;
99
106
 
100
107
  if (seen.has(`${edge.refName}:${id}`)) continue;
101
108
  seen.add(`${edge.refName}:${id}`);
@@ -879,8 +879,11 @@ export class RscRenderer {
879
879
  } = {},
880
880
  ): Promise<FlightRenderResult> {
881
881
  const controlRef: { current: RenderControl | null } = { current: null };
882
+
883
+ let isCancelling = false;
882
884
  const stream = await renderToReadableStream(element, clientManifest, {
883
885
  onError: (error) => {
886
+ if (isCancelling || (options.requestId && this.#cancelledRenderRequests.has(options.requestId))) return;
884
887
  if (isAkanRedirectError(error)) {
885
888
  const { location, method, status } = error;
886
889
  controlRef.current = { type: "redirect", location, method, status };
@@ -927,6 +930,11 @@ export class RscRenderer {
927
930
  reportedTheme = theme;
928
931
  this.#send({ type: "theme", requestId: options.requestId, theme });
929
932
  };
933
+ const cancelWith = async (control: RenderControl | null, cancelled: boolean): Promise<FlightRenderResult> => {
934
+ isCancelling = true;
935
+ await reader.cancel();
936
+ return { chunks, bytes, chunksCount, control, lateControlSent, cancelled };
937
+ };
930
938
  const readProbe = () => {
931
939
  if (!controlRef.current && options.notFoundProbe?.hit) controlRef.current = { type: "not-found" };
932
940
  };
@@ -953,26 +961,18 @@ export class RscRenderer {
953
961
  };
954
962
  try {
955
963
  for (;;) {
956
- if (options.requestId && this.#cancelledRenderRequests.has(options.requestId)) {
957
- await reader.cancel();
958
- return { chunks, bytes, chunksCount, control: null, lateControlSent, cancelled: true };
959
- }
964
+ if (options.requestId && this.#cancelledRenderRequests.has(options.requestId))
965
+ return await cancelWith(null, true);
960
966
  const { value, done } = await reader.read();
961
967
  readProbe();
962
- if (controlRef.current && !sentChunk) {
963
- await reader.cancel();
964
- return { chunks, bytes, chunksCount, control: controlRef.current, lateControlSent, cancelled: false };
965
- }
968
+ if (controlRef.current && !sentChunk) return await cancelWith(controlRef.current, false);
966
969
  if (controlRef.current && sentChunk) sendLateControl();
967
970
  if (done) break;
968
971
 
969
972
  if (!sentChunk && options.requestId) {
970
973
  await new Promise((resolve) => setTimeout(resolve, 0));
971
974
  readProbe();
972
- if (controlRef.current) {
973
- await reader.cancel();
974
- return { chunks, bytes, chunksCount, control: controlRef.current, lateControlSent, cancelled: false };
975
- }
975
+ if (controlRef.current) return await cancelWith(controlRef.current, false);
976
976
  }
977
977
  const chunk = value instanceof Uint8Array ? value : new Uint8Array(value as ArrayBufferLike);
978
978
  bytes += chunk.byteLength;
package/store/action.ts CHANGED
@@ -136,7 +136,7 @@ type BaseAction<
136
136
  ) => Promise<void>;
137
137
  } & { [K in `set${_CapitalizedRefName}`]: (...models: (Full | Light)[]) => void } & {
138
138
  [K in `reset${_CapitalizedRefName}`]: (model?: Full) => void;
139
- };
139
+ } & { [K in `invalidate${_CapitalizedRefName}`]: () => void };
140
140
 
141
141
  export type SliceAction<
142
142
  RefName extends string,
@@ -310,9 +310,19 @@ export const makeFormSetter = (refName: string, fetch: FetchProxy<any>) => {
310
310
 
311
311
  const names = {
312
312
  modelForm: `${fieldName}Form`,
313
+ modelFormUploading: databaseStateNames(refName).modelFormUploading,
313
314
  writeOnModel: `writeOn${className}`,
314
315
  addModelFiles: `add${className}Files`,
315
316
  };
317
+ type UploadState = { [key: string]: { [field: string]: string[] } };
318
+ let uploadSeq = 0;
319
+ const releaseUpload = (state: UploadState, field: string, ticket?: string) => {
320
+ const pending = state[names.modelFormUploading][field];
321
+ if (!pending || (ticket && !pending.includes(ticket))) return;
322
+ const { [field]: tickets = [], ...rest } = state[names.modelFormUploading];
323
+ const left = ticket ? tickets.filter((pending) => pending !== ticket) : [];
324
+ state[names.modelFormUploading] = left.length ? { ...rest, [field]: left } : rest;
325
+ };
316
326
  const baseSetAction = {
317
327
  [names.writeOnModel]: function (this: SetGet, path: string | (string | number)[], value: any) {
318
328
  this.set((state: { [key: string]: any }) => {
@@ -322,9 +332,13 @@ export const makeFormSetter = (refName: string, fetch: FetchProxy<any>) => {
322
332
  };
323
333
  const fieldSetAction = Object.entries(modelRef[FIELD_META]).reduce((acc, [key, field]) => {
324
334
  const namesOfField = formSetterNames(className, key);
335
+ const isFileField =
336
+ field.isClass && !!fileUploadRefName && ConstantRegistry.getRefName(field.modelRef) === fileUploadRefName;
325
337
  const singleFieldSetAction = {
326
338
  [namesOfField.setFieldOnModel]: function (this: SetGet, value: any | null) {
327
339
  this.set((state: { [key: string]: any }) => {
340
+
341
+ if (isFileField && !field.isArray) releaseUpload(state as UploadState, namesOfField.field);
328
342
  const setValue =
329
343
  value === null
330
344
  ? null
@@ -384,56 +398,88 @@ export const makeFormSetter = (refName: string, fetch: FetchProxy<any>) => {
384
398
  },
385
399
  }
386
400
  : {}),
387
- ...(field.isClass && fileUploadRefName && ConstantRegistry.getRefName(field.modelRef) === fileUploadRefName
401
+ ...(isFileField && fileUploadRefName
388
402
  ? {
389
403
  [namesOfField.uploadFieldOnModel]: async function (
390
404
  this: SetGet,
391
405
  fileList: FileList | File[],
392
406
  index?: number,
393
407
  ) {
394
- const form = (this.get() as { [key: string]: any })[names.modelForm] as { [key: string]: any };
408
+ const formId = ((this.get() as { [key: string]: any })[names.modelForm] as { id?: string }).id;
395
409
  if (!fileList.length) return;
396
- const files = await (fetch[names.addModelFiles] as (...args: any) => Promise<ProtoFile[]>)(
397
- fileList,
398
- form.id,
399
- );
400
- if (field.isArray) {
401
- const idx = index ?? (form[namesOfField.field] as ProtoLightFile[]).length;
402
- this.set((state: { [key: string]: { [key: string]: ProtoLightFile[] } }) => {
403
- state[names.modelForm][namesOfField.field] = [
404
- ...(form[namesOfField.field] as ProtoLightFile[]).slice(0, idx),
405
- ...files,
406
- ...(form[namesOfField.field] as ProtoLightFile[]).slice(idx),
407
- ];
408
- });
409
- } else {
410
- this.set((state: { [key: string]: { [key: string]: ProtoLightFile | null } }) => {
411
- state[names.modelForm][namesOfField.field] = files[0];
412
- });
410
+
411
+ const ticket = `${++uploadSeq}`;
412
+ this.set((state: UploadState) => {
413
+ const tickets = state[names.modelFormUploading][namesOfField.field] ?? [];
414
+ state[names.modelFormUploading] = {
415
+ ...state[names.modelFormUploading],
416
+ [namesOfField.field]: field.isArray ? [...tickets, ticket] : [ticket],
417
+ };
418
+ });
419
+ const held = (state: { [key: string]: any }) =>
420
+ !!(state as UploadState)[names.modelFormUploading][namesOfField.field]?.includes(ticket) &&
421
+ (state[names.modelForm] as { id?: string }).id === formId;
422
+ let files: ProtoFile[];
423
+ try {
424
+ files = await (fetch[names.addModelFiles] as (...args: any) => Promise<ProtoFile[]>)(fileList, formId);
425
+ } catch (error) {
426
+ this.set((state: UploadState) => releaseUpload(state, namesOfField.field, ticket));
427
+ throw error;
413
428
  }
429
+ let isWritten = false;
430
+
431
+ this.set((state: { [key: string]: any }) => {
432
+ isWritten = held(state);
433
+ releaseUpload(state as UploadState, namesOfField.field, ticket);
434
+ if (!isWritten) return;
435
+ const form = state[names.modelForm] as { [key: string]: ProtoLightFile[] | ProtoLightFile | null };
436
+ if (field.isArray) {
437
+ const current = (form[namesOfField.field] as ProtoLightFile[] | null) ?? [];
438
+ const idx = Math.min(index ?? current.length, current.length);
439
+ form[namesOfField.field] = [...current.slice(0, idx), ...files, ...current.slice(idx)];
440
+ } else form[namesOfField.field] = files[0] ?? null;
441
+ });
442
+ if (!isWritten) return;
443
+ const postSet = (this as unknown as { [key: string]: ((value: unknown) => unknown) | undefined })[
444
+ namesOfField.postSetField
445
+ ];
446
+ if (postSet)
447
+ void postSet.call(this, (this.get() as { [key: string]: any })[names.modelForm][namesOfField.field]);
414
448
 
415
449
  const fileReadName = ConstantRegistry.isLight(field.modelRef)
416
450
  ? `light${capitalize(fileUploadRefName)}`
417
451
  : fileUploadRefName;
452
+ const holdsFile = (id: string) => {
453
+ const value = (this.get() as { [key: string]: { [key: string]: unknown } })[names.modelForm][
454
+ namesOfField.field
455
+ ] as ProtoLightFile | ProtoLightFile[] | null;
456
+ return Array.isArray(value) ? value.some((heldFile) => heldFile.id === id) : value?.id === id;
457
+ };
418
458
  files.forEach((file) => {
419
459
  let attemptsLeft = UPLOAD_POLL_ATTEMPTS;
420
460
  const intervalKey = setInterval(() => {
421
461
  void (async () => {
462
+ if (!holdsFile(file.id)) {
463
+ clearInterval(intervalKey);
464
+ return;
465
+ }
422
466
  attemptsLeft -= 1;
423
467
  try {
424
468
  const currentFile = await (
425
469
  (fetch as { [key: string]: any })[fileReadName] as (id: string) => Promise<ProtoLightFile>
426
470
  )(file.id);
427
- if (field.isArray)
428
- this.set((state: { [key: string]: { [key: string]: ProtoLightFile[] } }) => {
429
- state[names.modelForm][namesOfField.field] = state[names.modelForm][namesOfField.field].map(
430
- (file) => (file.id === currentFile.id ? currentFile : file),
431
- );
432
- });
433
- else
434
- this.set((state: { [key: string]: { [key: string]: ProtoLightFile | null } }) => {
435
- state[names.modelForm][namesOfField.field] = currentFile;
436
- });
471
+ if (!holdsFile(currentFile.id)) {
472
+ clearInterval(intervalKey);
473
+ return;
474
+ }
475
+ this.set(
476
+ (state: { [key: string]: { [key: string]: ProtoLightFile[] | ProtoLightFile | null } }) => {
477
+ const value = state[names.modelForm][namesOfField.field];
478
+ state[names.modelForm][namesOfField.field] = Array.isArray(value)
479
+ ? value.map((heldFile) => (heldFile.id === currentFile.id ? currentFile : heldFile))
480
+ : currentFile;
481
+ },
482
+ );
437
483
  if (currentFile.status !== "uploading" || attemptsLeft <= 0) clearInterval(intervalKey);
438
484
  } catch (error) {
439
485
  clearInterval(intervalKey);
@@ -497,10 +543,14 @@ export const makeActions = (refName: string, slice: { [key: string]: SerializedS
497
543
  viewModel: `view${className}`,
498
544
  setModel: `set${className}`,
499
545
  resetModel: `reset${className}`,
546
+ invalidateModel: `invalidate${className}`,
500
547
  loadModelDraft: `load${className}FormDraft`,
501
548
  restoreModelDraft: `restore${className}FormDraft`,
502
549
  discardModelDraft: `discard${className}FormDraft`,
503
550
  };
551
+
552
+ const isUploadingIn = (state: { [key: string]: any }) =>
553
+ Object.keys(state[names.modelFormUploading] as object).length > 0;
504
554
  const defaultKeyOf = (sliceName: string) => capitalize(sliceName).replace(names.Model, names.defaultModel);
505
555
 
506
556
  const staleAtOfSlices = () => {
@@ -602,7 +652,7 @@ export const makeActions = (refName: string, slice: { [key: string]: SerializedS
602
652
  const defaultModel = currentState[defaultKeyOf(sliceName)] as Full;
603
653
  const modelInput = (cnst.input.purify as (form: any) => DefaultOf<Input> | null)(modelForm);
604
654
 
605
- if (!modelInput) return;
655
+ if (!modelInput || isUploadingIn(currentState)) return;
606
656
  this.set({ [names.modelLoading]: true });
607
657
  const model = await servedFetch<Full>(names.createModel)(modelInput, { onError });
608
658
  this.set({
@@ -627,7 +677,7 @@ export const makeActions = (refName: string, slice: { [key: string]: SerializedS
627
677
  const modelForm = currentState[names.modelForm] as Input & { id: string };
628
678
  const defaultModel = currentState[defaultKeyOf(sliceName)] as Full;
629
679
  const modelInput = (cnst.input.purify as (form: any) => DefaultOf<Input> | null)(modelForm);
630
- if (!modelInput) return;
680
+ if (!modelInput || isUploadingIn(currentState)) return;
631
681
  if (model?.id === modelForm.id) this.set({ [names.modelLoading]: modelForm.id });
632
682
  const updatedModel = await servedFetch<Full>(names.updateModel)(modelForm.id, modelInput, { onError });
633
683
  this.set({
@@ -730,7 +780,8 @@ export const makeActions = (refName: string, slice: { [key: string]: SerializedS
730
780
  const modelForm = currentState[names.modelForm] as Input;
731
781
  const modelSubmit = currentState[names.modelSubmit] as { disabled: boolean };
732
782
  const modelInput = (cnst.input.purify as (obj: any) => DefaultOf<Input> | null)(modelForm);
733
- this.set({ [names.modelSubmit]: { ...modelSubmit, disabled: !modelInput || disabled } });
783
+ const isDisabled = !modelInput || isUploadingIn(currentState) || disabled;
784
+ this.set({ [names.modelSubmit]: { ...modelSubmit, disabled: isDisabled } });
734
785
  },
735
786
  [names.submitModel]: async function (this: SetGet, option?: CreateOption<Full>) {
736
787
  const currentState = this.get() as { [key: string]: any };
@@ -855,6 +906,9 @@ export const makeActions = (refName: string, slice: { [key: string]: SerializedS
855
906
  });
856
907
  return model ?? null;
857
908
  },
909
+ [names.invalidateModel]: function (this: SetGet) {
910
+ this.set(staleAtOfSlices());
911
+ },
858
912
 
859
913
  [names.loadModelDraft]: async function (this: SetGet, draftScope?: string) {
860
914
  const currentState = this.get() as { [key: string]: any };
@@ -983,6 +1037,8 @@ export const makeActions = (refName: string, slice: { [key: string]: SerializedS
983
1037
  isQueryEqual(sort as unknown as object, sortOfModel as unknown as object)
984
1038
  )
985
1039
  return;
1040
+
1041
+ const requestedAt = new Date();
986
1042
  await loadList(
987
1043
  this,
988
1044
  () =>
@@ -999,7 +1055,7 @@ export const makeActions = (refName: string, slice: { [key: string]: SerializedS
999
1055
  [namesOfSlice.modelList]: modelList,
1000
1056
  [namesOfSlice.modelInsight]: modelInsight,
1001
1057
  [namesOfSlice.modelInitList]: modelList,
1002
- [namesOfSlice.modelInitAt]: new Date(),
1058
+ [namesOfSlice.modelInitAt]: requestedAt,
1003
1059
  ...lastPageFrom(modelInsight.count, limit),
1004
1060
  ...hasMoreFrom(modelDataList, fetchLimit),
1005
1061
  [namesOfSlice.limitOfModel]: limit,
@@ -1159,10 +1215,10 @@ export const makeActions = (refName: string, slice: { [key: string]: SerializedS
1159
1215
 
1160
1216
  [namesOfSlice.applyLiveModel]: function (this: SetGet, event: LiveEventPayload) {
1161
1217
  const currentState = this.get() as { [key: string]: any };
1162
- if (currentState[namesOfSlice.modelListLoading] as boolean) return;
1163
1218
  const modelList = currentState[namesOfSlice.modelList] as DataList<Light>;
1164
1219
  const staleAt = { [namesOfSlice.modelStaleAt]: new Date() };
1165
- if (event.op === "invalidate") {
1220
+
1221
+ if (event.op === "invalidate" || (currentState[namesOfSlice.modelListLoading] as boolean)) {
1166
1222
  this.set(staleAt);
1167
1223
  return;
1168
1224
  }
@@ -7,6 +7,7 @@ export const databaseStateNames = (refName: string) => {
7
7
  modelLoading: `${refName}Loading`,
8
8
  modelForm: `${refName}Form`,
9
9
  modelFormLoading: `${refName}FormLoading`,
10
+ modelFormUploading: `${refName}FormUploading`,
10
11
  modelSubmit: `${refName}Submit`,
11
12
  modelViewAt: `${refName}ViewAt`,
12
13
  modelModal: `${refName}Modal`,
@@ -0,0 +1,41 @@
1
+ import { capitalize } from "akanjs/common";
2
+ import { actionTagOf } from "./actionTag";
3
+ import { StoreRegistry } from "./storeRegistry";
4
+
5
+ interface HeldFile {
6
+ id: string;
7
+ }
8
+
9
+ export interface FormUpload {
10
+ upload: (fileList: FileList | File[]) => Promise<void>;
11
+ refresh: (files: HeldFile[]) => void;
12
+ }
13
+
14
+ export const formUploadOf = (setter: unknown): FormUpload | null => {
15
+ const tag = actionTagOf(setter);
16
+ const [formKey, field, ...rest] = tag?.state?.split(".") ?? [];
17
+ if (!formKey?.endsWith("Form") || !field || rest.length) return null;
18
+ const [Model, Field] = [capitalize(formKey.slice(0, -"Form".length)), capitalize(field)];
19
+ if (tag?.action !== `set${Field}On${Model}`) return null;
20
+ const actions = StoreRegistry.instance.do as unknown as { [key: string]: unknown };
21
+ const upload = actions[`upload${Field}On${Model}`];
22
+ const writeOn = actions[`writeOn${Model}`] as ((path: string, value: unknown) => unknown) | undefined;
23
+ if (typeof upload !== "function" || typeof writeOn !== "function") return null;
24
+
25
+ const refresh = (files: HeldFile[]) => {
26
+ const form = StoreRegistry.instance.get()[formKey] as { [key: string]: unknown } | undefined;
27
+ const held = form?.[field] as HeldFile | HeldFile[] | null | undefined;
28
+ const fresh = (file: HeldFile) => files.find((updated) => updated.id === file.id);
29
+ if (Array.isArray(held)) {
30
+ if (held.some((file) => fresh(file)))
31
+ void writeOn(
32
+ field,
33
+ held.map((file) => fresh(file) ?? file),
34
+ );
35
+ } else if (held) {
36
+ const updated = fresh(held);
37
+ if (updated) void writeOn(field, updated);
38
+ }
39
+ };
40
+ return { upload: upload as FormUpload["upload"], refresh };
41
+ };
package/store/index.ts CHANGED
@@ -6,6 +6,7 @@ export * from "./baseSt";
6
6
  export * from "./databaseStateNames";
7
7
  export * from "./draftStore";
8
8
  export * from "./formSetterNames";
9
+ export * from "./formUploadOf";
9
10
  export * from "./liveInsert";
10
11
  export * from "./rootStore";
11
12
  export * from "./sliceRole";
package/store/state.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { DataList } from "akanjs/base";
2
- import { ConstantRegistry, type DefaultOf } from "akanjs/constant";
2
+ import { ConstantRegistry, type DefaultOf, type ProtoLightFile } from "akanjs/constant";
3
3
  import type { ExtractSort, FilterInstance } from "akanjs/document";
4
4
  import type {
5
5
  SerializedSlice,
@@ -30,6 +30,11 @@ export interface DraftState {
30
30
  appliedAt: Date | null;
31
31
  }
32
32
 
33
+ /** Opaque tickets of the uploads in flight, per `File` field of the form; `{}` when nothing is uploading. */
34
+ export type FormUploading<_Default> = {
35
+ [K in keyof _Default as _Default[K] extends (ProtoLightFile | null) | ProtoLightFile[] ? K : never]?: string[];
36
+ };
37
+
33
38
  export type SliceStateKey =
34
39
  | "defaultModel"
35
40
  | "modelInsight"
@@ -64,6 +69,8 @@ type BaseState<RefName extends string, Full, _Default = DefaultOf<Full>> = {
64
69
  [K in `${RefName}Form`]: _Default;
65
70
  } & {
66
71
  [K in `${RefName}FormLoading`]: string | boolean;
72
+ } & {
73
+ [K in `${RefName}FormUploading`]: FormUploading<_Default>;
67
74
  } & {
68
75
  [K in `${RefName}Submit`]: Submit;
69
76
  } & {
@@ -183,6 +190,7 @@ export const createDatabaseState = (refName: string) => {
183
190
  [names.modelLoading]: true,
184
191
  [names.modelForm]: new cnst.input() as object,
185
192
  [names.modelFormLoading]: true,
193
+ [names.modelFormUploading]: {},
186
194
  [names.modelSubmit]: { disabled: true, loading: false, times: 0 },
187
195
  [names.modelViewAt]: new Date(0),
188
196
  [names.modelModal]: null,
@@ -45,6 +45,7 @@ export interface DraftMeta {
45
45
  refName: string;
46
46
  formKey: string;
47
47
  draftKey: string;
48
+ uploadingKey: string;
48
49
  }
49
50
 
50
51
  export interface StateDerivedMeta {
@@ -156,7 +157,12 @@ export const draftMetaOf = (refName: string): DraftMeta => {
156
157
  const cached = draftMetaByRefName.get(refName);
157
158
  if (cached) return cached;
158
159
  const names = databaseStateNames(refName);
159
- const meta: DraftMeta = { refName, formKey: names.modelForm, draftKey: names.modelDraft };
160
+ const meta: DraftMeta = {
161
+ refName,
162
+ formKey: names.modelForm,
163
+ draftKey: names.modelDraft,
164
+ uploadingKey: names.modelFormUploading,
165
+ };
160
166
  draftMetaByRefName.set(refName, meta);
161
167
  return meta;
162
168
  };
@@ -70,7 +70,7 @@ export class StoreInstance {
70
70
  if (typeof stateOrUpdater === "function") {
71
71
  this.#state = produce(this.#state, stateOrUpdater);
72
72
  } else {
73
- this.#state = { ...this.#state, ...stateOrUpdater };
73
+ this.#state = this.#dropReplacedUploads({ ...this.#state, ...stateOrUpdater }, stateOrUpdater);
74
74
  }
75
75
  this.#assertNoDerivedMutation(stateOrUpdater);
76
76
  this.#state = this.#materializeDerived(this.#state, prev);
@@ -509,6 +509,15 @@ export class StoreInstance {
509
509
  }
510
510
  }
511
511
 
512
+ #dropReplacedUploads(state: StoreStateRecord, patch: StoreStateRecord) {
513
+ for (const meta of Object.values(this.#derivedMeta.drafts)) {
514
+ if (!(meta.formKey in patch) || meta.uploadingKey in patch) continue;
515
+ const uploading = state[meta.uploadingKey] as object | undefined;
516
+ if (uploading && Object.keys(uploading).length) state = { ...state, [meta.uploadingKey]: {} };
517
+ }
518
+ return state;
519
+ }
520
+
512
521
  #syncDrafts(prev: StoreStateRecord, next: StoreStateRecord) {
513
522
  if (typeof window === "undefined") return;
514
523
  for (const meta of Object.values(this.#derivedMeta.drafts)) {
@@ -18,6 +18,8 @@ export interface CodeAgentSessionInfo {
18
18
  contextTokens: number | undefined;
19
19
  /** Absent when the model does no reasoning at all, which is not reasoning turned `off`. */
20
20
  effort: CodeAgentEffort | undefined;
21
+ /** Percent of the window that starts a compaction; absent leaves the engine's own, later threshold. */
22
+ autoCompactAt: number | undefined;
21
23
  /** Absent until the session has been asked something. */
22
24
  name: string | undefined;
23
25
  /** `await` keeps a question inside its turn; `suspend` ends the turn (`awaiting`) and the answer opens a new one. */
@@ -224,6 +226,11 @@ export type CodeAgentCommand = {
224
226
  type: "set_model";
225
227
  provider: string;
226
228
  modelId: string;
229
+ }
230
+ /** `percent` in steps of 10; absent, or 100, restores the default. */
231
+ | {
232
+ type: "set_auto_compact";
233
+ percent?: number;
227
234
  } | {
228
235
  type: "fork";
229
236
  entryId: string;
@@ -81,6 +81,8 @@ type BaseAction<RefName extends string, Input, Full extends {
81
81
  [K in `set${_CapitalizedRefName}`]: (...models: (Full | Light)[]) => void;
82
82
  } & {
83
83
  [K in `reset${_CapitalizedRefName}`]: (model?: Full) => void;
84
+ } & {
85
+ [K in `invalidate${_CapitalizedRefName}`]: () => void;
84
86
  };
85
87
  export type SliceAction<RefName extends string, Suffix extends string, Input, Light, QueryArgs extends any[], Filter extends FilterInstance, _CapitalizedRefName extends string = Capitalize<RefName>, _CapitalizedSuffix extends string = Capitalize<Suffix>, _Sort = ExtractSort<Filter>, _FetchInitFormWithFetchPolicy = FetchInitForm<Input, Filter> & FetchPolicy> = {
86
88
  [KDefaultOf in `init${_CapitalizedRefName}${_CapitalizedSuffix}`]: (...args: [...args: QueryArgs, initForm?: _FetchInitFormWithFetchPolicy]) => Promise<void>;
@@ -3,6 +3,7 @@ export declare const databaseStateNames: (refName: string) => {
3
3
  modelLoading: string;
4
4
  modelForm: string;
5
5
  modelFormLoading: string;
6
+ modelFormUploading: string;
6
7
  modelSubmit: string;
7
8
  modelViewAt: string;
8
9
  modelModal: string;
@@ -0,0 +1,9 @@
1
+ interface HeldFile {
2
+ id: string;
3
+ }
4
+ export interface FormUpload {
5
+ upload: (fileList: FileList | File[]) => Promise<void>;
6
+ refresh: (files: HeldFile[]) => void;
7
+ }
8
+ export declare const formUploadOf: (setter: unknown) => FormUpload | null;
9
+ export {};
@@ -6,6 +6,7 @@ export * from "./baseSt.d.ts";
6
6
  export * from "./databaseStateNames.d.ts";
7
7
  export * from "./draftStore.d.ts";
8
8
  export * from "./formSetterNames.d.ts";
9
+ export * from "./formUploadOf.d.ts";
9
10
  export * from "./liveInsert.d.ts";
10
11
  export * from "./rootStore.d.ts";
11
12
  export * from "./sliceRole.d.ts";
@@ -1,5 +1,5 @@
1
1
  import { DataList } from "akanjs/base";
2
- import { type DefaultOf } from "akanjs/constant";
2
+ import { type DefaultOf, type ProtoLightFile } from "akanjs/constant";
3
3
  import type { ExtractSort, FilterInstance } from "akanjs/document";
4
4
  import type { SerializedSlice, SlceCnstCapitalizedRefName, SlceCnstDefault, SlceCnstFull, SlceCnstInsight, SlceCnstLight, SlceCnstRefName, SlceDbFilter, SlceDbSort, SliceCls } from "akanjs/signal";
5
5
  import type { StoreSliceArgs, StoreSliceMap, StoreSliceSuffixCap, Submit } from "./types.d.ts";
@@ -18,6 +18,10 @@ export interface DraftState {
18
18
  /** Set while a draft is the thing in the form. Drives the "continuing, saved n minutes ago" chip. */
19
19
  appliedAt: Date | null;
20
20
  }
21
+ /** Opaque tickets of the uploads in flight, per `File` field of the form; `{}` when nothing is uploading. */
22
+ export type FormUploading<_Default> = {
23
+ [K in keyof _Default as _Default[K] extends (ProtoLightFile | null) | ProtoLightFile[] ? K : never]?: string[];
24
+ };
21
25
  export type SliceStateKey = "defaultModel" | "modelInsight" | "modelList" | "modelListLoading" | "modelInitList" | "modelInitAt" | "modelStaleAt" | "modelSelection" | "lastPageOfModel" | "pageOfModel" | "limitOfModel" | "hasMoreOfModel" | "isCumulativeOfModel" | "queryArgsOfModel" | "sortOfModel";
22
26
  type _SliceMap<S extends SliceCls> = StoreSliceMap<S>;
23
27
  type _StateRefName<S extends SliceCls> = SlceCnstRefName<S>;
@@ -36,6 +40,8 @@ type BaseState<RefName extends string, Full, _Default = DefaultOf<Full>> = {
36
40
  [K in `${RefName}Form`]: _Default;
37
41
  } & {
38
42
  [K in `${RefName}FormLoading`]: string | boolean;
43
+ } & {
44
+ [K in `${RefName}FormUploading`]: FormUploading<_Default>;
39
45
  } & {
40
46
  [K in `${RefName}Submit`]: Submit;
41
47
  } & {
@@ -28,6 +28,7 @@ export interface DraftMeta {
28
28
  refName: string;
29
29
  formKey: string;
30
30
  draftKey: string;
31
+ uploadingKey: string;
31
32
  }
32
33
  export interface StateDerivedMeta {
33
34
  drafts: Record<string, DraftMeta>;
package/ui/Load/Units.tsx CHANGED
@@ -1,6 +1,6 @@
1
1
  "use client";
2
2
  import { DataList } from "akanjs/base";
3
- import { cn, router } from "akanjs/client";
3
+ import { cn, isRscNavigationFromCache, router } from "akanjs/client";
4
4
  import { type DynamicRecord, isQueryEqual, lowerlize } from "akanjs/common";
5
5
  import type { BaseInsight } from "akanjs/constant";
6
6
  import { ConstantRegistry, labelOf, withSharedInstances } from "akanjs/constant";
@@ -142,9 +142,11 @@ function Render<RefName extends string, Light extends { id: string }>({
142
142
  }, [initSignature, queryArgsSignature]);
143
143
 
144
144
  useEffect(() => {
145
+
146
+ const seededFromReplay = !loaded && isRscNavigationFromCache();
145
147
  const modelStaleAt = storeGet<Date>()[namesOfSlice.modelStaleAt];
146
148
  const staleThreshold = Math.max(modelStaleAt.getTime(), staleTime === undefined ? 0 : Date.now() - staleTime);
147
- if (storeGet<Date>()[namesOfSlice.modelInitAt].getTime() >= staleThreshold) return;
149
+ if (!seededFromReplay && storeGet<Date>()[namesOfSlice.modelInitAt].getTime() >= staleThreshold) return;
148
150
  if (storeGet<boolean>()[namesOfSlice.modelListLoading]) return;
149
151
  void storeDo[namesOfSlice.refreshModel]({ invalidate: true });
150
152
  }, [initSignature]);
@@ -56,7 +56,7 @@ const EditModel = <Full,>({
56
56
  loadingWrapper,
57
57
  cancelEdit,
58
58
  }: OpenEditorProps<Full>) => {
59
- const storeUse = st.use as { [key: string]: () => unknown };
59
+ const storeUse = st.use as { [key: string]: (option?: { agent?: boolean }) => unknown };
60
60
  const storeDo = st.do as unknown as { [key: string]: (...args: any[]) => void };
61
61
  const { refName } = slice;
62
62
  const [modelName, ModelName] = useMemo(() => [lowerlize(refName), capitalize(refName)], []);
@@ -66,6 +66,7 @@ const EditModel = <Full,>({
66
66
  Model: ModelName,
67
67
  modelForm: `${modelName}Form`,
68
68
  modelFormLoading: `${modelName}FormLoading`,
69
+ modelFormUploading: `${modelName}FormUploading`,
69
70
  modelModal: `${modelName}Modal`,
70
71
  checkModelSubmitable: `check${ModelName}Submitable`,
71
72
  }),
@@ -73,6 +74,8 @@ const EditModel = <Full,>({
73
74
  );
74
75
  const modelModal = storeUse[names.modelModal]() as string | null;
75
76
  const modelForm = storeUse[names.modelForm]() as { id: string | null; [key: string]: any };
77
+
78
+ const modelFormUploading = storeUse[names.modelFormUploading]({ agent: false });
76
79
 
77
80
  st.tool(cancelEdit ? `cancelEditOf${ModelName}` : null)
78
81
  .desc(`Close the ${modelName} form without saving.`)
@@ -84,7 +87,7 @@ const EditModel = <Full,>({
84
87
 
85
88
  useEffect(() => {
86
89
  if (checkSubmit) checkSubmitable();
87
- }, [modelModal, modelForm]);
90
+ }, [modelModal, modelForm, modelFormUploading]);
88
91
 
89
92
  const LoadingWrapper = useMemo(() => {
90
93
  return loadingWrapper === false
@@ -167,6 +170,7 @@ export default function EditModal<Full extends { id: string }>({
167
170
  modelFormLoading: `${modelName}FormLoading`,
168
171
  modelModal: `${modelName}Modal`,
169
172
  modelSubmit: `${modelName}Submit`,
173
+ modelFormUploading: `${modelName}FormUploading`,
170
174
  submitModel: `submit${ModelName}`,
171
175
  resetModel: `reset${ModelName}`,
172
176
  setModelModal: `set${ModelName}Modal`,
@@ -301,6 +305,9 @@ export default function EditModal<Full extends { id: string }>({
301
305
  ? () => renderSubmit(storeUse[names.modelForm]() as Full)
302
306
  : () => {
303
307
  const modelSubmit = storeUse[names.modelSubmit]() as Submit;
308
+ const isUploading =
309
+ Object.keys(storeUse[names.modelFormUploading]({ agent: false }) as object).length > 0;
310
+ const isBlocked = modelSubmit.disabled || isUploading || !!disabled;
304
311
  const handleSubmit = async ({ onError }: { onError?: (e: string) => void } = {}) => {
305
312
  await storeDo[names.submitModel]({
306
313
  ...submitOption,
@@ -321,8 +328,7 @@ export default function EditModal<Full extends { id: string }>({
321
328
  };
322
329
  const submitModel = st
323
330
  .tool(names.submitModel, {
324
- guard: () =>
325
- modelSubmit.disabled || disabled ? `The ${names.model} form is not ready to submit.` : true,
331
+ guard: () => (isBlocked ? `The ${names.model} form is not ready to submit.` : true),
326
332
  })
327
333
  .desc(`Save the ${names.model} the open form holds.`)
328
334
  .exec(() => handleSubmit());
@@ -330,7 +336,7 @@ export default function EditModal<Full extends { id: string }>({
330
336
  <Button
331
337
  {...agentAttrs(submitModel)}
332
338
  className={cn("mt-4 w-full gap-2", submitClassName)}
333
- disabled={modelSubmit.disabled || !!disabled}
339
+ disabled={isBlocked}
334
340
  onClick={async (e, { onError }) => {
335
341
  await handleSubmit({ onError });
336
342
  }}
@@ -36,6 +36,7 @@ interface ActionProps {
36
36
  label: ReactNode;
37
37
  onAct: () => void;
38
38
  closeView: () => void;
39
+ isBlocked?: boolean;
39
40
  }
40
41
 
41
42
  const EditAction = ({ modelName, label, onAct, closeView }: ActionProps) => {
@@ -56,16 +57,19 @@ const EditAction = ({ modelName, label, onAct, closeView }: ActionProps) => {
56
57
  );
57
58
  };
58
59
 
59
- const SaveAction = ({ modelName, label, onAct, closeView }: ActionProps) => {
60
+ const SaveAction = ({ modelName, label, onAct, closeView, isBlocked = false }: ActionProps) => {
60
61
  useCloseViewTool(modelName, closeView);
61
62
  const submitModel = st
62
- .tool(`submit${capitalize(modelName)}`)
63
+ .tool(`submit${capitalize(modelName)}`, {
64
+ guard: () => (isBlocked ? `The ${modelName} form is not ready to submit.` : true),
65
+ })
63
66
  .desc(`Save the ${modelName} the open form holds.`)
64
67
  .exec(onAct);
65
68
  return (
66
69
  <button
67
70
  type="button"
68
71
  className={buttonRecipe({ variant: "primary" }, "w-full")}
72
+ disabled={isBlocked}
69
73
  onClick={submitModel}
70
74
  {...agentAttrs(submitModel)}
71
75
  >
@@ -100,7 +104,7 @@ export default function ViewEditModal({
100
104
  saveLabel,
101
105
  }: ViewEditModalProps) {
102
106
  const { l } = usePage();
103
- const storeUse = st.use as unknown as { [key: string]: () => unknown };
107
+ const storeUse = st.use as unknown as { [key: string]: (option?: { agent?: boolean }) => unknown };
104
108
  const storeDo = st.do as unknown as { [key: string]: (...args: any[]) => void };
105
109
  const storeSel = st.sel as unknown as <Ret, Val>(selector: (state: { [key: string]: Val }) => Ret) => Ret;
106
110
  const { refName, sliceName } = slice;
@@ -122,6 +126,7 @@ export default function ViewEditModal({
122
126
  const modelLoading = storeUse[names.modelLoading]() as string | boolean;
123
127
  const modelFormLoading = storeUse[names.modelFormLoading]() as string | boolean;
124
128
  const modelFormId = storeSel<string, { id: string }>((state) => state[names.modelForm].id);
129
+ const isUploading = Object.keys(storeUse[`${modelName}FormUploading`]({ agent: false }) as object).length > 0;
125
130
  const canUpdate = !!servedEndpointOf(fetch, `update${ModelName}`);
126
131
  const canRemove = !!servedEndpointOf(fetch, `remove${ModelName}`);
127
132
  const isModalOpen = modelModal === "view" || (modelModal === "edit" && (!!modelFormLoading || !!modelFormId));
@@ -188,6 +193,7 @@ export default function ViewEditModal({
188
193
  modelName={modelName}
189
194
  label={saveLabel ?? l("base.save")}
190
195
  closeView={closeView}
196
+ isBlocked={isUploading}
191
197
  onAct={() => {
192
198
  storeDo[names.submitModel]({ sliceName, modal: "view" });
193
199
  }}