@kabmo-labs/kabmo 0.26.0 → 0.27.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.
Files changed (71) hide show
  1. package/dist/client/index.html +1 -1
  2. package/dist/client/index.js +164 -164
  3. package/dist/client/static/js/index-32rpkj6b.css +1 -0
  4. package/dist/client/static/js/{index-95b3n20k.js → index-e3qh2yps.js} +668 -668
  5. package/package.json +1 -1
  6. package/src/client/components/common/Toast.test.tsx +28 -2
  7. package/src/client/components/common/Toast.tsx +21 -9
  8. package/src/client/components/layout/desktop-layout/LeftColumn.tsx +2 -1
  9. package/src/client/components/layout/session-sidebar/CategoryItem.tsx +2 -1
  10. package/src/client/components/layout/session-sidebar/SessionList.tsx +2 -1
  11. package/src/client/components/layout/session-sidebar/about-modal/UpdateSection.tsx +3 -2
  12. package/src/client/components/layout/session-sidebar/about-modal/index.tsx +2 -1
  13. package/src/client/components/layout/session-sidebar/modern/RevealRow.tsx +56 -0
  14. package/src/client/components/layout/session-sidebar/modern/WorkspaceSection.tsx +10 -28
  15. package/src/client/components/layout/session-sidebar/modern/reveal-row.test.tsx +104 -0
  16. package/src/client/components/layout/session-sidebar/scheduler-modal/index.tsx +2 -1
  17. package/src/client/components/layout/session-sidebar/variant-props.ts +2 -1
  18. package/src/client/components/mobile/SessionSidebar.tsx +2 -1
  19. package/src/client/components/mobile/mobile-session-sidebar/ClassicDrawer.tsx +2 -1
  20. package/src/client/components/mobile/mobile-session-sidebar/Item.tsx +2 -1
  21. package/src/client/components/mobile/mobile-session-sidebar/List.tsx +2 -1
  22. package/src/client/components/settings/Modal.tsx +1 -1
  23. package/src/client/components/settings/categories/project-settings/WorktreeSettings.tsx +2 -1
  24. package/src/client/components/settings/categories/usage-settings/LimitsSection.tsx +39 -19
  25. package/src/client/components/settings/categories/usage-settings/ProviderDetail.tsx +1 -0
  26. package/src/client/components/settings/categories/usage-settings/limit-groups.test.ts +94 -0
  27. package/src/client/components/settings/categories/usage-settings/limit-groups.ts +118 -0
  28. package/src/client/components/settings/categories/usage-settings/limits-section.test.tsx +118 -0
  29. package/src/client/components/workspace/chat-timeline/EmptyWorkspacePrompt.tsx +58 -54
  30. package/src/client/components/workspace/chat-timeline/PendingChatView.tsx +11 -1
  31. package/src/client/components/workspace/chat-timeline/PendingTranscript.tsx +130 -0
  32. package/src/client/components/workspace/chat-timeline/fork-preview.test.tsx +141 -0
  33. package/src/client/components/workspace/chat-timeline/index.tsx +6 -1
  34. package/src/client/components/workspace/chat-timeline/target-picker/DraftTargetRow.tsx +2 -1
  35. package/src/client/components/workspace/chat-timeline/target-picker/WorktreePicker.tsx +5 -4
  36. package/src/client/components/workspace/git-panel/index.tsx +2 -2
  37. package/src/client/components/workspace/terminal-panel/RealtimeTerminalView.tsx +8 -5
  38. package/src/client/components/workspace/terminal-panel/index.tsx +3 -0
  39. package/src/client/hooks/chat/omp/session-list.tsx +5 -0
  40. package/src/client/hooks/chat/omp/sidebar-reload.test.ts +85 -0
  41. package/src/client/hooks/chat/omp/sidebar-reload.ts +30 -0
  42. package/src/client/hooks/chat/timeline/fork-preview.test.ts +148 -0
  43. package/src/client/hooks/chat/timeline/fork-preview.ts +104 -0
  44. package/src/client/hooks/chat/timeline/fork-send.test.ts +139 -0
  45. package/src/client/hooks/chat/timeline/pending-branch.ts +9 -0
  46. package/src/client/hooks/chat/timeline/pending-dispatch.ts +49 -0
  47. package/src/client/hooks/chat/timeline/stop-with-queue.ts +1 -1
  48. package/src/client/hooks/chat/waiting/cancel.ts +2 -1
  49. package/src/client/hooks/chat/waiting/dispatch.ts +5 -4
  50. package/src/client/hooks/chat/waiting/held.ts +2 -1
  51. package/src/client/hooks/settings/providers/actions.ts +3 -2
  52. package/src/client/hooks/settings/providers/messages.ts +9 -7
  53. package/src/client/hooks/settings/providers/model-actions.ts +2 -1
  54. package/src/client/hooks/ui/editor-error-toast.ts +2 -1
  55. package/src/client/hooks/workspace/batch-archive.test.ts +2 -2
  56. package/src/client/hooks/workspace/batch-archive.ts +4 -2
  57. package/src/client/hooks/workspace/git-action-outcome.ts +4 -3
  58. package/src/client/hooks/workspace/navbar-session-actions.ts +2 -1
  59. package/src/client/hooks/workspace/session-actions.test.ts +2 -1
  60. package/src/client/hooks/workspace/session-actions.ts +2 -1
  61. package/src/client/hooks/workspace/terminal/connection.test.ts +63 -0
  62. package/src/client/hooks/workspace/terminal/connection.ts +47 -0
  63. package/src/client/hooks/workspace/terminal/index.ts +35 -4
  64. package/src/client/hooks/workspace/workspace-folder-actions.ts +2 -1
  65. package/src/server/lib/usage/report.server.ts +57 -0
  66. package/src/shared/lib/chat/timeline/fork-preview.test.ts +62 -0
  67. package/src/shared/lib/chat/timeline/fork-preview.ts +36 -0
  68. package/src/shared/lib/ui/toast-duration.test.ts +25 -1
  69. package/src/shared/lib/ui/toast-duration.ts +22 -4
  70. package/src/shared/lib/workspace/session-state/store.ts +4 -0
  71. package/dist/client/static/js/index-p2yw9ywf.css +0 -1
