@ateam-ai-mobile/core 0.1.38 → 0.1.41
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/dist/index.d.mts +76 -1
- package/dist/index.d.ts +76 -1
- package/dist/index.js +264 -37
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +257 -37
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
- package/src/api/tenants.ts +2 -0
- package/src/chat/liveGoals.ts +39 -0
- package/src/chat/sideChat.ts +165 -0
- package/src/chat/sideChatPure.ts +59 -0
- package/src/chat/store.ts +15 -7
- package/src/chat/types.ts +7 -1
- package/src/index.ts +6 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ateam-ai-mobile/core",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.41",
|
|
4
4
|
"description": "Headless ADAS SDK core — auth bridge, API client, chat/job streaming, MCP calls, theme tokens. No UI, no Expo dependencies.",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
package/src/api/tenants.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { getConsumerAuthApiUrl, getToken, getConfig, type AdasSession } from '../config';
|
|
2
2
|
import { useChatStore, closeChatStream } from '../chat/store';
|
|
3
|
+
import { clearSideChats } from '../chat/sideChat';
|
|
3
4
|
|
|
4
5
|
export interface TenantMembership {
|
|
5
6
|
id: string;
|
|
@@ -136,6 +137,7 @@ export async function switchTenant(targetTenantId: string): Promise<AdasSession>
|
|
|
136
137
|
// against the new tenant on its next mount / loadConversation().
|
|
137
138
|
closeChatStream();
|
|
138
139
|
useChatStore.getState().clearChat();
|
|
140
|
+
clearSideChats();
|
|
139
141
|
|
|
140
142
|
return session;
|
|
141
143
|
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// The goal checklist of a running job: goals as the main lines, the tools that stream under the current goal.
|
|
2
|
+
// Core sends `goals` ({l:[[id,title,"d"|"t"]], c}) on the job message only when it changes (Core utils/liveGoals.js), so a
|
|
3
|
+
// message without it means "same as before". Tools are not sent at all: they already arrive as the live `→ tool` line and
|
|
4
|
+
// are filed here under the goal current at that moment. Same rule as Core's web chat (packages/side-chat/src/liveGoals.js);
|
|
5
|
+
// the two cannot share a file across repos, so keep them equal. Pure and import-free.
|
|
6
|
+
|
|
7
|
+
export type GoalWire = { l: [string, string, string][]; c?: string | null };
|
|
8
|
+
export type JobGoals = { l: [string, string, string][]; c: string | null; tools: Record<string, string[]>; lastKey?: string; ids?: string };
|
|
9
|
+
export type GoalRow = { id: string; title: string; state: 'done' | 'current' | 'todo'; tools: string[] };
|
|
10
|
+
|
|
11
|
+
const MAX_TOOLS = 4;
|
|
12
|
+
|
|
13
|
+
export function foldGoals(prev: JobGoals | undefined, wire: GoalWire | undefined, liveMessage?: string, liveSeq?: number): JobGoals | undefined {
|
|
14
|
+
const g = wire && Array.isArray(wire.l) ? wire : null;
|
|
15
|
+
if (g && g.l.length === 0) return undefined; // Core says the job has no goals now (a hand-off to a job without a plan)
|
|
16
|
+
const goals = g ? { l: g.l, c: g.c ?? null } : prev ? { l: prev.l, c: prev.c } : null;
|
|
17
|
+
if (!goals) return undefined;
|
|
18
|
+
// A different list (another job's plan, or a re-plan) starts with no tools: plans reuse goal ids, so old tools would land on the new goals.
|
|
19
|
+
const ids = goals.l.map(x => x[0]).join('|');
|
|
20
|
+
const tools = ids === prev?.ids ? { ...(prev?.tools || {}) } : {};
|
|
21
|
+
// A snapshot that only moved the current goal carries the SAME last progress entry as before: file a tool only when that
|
|
22
|
+
// entry is new (its seq changed; an entry without a seq falls back to "the message changed").
|
|
23
|
+
const key = liveSeq != null ? `s${liveSeq}` : `m${liveMessage ?? ''}`;
|
|
24
|
+
const fresh = key !== prev?.lastKey;
|
|
25
|
+
if (fresh && goals.c && liveMessage && liveMessage.startsWith('→ ')) {
|
|
26
|
+
const tool = liveMessage.slice(2).trim();
|
|
27
|
+
const list = tools[goals.c] || [];
|
|
28
|
+
if (tool && list[list.length - 1] !== tool) tools[goals.c] = [...list, tool].slice(-MAX_TOOLS);
|
|
29
|
+
}
|
|
30
|
+
return { ...goals, tools, lastKey: key, ids };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function goalRows(goals: JobGoals | undefined): GoalRow[] {
|
|
34
|
+
if (!goals?.l?.length) return [];
|
|
35
|
+
return goals.l.map(([id, title, s]) => {
|
|
36
|
+
const state = s === 'd' ? 'done' : id === goals.c ? 'current' : 'todo';
|
|
37
|
+
return { id, title, state, tools: state === 'current' ? goals.tools?.[id] || [] : [] };
|
|
38
|
+
});
|
|
39
|
+
}
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Side chat store — one per (workspace, page).
|
|
3
|
+
*
|
|
4
|
+
* A side chat is the person's ONE conversation seen through a topic (Docs/WIDGET_PROTOCOL.md, `open-side-chat`):
|
|
5
|
+
* - send → POST /api/chat, an ordinary chat turn whose triggerContext.pageContext is { page, chat: "page" }, which
|
|
6
|
+
* is how Core tags the turn with the page as its TOPIC and gives those turns their seats first;
|
|
7
|
+
* - open → GET /api/conversation?topic=<page id>, the turns said in this chat before.
|
|
8
|
+
* Same endpoints and rules as the web SideChatWindow; the job is followed by reading its status (no second socket), and its
|
|
9
|
+
* live line (humanStatus, liveProgress) comes from the same snapshot reader as the main chat.
|
|
10
|
+
*/
|
|
11
|
+
import { create } from 'zustand';
|
|
12
|
+
import type { StoreApi, UseBoundStore } from 'zustand';
|
|
13
|
+
import { getCoreApiUrl, getTenant, getUser } from '../config';
|
|
14
|
+
import { blocksToText } from './blockText';
|
|
15
|
+
import { foldGoals } from './liveGoals';
|
|
16
|
+
import { coreHeaders, snapshotToProgress, isTerminalSnapshot, normalizeJobStatus, blocksToAttachments } from './store';
|
|
17
|
+
import { mergeSideChatHistory } from './sideChatPure';
|
|
18
|
+
import type { Message, JobProgress } from './types';
|
|
19
|
+
|
|
20
|
+
const HISTORY_TURNS = 20;
|
|
21
|
+
|
|
22
|
+
export interface SideChatState {
|
|
23
|
+
pageId: string;
|
|
24
|
+
messages: Message[];
|
|
25
|
+
/** A turn of this chat is running: Send waits (the web window does the same). */
|
|
26
|
+
loading: boolean;
|
|
27
|
+
loaded: boolean;
|
|
28
|
+
load: () => Promise<void>;
|
|
29
|
+
send: (text: string) => Promise<boolean>;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
type SideChatStore = UseBoundStore<StoreApi<SideChatState>>;
|
|
33
|
+
const stores = new Map<string, SideChatStore>();
|
|
34
|
+
|
|
35
|
+
/** The side chat for this page in the current workspace; reopened chats keep a running turn. */
|
|
36
|
+
export function getSideChatStore(pageId: string): SideChatStore {
|
|
37
|
+
const key = `${getTenant()}\u0000${pageId}`;
|
|
38
|
+
let s = stores.get(key);
|
|
39
|
+
if (!s) { s = createSideChatStore(pageId); stores.set(key, s); }
|
|
40
|
+
return s;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Forget every side chat (sign-out, workspace or environment switch). */
|
|
44
|
+
export function clearSideChats(): void { stores.clear(); }
|
|
45
|
+
|
|
46
|
+
function turnToMessages(turn: any): Message[] {
|
|
47
|
+
const out: Message[] = [];
|
|
48
|
+
const chainId = typeof turn?.chainId === 'string' ? turn.chainId : undefined;
|
|
49
|
+
const base = turn?.jobId || turn?.chainId || `${turn?.startedAt || Date.now()}`;
|
|
50
|
+
const userText = blocksToText(turn?.user?.blocks);
|
|
51
|
+
const userAtts = blocksToAttachments(turn?.user?.blocks);
|
|
52
|
+
if (userText || userAtts) {
|
|
53
|
+
out.push({ id: `user-${base}`, role: 'user', content: userText || '', timestamp: new Date(turn.startedAt || Date.now()), ...(userAtts ? { attachments: userAtts } : {}), ...(chainId ? { chainId } : {}) });
|
|
54
|
+
}
|
|
55
|
+
const answer = blocksToText(turn?.assistant?.blocks);
|
|
56
|
+
const actions = Array.isArray(turn?.assistant?.actions) && turn.assistant.actions.length ? turn.assistant.actions : undefined;
|
|
57
|
+
if (answer || actions) {
|
|
58
|
+
out.push({ id: `bot-${base}`, role: 'assistant', content: answer || '', timestamp: new Date(turn.finishedAt || turn.startedAt || Date.now()), skillSlug: turn.skillSlug, ...(actions ? { actions } : {}), ...(chainId ? { chainId } : {}) });
|
|
59
|
+
} else if (turn?.status === 'failed') {
|
|
60
|
+
out.push({ id: `err-${base}`, role: 'system', content: turn.failReason || 'This turn failed.', timestamp: new Date(turn.finishedAt || turn.startedAt || Date.now()), ...(chainId ? { chainId } : {}) });
|
|
61
|
+
}
|
|
62
|
+
return out;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function createSideChatStore(pageId: string): SideChatStore {
|
|
66
|
+
return create<SideChatState>((set, get) => {
|
|
67
|
+
const local = (m: Omit<Message, 'local'>): Message => ({ ...m, local: true });
|
|
68
|
+
const patchJob = (jobId: string, p: Partial<JobProgress>) => {
|
|
69
|
+
const { goalsWire, ...rest } = p;
|
|
70
|
+
set(s => ({
|
|
71
|
+
messages: s.messages.map(m => (m.jobProgress?.jobId === jobId
|
|
72
|
+
? { ...m, jobProgress: { ...m.jobProgress, ...rest, goals: foldGoals(m.jobProgress.goals, goalsWire, p.liveProgress?.message, p.liveProgress?.seq) } as JobProgress }
|
|
73
|
+
: m)),
|
|
74
|
+
}));
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
// Follow the job by reading its status until it ends (a hand-over keeps going), then read the saved turn.
|
|
78
|
+
async function follow(jobId: string, chainId: string) {
|
|
79
|
+
let ended: any = null;
|
|
80
|
+
for (let i = 0; !ended; i++) {
|
|
81
|
+
if (i > 0) await new Promise(r => setTimeout(r, i < 120 ? 1500 : 5000));
|
|
82
|
+
// The chat was cleared away (workspace switch): stop.
|
|
83
|
+
if (!get().messages.some(m => m.jobProgress?.jobId === jobId)) return;
|
|
84
|
+
try {
|
|
85
|
+
const res = await fetch(`${getCoreApiUrl()}/api/job/${encodeURIComponent(jobId)}/status`, { headers: coreHeaders() });
|
|
86
|
+
if (!res.ok) { if (res.status === 404) break; continue; }
|
|
87
|
+
const snap = await res.json();
|
|
88
|
+
const handoff = snap?.isHandoff || snap?.state?.handoffTransfer;
|
|
89
|
+
if (isTerminalSnapshot(snap) && !(normalizeJobStatus(snap) === 'done' && handoff)) ended = snap;
|
|
90
|
+
else patchJob(jobId, snapshotToProgress(snap, jobId));
|
|
91
|
+
} catch { /* a read failed: try again */ }
|
|
92
|
+
}
|
|
93
|
+
// The saved turn replaces the live bubble; give the server a moment to save it.
|
|
94
|
+
for (let t = 0; t < 5; t++) {
|
|
95
|
+
await get().load();
|
|
96
|
+
if (!get().messages.some(m => m.jobProgress?.jobId === jobId)) { set({ loading: false }); return; }
|
|
97
|
+
await new Promise(r => setTimeout(r, 800));
|
|
98
|
+
}
|
|
99
|
+
const failed = ended ? normalizeJobStatus(ended) === 'error' : false;
|
|
100
|
+
const fallback = ended?.result?.message || ended?.state?.finalReply || (failed ? 'Something went wrong. Please try again.' : 'Done.');
|
|
101
|
+
set(s => ({
|
|
102
|
+
loading: false,
|
|
103
|
+
messages: s.messages.map(m => (m.jobProgress?.jobId === jobId
|
|
104
|
+
? { ...m, id: `done-${jobId}`, content: fallback, jobProgress: { ...m.jobProgress, status: failed ? 'error' : 'done' } as JobProgress, chainId }
|
|
105
|
+
: m)),
|
|
106
|
+
}));
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
return {
|
|
110
|
+
pageId,
|
|
111
|
+
messages: [],
|
|
112
|
+
loading: false,
|
|
113
|
+
loaded: false,
|
|
114
|
+
|
|
115
|
+
load: async () => {
|
|
116
|
+
try {
|
|
117
|
+
const res = await fetch(`${getCoreApiUrl()}/api/conversation?topic=${encodeURIComponent(pageId)}&page_size=${HISTORY_TURNS}`, { headers: coreHeaders() });
|
|
118
|
+
if (!res.ok) { set({ loaded: true }); return; }
|
|
119
|
+
const json = await res.json();
|
|
120
|
+
const items: any[] = Array.isArray(json?.items) ? [...json.items].reverse() : [];
|
|
121
|
+
const seen = new Set<string>();
|
|
122
|
+
const saved = items.filter(t => { const k = t?.jobId; if (!k) return true; if (seen.has(k)) return false; seen.add(k); return true; }).flatMap(turnToMessages);
|
|
123
|
+
set(s => ({ messages: mergeSideChatHistory(saved, s.messages), loaded: true }));
|
|
124
|
+
} catch { set({ loaded: true }); }
|
|
125
|
+
},
|
|
126
|
+
|
|
127
|
+
send: async (text: string) => {
|
|
128
|
+
const t = text.trim();
|
|
129
|
+
if (!t || get().loading) return false;
|
|
130
|
+
const echo = local({ id: `user-${Date.now()}`, role: 'user', content: t, timestamp: new Date() });
|
|
131
|
+
set(s => ({ messages: [...s.messages, echo], loading: true }));
|
|
132
|
+
const fail = (msg: string) => set(s => ({ loading: false, messages: [...s.messages, local({ id: `error-${Date.now()}`, role: 'system', content: msg, timestamp: new Date() })] }));
|
|
133
|
+
try {
|
|
134
|
+
const actor = getUser();
|
|
135
|
+
const res = await fetch(`${getCoreApiUrl()}/api/chat`, {
|
|
136
|
+
method: 'POST',
|
|
137
|
+
headers: coreHeaders(),
|
|
138
|
+
body: JSON.stringify({
|
|
139
|
+
goal: t,
|
|
140
|
+
triggerContext: {
|
|
141
|
+
channel: 'mobile',
|
|
142
|
+
replyContext: { chatId: actor?.actorId || 'unknown' },
|
|
143
|
+
pageContext: { page: pageId, chat: 'page' },
|
|
144
|
+
},
|
|
145
|
+
}),
|
|
146
|
+
});
|
|
147
|
+
const json = await res.json().catch(() => null);
|
|
148
|
+
const jobId = json?.jobId || json?.id;
|
|
149
|
+
if (!res.ok || !jobId) { fail(json?.error || `Could not start (${res.status}).`); return false; }
|
|
150
|
+
const chainId: string = json.job?.chainId || jobId; // what the saved turn is filed under
|
|
151
|
+
const bubble = local({
|
|
152
|
+
id: `job-${jobId}`, role: 'assistant', content: 'Working on it...', timestamp: new Date(), chainId,
|
|
153
|
+
jobProgress: { jobId, actorId: actor?.actorId, status: 'running', subStatus: 'Starting...', chainStartedAt: Date.now() },
|
|
154
|
+
});
|
|
155
|
+
set(s => ({ messages: [...s.messages.map(m => (m.id === echo.id ? { ...m, chainId } : m)), bubble] }));
|
|
156
|
+
void follow(jobId, chainId);
|
|
157
|
+
return true;
|
|
158
|
+
} catch (e: any) {
|
|
159
|
+
fail(`Request failed: ${e?.message || e}`);
|
|
160
|
+
return false;
|
|
161
|
+
}
|
|
162
|
+
},
|
|
163
|
+
};
|
|
164
|
+
});
|
|
165
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Side chat — the pure rules (no imports of the SDK, so they run under plain node tests).
|
|
3
|
+
*
|
|
4
|
+
* A builder's page asks for a side chat with the widget message `open-side-chat`. The look it may give the chat is
|
|
5
|
+
* cleaned here (same limits and shape as the web host: ai-dev-assistant packages/widget-surface/src/sideChatOptions.js),
|
|
6
|
+
* and the chat's saved turns are merged with the messages this phone sent that the server has not saved yet.
|
|
7
|
+
*/
|
|
8
|
+
import type { Message } from './types';
|
|
9
|
+
|
|
10
|
+
export const SIDE_CHAT_LIMITS = { title: 60, header: 40, welcome: 200, placeholder: 60 } as const;
|
|
11
|
+
const HEX = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;
|
|
12
|
+
|
|
13
|
+
export interface SideChatOptions {
|
|
14
|
+
title: string;
|
|
15
|
+
header: string;
|
|
16
|
+
welcome: string;
|
|
17
|
+
placeholder: string;
|
|
18
|
+
accent: string | null;
|
|
19
|
+
side: 'left' | 'right';
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const text = (v: unknown, max: number): string =>
|
|
23
|
+
(typeof v === 'string' ? v.replace(/\s+/g, ' ').trim().slice(0, max) : '');
|
|
24
|
+
|
|
25
|
+
/** What the page asked for, cleaned: plain text cut to a length, one hex color, `left`/`right`. A widget is not trusted with markup. */
|
|
26
|
+
export function sideChatOptions(payload: unknown): SideChatOptions {
|
|
27
|
+
const p: any = payload && typeof payload === 'object' ? payload : {};
|
|
28
|
+
return {
|
|
29
|
+
title: text(p.title, SIDE_CHAT_LIMITS.title),
|
|
30
|
+
header: text(p.header, SIDE_CHAT_LIMITS.header),
|
|
31
|
+
welcome: text(p.welcome, SIDE_CHAT_LIMITS.welcome),
|
|
32
|
+
placeholder: text(p.placeholder, SIDE_CHAT_LIMITS.placeholder),
|
|
33
|
+
accent: typeof p.accent === 'string' && HEX.test(p.accent.trim()) ? p.accent.trim() : null,
|
|
34
|
+
side: p.side === 'left' ? 'left' : 'right',
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const SHORT = new Set(['ui', 'ai', 'mcp', 'api', 'crm', 'sms', 'pa']);
|
|
39
|
+
const nameOf = (slug: string): string =>
|
|
40
|
+
slug.split(/[-_]+/).filter(Boolean)
|
|
41
|
+
.map(w => (SHORT.has(w.toLowerCase()) ? w.toUpperCase() : w[0].toUpperCase() + w.slice(1))).join(' ');
|
|
42
|
+
|
|
43
|
+
/** The words in the TOPIC tag: the title the page gave, else the last part of its page id ("mcp:crm:deal-board" → "Deal Board"). */
|
|
44
|
+
export function topicLabel(pageId: string, title?: string): string {
|
|
45
|
+
if (title) return title;
|
|
46
|
+
const last = String(pageId || '').split(':').pop() || '';
|
|
47
|
+
return nameOf(last) || 'Side chat';
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* The chat's messages: the server's saved turns (oldest first), then this phone's own messages of a turn the server does
|
|
52
|
+
* not hold yet. A local message carries `chainId`; it is dropped once a saved message of that chain is there. A local
|
|
53
|
+
* message with no chain (a send that never started, an error) stays. So a turn is drawn once.
|
|
54
|
+
*/
|
|
55
|
+
export function mergeSideChatHistory(saved: Message[], current: Message[]): Message[] {
|
|
56
|
+
const savedChains = new Set(saved.map(m => m.chainId).filter(Boolean) as string[]);
|
|
57
|
+
const keep = current.filter(m => m.local && !(m.chainId && savedChains.has(m.chainId)));
|
|
58
|
+
return [...saved, ...keep];
|
|
59
|
+
}
|
package/src/chat/store.ts
CHANGED
|
@@ -18,6 +18,7 @@ import { focusPlugin } from '../utils/hostIntents';
|
|
|
18
18
|
import type { OutgoingAttachment } from '../storage/types';
|
|
19
19
|
import { prepareAttachments } from './attachments';
|
|
20
20
|
import { blocksToText } from './blockText';
|
|
21
|
+
import { foldGoals } from './liveGoals';
|
|
21
22
|
import type { Message, MessageAttachment, JobProgress, UIAction } from './types';
|
|
22
23
|
|
|
23
24
|
// ---------------------------------------------------------------------------
|
|
@@ -48,7 +49,7 @@ interface ChatState {
|
|
|
48
49
|
// Helpers
|
|
49
50
|
// ---------------------------------------------------------------------------
|
|
50
51
|
|
|
51
|
-
function coreHeaders(): Record<string, string> {
|
|
52
|
+
export function coreHeaders(): Record<string, string> {
|
|
52
53
|
const token = getToken();
|
|
53
54
|
const headers: Record<string, string> = {
|
|
54
55
|
'Content-Type': 'application/json',
|
|
@@ -62,7 +63,7 @@ function isTerminalStatus(status?: unknown): boolean {
|
|
|
62
63
|
return s === 'done' || s === 'error' || s === 'failed' || s === 'completed';
|
|
63
64
|
}
|
|
64
65
|
|
|
65
|
-
function normalizeJobStatus(snap: any): JobProgress['status'] {
|
|
66
|
+
export function normalizeJobStatus(snap: any): JobProgress['status'] {
|
|
66
67
|
const status = typeof snap?.status === 'string' ? snap.status.toLowerCase() : '';
|
|
67
68
|
if (status === 'done' || status === 'completed') return 'done';
|
|
68
69
|
if (status === 'error' || status === 'failed') return 'error';
|
|
@@ -94,6 +95,7 @@ function extractLiveProgress(snap: any): JobProgress['liveProgress'] | undefined
|
|
|
94
95
|
message: String(latest.message || ''),
|
|
95
96
|
...(latest.step != null ? { step: latest.step } : {}),
|
|
96
97
|
...(latest.total != null ? { total: latest.total } : {}),
|
|
98
|
+
...(latest.seq != null ? { seq: latest.seq } : {}),
|
|
97
99
|
};
|
|
98
100
|
}
|
|
99
101
|
|
|
@@ -115,7 +117,7 @@ function extractCurrentTool(state: any): string | undefined {
|
|
|
115
117
|
return (last?.tool || last?.phase) as string | undefined;
|
|
116
118
|
}
|
|
117
119
|
|
|
118
|
-
function snapshotToProgress(snap: any, rootJobId: string): Partial<JobProgress> {
|
|
120
|
+
export function snapshotToProgress(snap: any, rootJobId: string): Partial<JobProgress> {
|
|
119
121
|
const pq = extractPendingQuestion(snap);
|
|
120
122
|
const progress: Partial<JobProgress> = {
|
|
121
123
|
jobId: rootJobId,
|
|
@@ -134,6 +136,7 @@ function snapshotToProgress(snap: any, rootJobId: string): Partial<JobProgress>
|
|
|
134
136
|
// Human-language status (additive; absent when disabled/uncached).
|
|
135
137
|
if (typeof snap?.humanStatus === 'string' && snap.humanStatus) progress.humanStatus = snap.humanStatus;
|
|
136
138
|
if (snap?.humanLabels && typeof snap.humanLabels === 'object') progress.humanLabels = snap.humanLabels;
|
|
139
|
+
if (snap?.goals && Array.isArray(snap.goals.l)) progress.goalsWire = snap.goals;
|
|
137
140
|
|
|
138
141
|
if (pq) {
|
|
139
142
|
progress.pendingQuestion = {
|
|
@@ -148,13 +151,13 @@ function snapshotToProgress(snap: any, rootJobId: string): Partial<JobProgress>
|
|
|
148
151
|
return progress;
|
|
149
152
|
}
|
|
150
153
|
|
|
151
|
-
function isTerminalSnapshot(snap: any): boolean {
|
|
154
|
+
export function isTerminalSnapshot(snap: any): boolean {
|
|
152
155
|
if (extractPendingQuestion(snap)) return false;
|
|
153
156
|
return snap?.done === true || isTerminalStatus(snap?.status);
|
|
154
157
|
}
|
|
155
158
|
|
|
156
159
|
/** Extract image/file attachments from conversation blocks */
|
|
157
|
-
function blocksToAttachments(blocks?: Array<{ kind: string; hash?: string; url?: string; mimeType?: string; name?: string }>): MessageAttachment[] | undefined {
|
|
160
|
+
export function blocksToAttachments(blocks?: Array<{ kind: string; hash?: string; url?: string; mimeType?: string; name?: string }>): MessageAttachment[] | undefined {
|
|
158
161
|
if (!blocks || blocks.length === 0) return undefined;
|
|
159
162
|
const atts: MessageAttachment[] = [];
|
|
160
163
|
for (const b of blocks) {
|
|
@@ -339,12 +342,14 @@ export const useChatStore = create<ChatState>((set, get) => ({
|
|
|
339
342
|
? slim.createdAt
|
|
340
343
|
: (typeof slim.lastUpdate === 'number' ? slim.lastUpdate : Date.now());
|
|
341
344
|
const chainLastUpdate = typeof slim.lastUpdate === 'number' ? slim.lastUpdate : chainCreatedAt;
|
|
345
|
+
const { goalsWire, ...progressRest } = progress;
|
|
342
346
|
const jobProgress = {
|
|
343
347
|
jobId: chainId,
|
|
344
348
|
actorId: extractActorId(slim),
|
|
345
349
|
status: 'running',
|
|
346
350
|
chainStartedAt: chainCreatedAt,
|
|
347
|
-
...
|
|
351
|
+
...progressRest,
|
|
352
|
+
goals: foldGoals(undefined, goalsWire, progress.liveProgress?.message, progress.liveProgress?.seq),
|
|
348
353
|
} as JobProgress;
|
|
349
354
|
|
|
350
355
|
// Synthesize the user bubble if a hard refresh wiped the optimistic
|
|
@@ -592,7 +597,10 @@ export const useChatStore = create<ChatState>((set, get) => ({
|
|
|
592
597
|
set(s => ({
|
|
593
598
|
messages: s.messages.map(m => {
|
|
594
599
|
if (m.jobProgress?.jobId === jobId) {
|
|
595
|
-
const
|
|
600
|
+
const { goalsWire, ...rest } = progress;
|
|
601
|
+
const updated = { ...m.jobProgress, ...rest };
|
|
602
|
+
// Goal checklist: goals arrive only when they change; the streamed `→ tool` line is filed under the current goal.
|
|
603
|
+
updated.goals = foldGoals(m.jobProgress.goals, goalsWire, progress.liveProgress?.message, progress.liveProgress?.seq);
|
|
596
604
|
// Clear pendingQuestion when status is no longer paused
|
|
597
605
|
if (progress.status && progress.status !== 'paused') {
|
|
598
606
|
updated.pendingQuestion = undefined;
|
package/src/chat/types.ts
CHANGED
|
@@ -25,13 +25,17 @@ export interface JobProgress {
|
|
|
25
25
|
/** UI Action chips to attach to the assistant bubble when this job finishes. */
|
|
26
26
|
resultActions?: UIAction[];
|
|
27
27
|
/** Live progress from adas_emit_progress() — latest event from a running fat tool */
|
|
28
|
-
liveProgress?: { message: string; step?: number; total?: number };
|
|
28
|
+
liveProgress?: { message: string; step?: number; total?: number; seq?: number };
|
|
29
29
|
/** One warm, present-tense, localized line describing the current action
|
|
30
30
|
* (backend statusI18n). Absent when disabled / not yet cached → fall back
|
|
31
31
|
* to raw tokens. */
|
|
32
32
|
humanStatus?: string;
|
|
33
33
|
/** Lookup { rawToken → friendly phrase } for tokens in this snapshot. */
|
|
34
34
|
humanLabels?: Record<string, string>;
|
|
35
|
+
/** The job's goal checklist, built from the goals Core streams on the job message plus the live `→ tool` line (chat/liveGoals.ts). */
|
|
36
|
+
goals?: import('./liveGoals').JobGoals;
|
|
37
|
+
/** The raw `goals` of ONE job message, in transit from snapshotToProgress to updateJobProgress (which folds it into `goals` and drops it). */
|
|
38
|
+
goalsWire?: import('./liveGoals').GoalWire;
|
|
35
39
|
pendingQuestion?: {
|
|
36
40
|
inputId: string;
|
|
37
41
|
question: string;
|
|
@@ -81,4 +85,6 @@ export interface Message {
|
|
|
81
85
|
chainId?: string;
|
|
82
86
|
/** Turn variant. 'notification' = proactive/system-initiated. */
|
|
83
87
|
kind?: 'notification' | string;
|
|
88
|
+
/** A side chat's own message this phone sent that the server has not saved yet (see chat/sideChat.ts). */
|
|
89
|
+
local?: boolean;
|
|
84
90
|
}
|
package/src/index.ts
CHANGED
|
@@ -147,6 +147,10 @@ export {
|
|
|
147
147
|
useChatStore,
|
|
148
148
|
closeChatStream,
|
|
149
149
|
} from './chat/store';
|
|
150
|
+
export { getSideChatStore, clearSideChats } from './chat/sideChat';
|
|
151
|
+
export type { SideChatState } from './chat/sideChat';
|
|
152
|
+
export { sideChatOptions, topicLabel, mergeSideChatHistory, SIDE_CHAT_LIMITS } from './chat/sideChatPure';
|
|
153
|
+
export type { SideChatOptions } from './chat/sideChatPure';
|
|
150
154
|
export {
|
|
151
155
|
blocksToText,
|
|
152
156
|
splitBlockSegments,
|
|
@@ -209,6 +213,8 @@ export type {
|
|
|
209
213
|
FileUploadRequest,
|
|
210
214
|
} from './storage/types';
|
|
211
215
|
export { MAX_ATTACHMENT_BYTES, MAX_INLINE_ATTACHMENT_BYTES } from './storage/types';
|
|
216
|
+
export { goalRows } from './chat/liveGoals';
|
|
217
|
+
export type { JobGoals, GoalRow } from './chat/liveGoals';
|
|
212
218
|
export { prepareAttachments } from './chat/attachments';
|
|
213
219
|
export type { WireAttachment } from './chat/attachments';
|
|
214
220
|
|