@@ -0,0 +1,148 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The fork preview's TRANSPORT half: which source it reads, and what happens
8
+ * when "Fork from" moves.
9
+ *
10
+ * The slice itself is asserted in `shared/lib/chat/timeline/fork-preview.test.ts`;
11
+ * this pins the two behaviours the picker depends on — a source switch refetches
12
+ * (the old rows must not stand in for the new source) and a late answer for a
13
+ * source that is no longer selected is dropped, not painted.
14
+ */
15
+
16
+ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
17
+ import { Window } from 'happy-dom';
18
+ import { h, render } from 'preact';
19
+ import { act } from 'preact/test-utils';
20
+
21
+ import { installDomGlobals, restoreDomGlobals } from '@/test-support/pristine-globals';
22
+ import { useForkPreview, type ForkPreview } from '@/client/hooks/chat/timeline/fork-preview';
23
+ import type { ChatMessageData } from '@/shared/types';
24
+
25
+ let container: HTMLElement;
26
+ let requested: string[];
27
+ /** The runner's own fetch: a stub left installed poisons every later suite. */
28
+ const originalFetch = Bun.fetch;
29
+ interface DeferredResponse {
30
+ promise: Promise<Response>;
31
+ resolve: (value: Response) => void;
32
+ }
33
+ const gates = new Map<string, DeferredResponse>();
34
+
35
+ beforeAll(() => installDomGlobals(new Window({ url: 'http://localhost' })));
36
+ afterAll(() => restoreDomGlobals());
37
+
38
+ beforeEach(() => {
39
+ requested = [];
40
+ gates.clear();
41
+ globalThis.fetch = ((input: RequestInfo | URL) => {
42
+ const url = String(input);
43
+ requested.push(url);
44
+ const gate = Promise.withResolvers<Response>();
45
+ gates.set(url, gate);
46
+ return gate.promise;
47
+ }) as typeof fetch;
48
+ container = document.createElement('div');
49
+ document.body.appendChild(container);
50
+ });
51
+
52
+ afterEach(() => {
53
+ globalThis.fetch = originalFetch;
54
+ render(null, container);
55
+ container.remove();
56
+ });
57
+
58
+ const sessionResponse = (id: string, messages: ChatMessageData[]) =>
59
+ Response.json({ session: { id, messages } });
60
+
61
+ /** Mounts the hook and records its latest value. */
62
+ function mount(source: string | null, anchor: string | null): { current: ForkPreview | null } {
63
+ const state: { current: ForkPreview | null } = { current: null };
64
+ function Probe({ sourceId, anchorId }: { sourceId: string | null; anchorId: string | null }) {
65
+ state.current = useForkPreview(sourceId, anchorId);
66
+ return null;
67
+ }
68
+ act(() => render(h(Probe, { sourceId: source, anchorId: anchor }), container));
69
+ return state;
70
+ }
71
+
72
+ async function settle(): Promise<void> {
73
+ // The fetch chain is microtasks only: drain them deterministically rather
74
+ // than guessing a wall-clock delay.
75
+ await act(async () => {
76
+ for (let tick = 0; tick < 8; tick += 1) await Promise.resolve();
77
+ });
78
+ }
79
+
80
+ describe('useForkPreview', () => {
81
+ test('reads the whole source transcript and slices it at the anchor', async () => {
82
+ const state = mount('sess-a', 'a1');
83
+ expect(requested).toEqual(['/api/chat/sess-a?limit=all']);
84
+
85
+ const gate = gates.get('/api/chat/sess-a?limit=all')!;
86
+ gate.resolve(sessionResponse('sess-a', [
87
+ { id: 'u1', role: 'user', content: 'one' },
88
+ { id: 'a1', role: 'ai', content: 'two' },
89
+ { id: 'u2', role: 'user', content: 'three' },
90
+ ]));
91
+ await settle();
92
+
93
+ expect(state.current?.loading).toBe(false);
94
+ expect(state.current?.messages.map((m) => m.id)).toEqual(['u1', 'a1']);
95
+ });
96
+
97
+ test('a new "Fork from" refetches and never shows the previous source rows', async () => {
98
+ const state = mount('sess-a', null);
99
+ gates.get('/api/chat/sess-a?limit=all')!.resolve(sessionResponse('sess-a', [
100
+ { id: 'a1', role: 'user', content: 'from A' },
101
+ ]));
102
+ await settle();
103
+ expect(state.current?.messages.map((m) => m.id)).toEqual(['a1']);
104
+
105
+ act(() => {
106
+ render(h(function Next() {
107
+ state.current = useForkPreview('sess-b', null);
108
+ return null;
109
+ }, {}), container);
110
+ });
111
+ // The picker moved: A's transcript is gone from the surface immediately.
112
+ expect(state.current?.messages).toEqual([]);
113
+ expect(requested.at(-1)).toBe('/api/chat/sess-b?limit=all');
114
+
115
+ gates.get('/api/chat/sess-b?limit=all')!.resolve(sessionResponse('sess-b', [
116
+ { id: 'b1', role: 'user', content: 'from B' },
117
+ ]));
118
+ await settle();
119
+ expect(state.current?.messages.map((m) => m.id)).toEqual(['b1']);
120
+ });
121
+
122
+ test('a late answer for an abandoned source is dropped', async () => {
123
+ const state = mount('sess-a', null);
124
+ act(() => {
125
+ render(h(function Next() {
126
+ state.current = useForkPreview('sess-b', null);
127
+ return null;
128
+ }, {}), container);
129
+ });
130
+ gates.get('/api/chat/sess-b?limit=all')!.resolve(sessionResponse('sess-b', [
131
+ { id: 'b1', role: 'user', content: 'from B' },
132
+ ]));
133
+ await settle();
134
+ gates.get('/api/chat/sess-a?limit=all')!.resolve(sessionResponse('sess-a', [
135
+ { id: 'a1', role: 'user', content: 'from A' },
136
+ ]));
137
+ await settle();
138
+ expect(state.current?.messages.map((m) => m.id)).toEqual(['b1']);
139
+ });
140
+
141
+ test('a failed read is reported, not replaced with an empty transcript', async () => {
142
+ const state = mount('sess-a', null);
143
+ gates.get('/api/chat/sess-a?limit=all')!.resolve(Response.json({ error: 'not found' }, { status: 404 }));
144
+ await settle();
145
+ expect(state.current?.error).toBe('not found');
146
+ expect(state.current?.messages).toEqual([]);
147
+ });
148
+ });
@@ -0,0 +1,104 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The SOURCE transcript of the fork being composed.
8
+ *
9
+ * A fork chat is empty until the first send, so the operator had no sight of
10
+ * the history the first turn continues — and after switching "Fork from" the
11
+ * old preview stayed. This reads the source session and slices it the way the
12
+ * server will cut the branch (`forkPreviewMessages`), refetching when the
13
+ * source changes.
14
+ *
15
+ * `limit=all` on purpose: the default 120-row window would cut the preview at
16
+ * a different row than the branch file, and a fork of a long session usually
17
+ * anchors further back than that window covers.
18
+ */
19
+
20
+ import { useEffect, useMemo, useState } from 'preact/hooks';
21
+ import type { ChatMessageData } from '@/shared/types';
22
+ import { forkPreviewMessages } from '@/shared/lib/chat/timeline/fork-preview';
23
+
24
+ export interface ForkPreview {
25
+ /** The rows the fork will carry, in source order; empty while loading. */
26
+ messages: ChatMessageData[];
27
+ loading: boolean;
28
+ /** Why the source transcript could not be read, or null. */
29
+ error: string | null;
30
+ }
31
+
32
+ interface LoadedSource {
33
+ id: string;
34
+ messages: ChatMessageData[];
35
+ }
36
+
37
+ const EMPTY: ChatMessageData[] = [];
38
+
39
+ export function useForkPreview(
40
+ sourceSessionId: string | null,
41
+ anchorEntryId: string | null,
42
+ ): ForkPreview {
43
+ const [loaded, setLoaded] = useState<LoadedSource | null>(null);
44
+ const [loading, setLoading] = useState(false);
45
+ const [error, setError] = useState<{ id: string; message: string } | null>(null);
46
+
47
+ useEffect(() => {
48
+ if (!sourceSessionId) {
49
+ setLoaded(null);
50
+ setLoading(false);
51
+ setError(null);
52
+ return;
53
+ }
54
+ const controller = new AbortController();
55
+ let live = true;
56
+ setLoading(true);
57
+ setError(null);
58
+ fetch(`/api/chat/${encodeURIComponent(sourceSessionId)}?limit=all`, {
59
+ signal: controller.signal,
60
+ })
61
+ .then(async (response) => {
62
+ const body = (await response.json().catch(() => null)) as
63
+ | { session?: { messages?: ChatMessageData[] }; error?: string }
64
+ | null;
65
+ if (!live) return;
66
+ if (!response.ok) {
67
+ setError({ id: sourceSessionId, message: body?.error ?? `HTTP ${response.status}` });
68
+ setLoaded(null);
69
+ return;
70
+ }
71
+ setLoaded({ id: sourceSessionId, messages: body?.session?.messages ?? [] });
72
+ })
73
+ .catch((err: unknown) => {
74
+ if (!live || controller.signal.aborted) return;
75
+ setError({
76
+ id: sourceSessionId,
77
+ message: err instanceof Error ? err.message : 'Could not load the source transcript',
78
+ });
79
+ setLoaded(null);
80
+ })
81
+ .finally(() => {
82
+ if (live) setLoading(false);
83
+ });
84
+ return () => {
85
+ live = false;
86
+ controller.abort();
87
+ };
88
+ }, [sourceSessionId]);
89
+
90
+ // Rows from a previous source are not this fork's history: they disappear
91
+ // the moment the picker moves, rather than standing in for the new source.
92
+ const messages = useMemo(
93
+ () => (loaded && loaded.id === sourceSessionId
94
+ ? forkPreviewMessages(loaded.messages, anchorEntryId)
95
+ : EMPTY),
96
+ [loaded, sourceSessionId, anchorEntryId],
97
+ );
98
+
99
+ return {
100
+ messages,
101
+ loading,
102
+ error: error && error.id === sourceSessionId ? error.message : null,
103
+ };
104
+ }
@@ -0,0 +1,139 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The FORK send: the branch inherits the source's history, so the chat that
8
+ * continues it must render that history — not just the new turn.
9
+ *
10
+ * The fork's file on disk already holds the copied rows, but the timeline skips
11
+ * a committed read while a run this page dispatched owns the rows, and a run
12
+ * that ends cleanly never re-reads the transcript. Measured symptom: the first
13
+ * forked turn appeared in an empty-looking chat and the conversation it
14
+ * continued only came back after a reload.
15
+ */
16
+
17
+ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
18
+ import {
19
+ act,
20
+ installDomGlobals,
21
+ makeSendHarness,
22
+ originalFetch,
23
+ requests,
24
+ restoreDomGlobals,
25
+ } from '@/client/hooks/chat/timeline/send.test-util';
26
+ import {
27
+ listPendingSessions,
28
+ releasePendingSession,
29
+ startPendingSession,
30
+ } from '@/client/hooks/chat/omp/pending-sessions';
31
+
32
+ beforeAll(() => installDomGlobals());
33
+ afterAll(() => restoreDomGlobals());
34
+ afterEach(() => {
35
+ globalThis.fetch = originalFetch;
36
+ for (const entry of listPendingSessions()) releasePendingSession(entry.id);
37
+ });
38
+ beforeEach(() => {
39
+ requests.length = 0;
40
+ });
41
+
42
+ const SOURCE_MESSAGES = [
43
+ { id: 'u1', role: 'user', content: 'first question' },
44
+ { id: 'a1', role: 'ai', content: 'first answer' },
45
+ { id: 'u2', role: 'user', content: 'second question' },
46
+ { id: 'a2', role: 'ai', content: 'second answer' },
47
+ ];
48
+
49
+ interface ForkStub {
50
+ /** Resolves the source transcript read, so a case can order the race. */
51
+ resolveSource: (body: unknown) => void;
52
+ }
53
+
54
+ /** Answers the fork POST and holds the source read open until a case asks. */
55
+ function stubForkFetch(): ForkStub {
56
+ const source = Promise.withResolvers<Response>();
57
+ globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
58
+ const url = String(input);
59
+ requests.push({ url, method: init?.method ?? 'GET', body: init?.body === undefined ? null : String(init.body) });
60
+ if (url.startsWith('/api/sessions/src-1/fork')) {
61
+ return Response.json({ sessionId: 'fork-9', sourceSessionId: 'src-1', originKind: 'fork' }, { status: 201 });
62
+ }
63
+ if (url.startsWith('/api/chat/src-1?limit=all')) return source.promise;
64
+ return new Response('{}', { status: 200, headers: { 'content-type': 'application/json' } });
65
+ }) as typeof fetch;
66
+ return { resolveSource: (body) => source.resolve(Response.json(body)) };
67
+ }
68
+
69
+ /** A pending fork chat bound to `src-1`, anchored at `anchor` (null = tip). */
70
+ function pendingFork(anchor: string | null): string {
71
+ return startPendingSession(4, {
72
+ forkSourceSessionId: 'src-1',
73
+ ...(anchor ? { forkAnchorEntryId: anchor } : {}),
74
+ });
75
+ }
76
+
77
+ async function flush(): Promise<void> {
78
+ await act(async () => {
79
+ for (let tick = 0; tick < 8; tick += 1) await Promise.resolve();
80
+ });
81
+ }
82
+
83
+ describe('fork send inherits the source history', () => {
84
+ test('the branch transcript lands above the optimistic turn', async () => {
85
+ const stub = stubForkFetch();
86
+ const h1 = makeSendHarness({
87
+ isOmpSession: false,
88
+ sessionId: pendingFork('a2'),
89
+ folders: [{ id: 4, name: 'demo', project_path: '/tmp/demo' }],
90
+ selectedFolderId: 4,
91
+ });
92
+ await act(async () => {
93
+ await h1.sends.executeSend('continue it', []);
94
+ });
95
+ expect(h1.adoptedSessionIdRef.current).toBe('fork-9');
96
+
97
+ stub.resolveSource({ session: { messages: SOURCE_MESSAGES } });
98
+ await flush();
99
+
100
+ expect(h1.state.messages.map((m) => m.id)).toEqual([
101
+ 'u1', 'a1', 'u2', 'a2', expect.stringMatching(/^msg-\d+-user$/), expect.stringMatching(/^msg-\d+-ai$/),
102
+ ]);
103
+ });
104
+
105
+ test('the anchor cuts the prefix the same way the branch cuts the file', async () => {
106
+ const stub = stubForkFetch();
107
+ const h1 = makeSendHarness({
108
+ isOmpSession: false,
109
+ sessionId: pendingFork('u2'),
110
+ folders: [{ id: 4, name: 'demo', project_path: '/tmp/demo' }],
111
+ selectedFolderId: 4,
112
+ });
113
+ await act(async () => {
114
+ await h1.sends.executeSend('continue it', []);
115
+ });
116
+ stub.resolveSource({ session: { messages: SOURCE_MESSAGES } });
117
+ await flush();
118
+ // A user anchor branches BEFORE that turn: 'u2' is the message being replaced.
119
+ expect(h1.state.messages.slice(0, 2).map((m) => m.id)).toEqual(['u1', 'a1']);
120
+ });
121
+
122
+ test('a read that lands after the chat moved on is dropped', async () => {
123
+ const stub = stubForkFetch();
124
+ const h1 = makeSendHarness({
125
+ isOmpSession: false,
126
+ sessionId: pendingFork(null),
127
+ folders: [{ id: 4, name: 'demo', project_path: '/tmp/demo' }],
128
+ selectedFolderId: 4,
129
+ });
130
+ await act(async () => {
131
+ await h1.sends.executeSend('continue it', []);
132
+ });
133
+ h1.adoptedSessionIdRef.current = 'another-chat';
134
+ stub.resolveSource({ session: { messages: SOURCE_MESSAGES } });
135
+ await flush();
136
+ expect(h1.state.messages).toHaveLength(2);
137
+ expect(h1.state.messages[0]?.id).toMatch(/^msg-\d+-user$/);
138
+ });
139
+ });
@@ -42,6 +42,10 @@ export interface PendingBranchComposerProps {
42
42
  export interface PendingBranch {
43
43
  /** The linked session id, under either meaning. */
44
44
  parentSessionId: string | null;
45
+ /** The session this chat forks from, or null for a child / top-level chat. */
46
+ forkSourceSessionId: string | null;
47
+ /** The source row the fork cuts at; absent means that source's tip. */
48
+ forkAnchorEntryId: string | null;
45
49
  /** The model the linked session runs on, so the composer starts on it. */
46
50
  parentModel: { provider: string; modelId: string } | null;
47
51
  viewProps: PendingBranchViewProps;
@@ -76,6 +80,9 @@ export function usePendingBranch(args: {
76
80
  const entry = entries.find((candidate) => candidate.id === sessionId);
77
81
  const forkSourceId = entry?.forkSourceSessionId ?? urlForkFrom ?? null;
78
82
  const isFork = Boolean(forkSourceId);
83
+ const forkAnchorEntryId = entry?.forkSourceSessionId
84
+ ? (entry.forkAnchorEntryId ?? null)
85
+ : (urlForkFrom ? urlForkAt : null);
79
86
  const parentSessionId = forkSourceId ?? entry?.parentSessionId ?? urlParentId ?? null;
80
87
  const sessionOf = useCallback(
81
88
  (id: string) => folders
@@ -193,6 +200,8 @@ export function usePendingBranch(args: {
193
200
 
194
201
  return {
195
202
  parentSessionId,
203
+ forkSourceSessionId: forkSourceId,
204
+ forkAnchorEntryId,
196
205
  parentModel: linked?.runModel ?? null,
197
206
  viewProps: {
198
207
  parentSessionId,
@@ -23,6 +23,7 @@ import { adoptPendingSession, pendingEntryFor } from '@/client/hooks/chat/omp/pe
23
23
  import { recordSpawnHarness } from '@/client/hooks/chat/timeline/spawn-harness';
24
24
  import { childSpawnBody } from '@/client/hooks/chat/timeline/child-spawn';
25
25
  import { forkRequestBody } from '@/client/hooks/chat/timeline/fork-request';
26
+ import { forkPreviewMessages } from '@/shared/lib/chat/timeline/fork-preview';
26
27
  import { collectImages } from '@/client/hooks/chat/timeline/send-helpers';
27
28
 
28
29
  type PendingDispatchDeps = Pick<
@@ -85,6 +86,48 @@ function persistUserTurn(sessionId: string, newUserMsg: ChatMessageData): void {
85
86
  }).catch((err) => console.error('Error persisting spawned user turn:', err));
86
87
  }
87
88
 
89
+ /**
90
+ * Put the branch's inherited history above the optimistic turn.
91
+ *
92
+ * The fork's file already holds these rows, but the timeline cannot show them
93
+ * on its own: while a run THIS PAGE dispatched owns the rows, a committed read
94
+ * is a lagging snapshot and is skipped (`timelineOwnedByLiveRun`), and a run
95
+ * that ends cleanly does not re-read the transcript (only one that lost frames
96
+ * does). So the first fork turn rendered in an apparently empty chat, and the
97
+ * conversation it continues appeared only after a reload.
98
+ *
99
+ * The slice is the preview's own (`forkPreviewMessages`, the server's cut), so
100
+ * what lands here is exactly the prefix the branch file starts with. Read-only
101
+ * and non-blocking: the run is already in flight, and a failed read costs the
102
+ * prefix — never the turn.
103
+ */
104
+ function prependInheritedHistory(
105
+ deps: PendingDispatchDeps,
106
+ adoptedId: string,
107
+ sourceSessionId: string,
108
+ anchorEntryId: string | null,
109
+ ): void {
110
+ fetch(`/api/chat/${encodeURIComponent(sourceSessionId)}?limit=all`)
111
+ .then(async (response) => {
112
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
113
+ const body = (await response.json()) as { session?: { messages?: ChatMessageData[] } } | null;
114
+ const inherited = forkPreviewMessages(body?.session?.messages ?? [], anchorEntryId);
115
+ // The operator may have switched chats while this read was in flight: the
116
+ // rows belong to the fork adopted above, never to whatever is on screen.
117
+ if (inherited.length === 0 || deps.adoptedSessionIdRef.current !== adoptedId) return;
118
+ deps.setLocalMessages((prev) =>
119
+ // A committed read may already carry the prefix (e.g. a reload raced
120
+ // this one); prepending it again would render the history twice.
121
+ prev.some((row) => row.id === inherited[0]!.id) ? prev : [...inherited, ...prev],
122
+ );
123
+ })
124
+ .catch((error: unknown) => {
125
+ deps.reportActionError(
126
+ `Could not show the forked history: ${error instanceof Error ? error.message : String(error)}`,
127
+ );
128
+ });
129
+ }
130
+
88
131
  export async function dispatchPendingChat(
89
132
  deps: PendingDispatchDeps,
90
133
  input: PendingDispatchInput,
@@ -147,6 +190,12 @@ export async function dispatchPendingChat(
147
190
  next.delete('parentSessionId');
148
191
  return next;
149
192
  }, { replace: true });
193
+ prependInheritedHistory(
194
+ deps,
195
+ body.sessionId,
196
+ entry.forkSourceSessionId,
197
+ entry.forkAnchorEntryId ?? null,
198
+ );
150
199
  return { ok: true, busy: false };
151
200
  }
152
201
 
@@ -26,7 +26,7 @@ export function useStopWithQueuedPrompts<T>(
26
26
  if (heldCount === 0) return;
27
27
  pushToast(
28
28
  `Stopped. ${heldCount} message${heldCount > 1 ? 's' : ''} still queued — nothing was sent.`,
29
- 'success',
29
+ 'warning',
30
30
  {
31
31
  action: {
32
32
  label: 'Send now',
@@ -15,10 +15,11 @@
15
15
  import { useCallback } from 'preact/hooks';
16
16
  import { cancelWaitingPromptRequest } from '@/client/hooks/chat/waiting/store';
17
17
  import { releasePendingSessionByWait } from '@/client/hooks/chat/omp/pending-waiting';
18
+ import type { ToastTone } from '@/shared/lib/ui/toast-duration';
18
19
 
19
20
  export type CancelWait = (waitId: string) => void;
20
21
 
21
- export function useCancelWait(onNotice?: (message: string, type?: 'success' | 'error') => void): CancelWait {
22
+ export function useCancelWait(onNotice?: (message: string, type?: ToastTone) => void): CancelWait {
22
23
  return useCallback((waitId: string) => {
23
24
  void cancelWaitingPromptRequest(waitId).then((result) => {
24
25
  if (!result.ok) {
@@ -25,10 +25,11 @@ import {
25
25
  } from '@/client/hooks/chat/omp/pending-sessions';
26
26
  import { clearPendingSessionWaiting, pendingSessionWait } from '@/client/hooks/chat/omp/pending-waiting';
27
27
  import { useSearchParams } from '@/client/lib/router/search-params';
28
+ import type { ToastTone } from '@/shared/lib/ui/toast-duration';
28
29
 
29
30
  export interface WaitingDispatchOptions {
30
31
  /** Surfaces an outcome the user must know about (a failed or cancelled wait). */
31
- onNotice?: (message: string) => void;
32
+ onNotice?: (message: string, tone?: ToastTone) => void;
32
33
  }
33
34
 
34
35
  /**
@@ -69,7 +70,7 @@ export function useWaitingDispatch({ onNotice }: WaitingDispatchOptions = {}): v
69
70
  next.set('sessionId', prompt.sessionId as string);
70
71
  return next;
71
72
  }, { replace: true });
72
- noticeRef.current?.(`Waiting finished — your prompt is now running in a new session.`);
73
+ noticeRef.current?.(`Waiting finished — your prompt is now running in a new session.`, 'success');
73
74
  continue;
74
75
  }
75
76
 
@@ -78,13 +79,13 @@ export function useWaitingDispatch({ onNotice }: WaitingDispatchOptions = {}): v
78
79
  if (!held && openId !== pendingId) continue;
79
80
  clearPendingSessionWaiting(pendingId);
80
81
  releasePendingSession(pendingId);
81
- noticeRef.current?.(`The prompt you held was not sent: ${prompt.error ?? 'the dispatch failed.'}`);
82
+ noticeRef.current?.(`The prompt you held was not sent: ${prompt.error ?? 'the dispatch failed.'}`, 'error');
82
83
  continue;
83
84
  }
84
85
 
85
86
  if (prompt.status === 'cancelled' && held) {
86
87
  clearPendingSessionWaiting(pendingId);
87
- noticeRef.current?.('The held prompt was cancelled.');
88
+ noticeRef.current?.('The held prompt was cancelled.', 'success');
88
89
  }
89
90
  }
90
91
  }, [prompts, setSearchParams]);
@@ -15,6 +15,7 @@ import { useCallback, useMemo } from 'preact/hooks';
15
15
  import { useWaitingPrompts } from '@/client/hooks/chat/waiting/store';
16
16
  import { useCancelWait } from '@/client/hooks/chat/waiting/cancel';
17
17
  import type { WaitingPrompt } from '@/shared/types/waiting';
18
+ import type { ToastTone } from '@/shared/lib/ui/toast-duration';
18
19
 
19
20
  export interface HeldWait {
20
21
  /** The waiting row for the open chat, or null. */
@@ -25,7 +26,7 @@ export interface HeldWait {
25
26
  export function useHeldWait(
26
27
  sessionId: string | null,
27
28
  isPendingSession: boolean,
28
- onNotice?: (message: string, type?: 'success' | 'error') => void,
29
+ onNotice?: (message: string, type?: ToastTone) => void,
29
30
  ): HeldWait {
30
31
  const { prompts } = useWaitingPrompts();
31
32
  const cancelWait = useCancelWait(onNotice);
@@ -31,12 +31,13 @@ import type { ProviderItem } from '@/shared/types';
31
31
  import { saveProviderOverlay, setProviderEnabled, deleteProvider } from '@/shared/lib/models/provider/connection';
32
32
  import { addProviderMessage } from '@/client/hooks/settings/providers/messages';
33
33
  import { loadProvidersFromApi } from '@/client/hooks/settings/providers/api';
34
+ import type { ToastTone } from '@/shared/lib/ui/toast-duration';
34
35
 
35
36
  export interface ProviderActionsDeps {
36
37
  providers: ProviderItem[];
37
38
  selectedProvider: ProviderItem | undefined;
38
39
  isDeletingProvider: boolean;
39
- pushToast: (message: string, tone: 'success' | 'error') => void;
40
+ pushToast: (message: string, tone: ToastTone) => void;
40
41
  setProviders: (providers: ProviderItem[]) => void;
41
42
  setSelectedProviderId: (id: string) => void;
42
43
  setIsAddModalOpen: (open: boolean) => void;
@@ -209,7 +210,7 @@ export function createProviderActions(deps: ProviderActionsDeps) {
209
210
  // The overlay row is gone even when the file cleanup failed, so the
210
211
  // warning is reported rather than presented as a clean delete.
211
212
  if (result.warning) {
212
- pushToast(`${provider.name} removed from Kabmo, but models.yml cleanup failed: ${result.warning}`, 'error');
213
+ pushToast(`${provider.name} removed from Kabmo, but models.yml cleanup failed: ${result.warning}`, 'warning');
213
214
  } else if (result.removedFromOmp) {
214
215
  const count = result.modelsRemoved ?? 0;
215
216
  pushToast(
@@ -14,12 +14,13 @@
14
14
  */
15
15
 
16
16
  import type { ProviderItem } from '@/shared/types';
17
+ import type { ToastTone } from '@/shared/lib/ui/toast-duration';
17
18
 
18
19
  /** The success/failure line for an Add Provider submission. */
19
20
  export function addProviderMessage(
20
21
  provider: ProviderItem,
21
22
  options: { fetchedCount: number; ompNote?: string },
22
- ): { text: string; tone: 'success' | 'error' } {
23
+ ): { text: string; tone: ToastTone } {
23
24
  if (provider.modelSource === 'discovery') {
24
25
  return { text: `${provider.name} registered — omp discovers its models on each run.`, tone: 'success' };
25
26
  }
@@ -37,12 +38,13 @@ export function addProviderMessage(
37
38
  }
38
39
  if (options.fetchedCount === -1) {
39
40
  // The listing failed. When omp reported a reason it is the actionable half,
40
- // so it is quoted rather than replaced by a generic line.
41
+ // so it is quoted rather than replaced by a generic line. The provider IS
42
+ // registered, so this is a partial outcome, not a failed add.
41
43
  return {
42
44
  text: options.ompNote
43
45
  ? `Provider registered, but models could not be listed: ${options.ompNote}`
44
46
  : 'Auto-fetch models failed — provider added with default models.',
45
- tone: 'error',
47
+ tone: 'warning',
46
48
  };
47
49
  }
48
50
  return { text: `${provider.name} registered — no new models to add.`, tone: 'success' };
@@ -56,7 +58,7 @@ export function addProviderMessage(
56
58
  */
57
59
  export function fetchModelsMessage(counts: { addedCount: number; removedCount: number }): {
58
60
  text: string;
59
- tone: 'success' | 'error';
61
+ tone: ToastTone;
60
62
  } {
61
63
  const plural = (count: number) => (count === 1 ? '' : 's');
62
64
  if (counts.addedCount > 0 && counts.removedCount > 0) {
@@ -87,7 +89,7 @@ export function fetchModelsMessage(counts: { addedCount: number; removedCount: n
87
89
  */
88
90
  export function fetchModelsNote(result: {
89
91
  omp?: { written: boolean; addedCount: number; backfilledCount: number; removedCount?: number; reason?: string };
90
- }): { text: string; tone: 'success' | 'error' } | null {
92
+ }): { text: string; tone: ToastTone } | null {
91
93
  if (!result.omp) return null;
92
94
  if (result.omp.written) {
93
95
  const parts: string[] = [];
@@ -106,7 +108,7 @@ export function fetchModelsNote(result: {
106
108
  };
107
109
  }
108
110
  if (result.omp.reason) {
109
- return { text: `omp models.yml not updated: ${result.omp.reason}`, tone: 'error' };
111
+ return { text: `omp models.yml not updated: ${result.omp.reason}`, tone: 'warning' };
110
112
  }
111
113
  return null;
112
114
  }
@@ -122,7 +124,7 @@ export function fetchModelsNote(result: {
122
124
  export function refreshModelsMessage(
123
125
  providerName: string,
124
126
  result: { added: number; removed: number },
125
- ): { text: string; tone: 'success' | 'error' } {
127
+ ): { text: string; tone: ToastTone } {
126
128
  const plural = (count: number) => (count === 1 ? '' : 's');
127
129
  if (result.added > 0 || result.removed > 0) {
128
130
  const parts: string[] = [];
@@ -24,12 +24,13 @@ import {
24
24
  import { removeLegacyKenariModels } from '@/shared/lib/models/provider/cleanup';
25
25
  import { fetchModelsMessage, fetchModelsNote, refreshModelsMessage } from '@/client/hooks/settings/providers/messages';
26
26
  import { saveModelOverrideRemote } from '@/client/hooks/settings/providers/api';
27
+ import type { ToastTone } from '@/shared/lib/ui/toast-duration';
27
28
 
28
29
  export interface ModelActionsDeps {
29
30
  providers: ProviderItem[];
30
31
  selectedProvider: ProviderItem | undefined;
31
32
  isFetchingModels: boolean;
32
- pushToast: (message: string, tone: 'success' | 'error') => void;
33
+ pushToast: (message: string, tone: ToastTone) => void;
33
34
  setProviders: (providers: ProviderItem[]) => void;
34
35
  setIsFetchingModels: (fetching: boolean) => void;
35
36
  persistProviders: (updated: ProviderItem[]) => Promise<void>;