@webiny/app-admin 6.6.0-alpha.10 → 6.6.0-alpha.11
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/features/accessManagement/roles/roleEvents/AddCreatedRoleToCache.d.ts +12 -0
- package/features/accessManagement/roles/roleEvents/AddCreatedRoleToCache.js +18 -0
- package/features/accessManagement/roles/roleEvents/AddCreatedRoleToCache.js.map +1 -0
- package/features/accessManagement/roles/roleEvents/RefreshRoleInCacheRepository.d.ts +18 -0
- package/features/accessManagement/roles/roleEvents/RefreshRoleInCacheRepository.js +26 -0
- package/features/accessManagement/roles/roleEvents/RefreshRoleInCacheRepository.js.map +1 -0
- package/features/accessManagement/roles/roleEvents/RefreshUpdatedRoleInCache.d.ts +12 -0
- package/features/accessManagement/roles/roleEvents/RefreshUpdatedRoleInCache.js +18 -0
- package/features/accessManagement/roles/roleEvents/RefreshUpdatedRoleInCache.js.map +1 -0
- package/features/accessManagement/roles/roleEvents/RemoveDeletedRoleFromCache.d.ts +12 -0
- package/features/accessManagement/roles/roleEvents/RemoveDeletedRoleFromCache.js +20 -0
- package/features/accessManagement/roles/roleEvents/RemoveDeletedRoleFromCache.js.map +1 -0
- package/features/accessManagement/roles/roleEvents/RoleCreatedEvent.d.ts +14 -0
- package/features/accessManagement/roles/roleEvents/RoleCreatedEvent.js +13 -0
- package/features/accessManagement/roles/roleEvents/RoleCreatedEvent.js.map +1 -0
- package/features/accessManagement/roles/roleEvents/RoleDeletedEvent.d.ts +9 -0
- package/features/accessManagement/roles/roleEvents/RoleDeletedEvent.js +13 -0
- package/features/accessManagement/roles/roleEvents/RoleDeletedEvent.js.map +1 -0
- package/features/accessManagement/roles/roleEvents/RoleUpdatedEvent.d.ts +9 -0
- package/features/accessManagement/roles/roleEvents/RoleUpdatedEvent.js +13 -0
- package/features/accessManagement/roles/roleEvents/RoleUpdatedEvent.js.map +1 -0
- package/features/accessManagement/roles/roleEvents/RoleWebsocketMessages.d.ts +12 -0
- package/features/accessManagement/roles/roleEvents/RoleWebsocketMessages.js +49 -0
- package/features/accessManagement/roles/roleEvents/RoleWebsocketMessages.js.map +1 -0
- package/features/accessManagement/roles/roleEvents/abstractions.d.ts +33 -0
- package/features/accessManagement/roles/roleEvents/abstractions.js +8 -0
- package/features/accessManagement/roles/roleEvents/abstractions.js.map +1 -0
- package/features/accessManagement/roles/roleEvents/feature.d.ts +5 -0
- package/features/accessManagement/roles/roleEvents/feature.js +19 -0
- package/features/accessManagement/roles/roleEvents/feature.js.map +1 -0
- package/features/accessManagement/roles/roleEvents/index.d.ts +1 -0
- package/features/accessManagement/roles/roleEvents/index.js +1 -0
- package/features/accessManagement/teams/teamEvents/AddCreatedTeamToCache.d.ts +12 -0
- package/features/accessManagement/teams/teamEvents/AddCreatedTeamToCache.js +18 -0
- package/features/accessManagement/teams/teamEvents/AddCreatedTeamToCache.js.map +1 -0
- package/features/accessManagement/teams/teamEvents/RefreshTeamInCacheRepository.d.ts +18 -0
- package/features/accessManagement/teams/teamEvents/RefreshTeamInCacheRepository.js +26 -0
- package/features/accessManagement/teams/teamEvents/RefreshTeamInCacheRepository.js.map +1 -0
- package/features/accessManagement/teams/teamEvents/RefreshUpdatedTeamInCache.d.ts +12 -0
- package/features/accessManagement/teams/teamEvents/RefreshUpdatedTeamInCache.js +18 -0
- package/features/accessManagement/teams/teamEvents/RefreshUpdatedTeamInCache.js.map +1 -0
- package/features/accessManagement/teams/teamEvents/RemoveDeletedTeamFromCache.d.ts +12 -0
- package/features/accessManagement/teams/teamEvents/RemoveDeletedTeamFromCache.js +20 -0
- package/features/accessManagement/teams/teamEvents/RemoveDeletedTeamFromCache.js.map +1 -0
- package/features/accessManagement/teams/teamEvents/TeamCreatedEvent.d.ts +14 -0
- package/features/accessManagement/teams/teamEvents/TeamCreatedEvent.js +13 -0
- package/features/accessManagement/teams/teamEvents/TeamCreatedEvent.js.map +1 -0
- package/features/accessManagement/teams/teamEvents/TeamDeletedEvent.d.ts +9 -0
- package/features/accessManagement/teams/teamEvents/TeamDeletedEvent.js +13 -0
- package/features/accessManagement/teams/teamEvents/TeamDeletedEvent.js.map +1 -0
- package/features/accessManagement/teams/teamEvents/TeamUpdatedEvent.d.ts +9 -0
- package/features/accessManagement/teams/teamEvents/TeamUpdatedEvent.js +13 -0
- package/features/accessManagement/teams/teamEvents/TeamUpdatedEvent.js.map +1 -0
- package/features/accessManagement/teams/teamEvents/TeamWebsocketMessages.d.ts +12 -0
- package/features/accessManagement/teams/teamEvents/TeamWebsocketMessages.js +48 -0
- package/features/accessManagement/teams/teamEvents/TeamWebsocketMessages.js.map +1 -0
- package/features/accessManagement/teams/teamEvents/abstractions.d.ts +33 -0
- package/features/accessManagement/teams/teamEvents/abstractions.js +8 -0
- package/features/accessManagement/teams/teamEvents/abstractions.js.map +1 -0
- package/features/accessManagement/teams/teamEvents/feature.d.ts +5 -0
- package/features/accessManagement/teams/teamEvents/feature.js +19 -0
- package/features/accessManagement/teams/teamEvents/feature.js.map +1 -0
- package/features/accessManagement/teams/teamEvents/index.d.ts +1 -0
- package/features/accessManagement/teams/teamEvents/index.js +1 -0
- package/features/adminAssistant/AdminAssistantGateway.js +3 -3
- package/features/adminAssistant/AdminAssistantGateway.js.map +1 -1
- package/features/adminAssistant/AdminAssistantPresenter.d.ts +8 -12
- package/features/adminAssistant/AdminAssistantPresenter.js +45 -87
- package/features/adminAssistant/AdminAssistantPresenter.js.map +1 -1
- package/features/adminAssistant/abstractions.d.ts +28 -23
- package/features/adminAssistant/abstractions.js.map +1 -1
- package/features/adminAssistant/turnsFromMessages.d.ts +4 -7
- package/features/adminAssistant/turnsFromMessages.js +0 -2
- package/features/adminAssistant/turnsFromMessages.js.map +1 -1
- package/features/aiChats/AiChatsGateway.d.ts +0 -3
- package/features/aiChats/AiChatsGateway.js +1 -26
- package/features/aiChats/AiChatsGateway.js.map +1 -1
- package/features/aiChats/AiChatsRepository.d.ts +1 -3
- package/features/aiChats/AiChatsRepository.js +9 -28
- package/features/aiChats/AiChatsRepository.js.map +1 -1
- package/features/aiChats/abstractions.d.ts +7 -19
- package/features/aiChats/abstractions.js.map +1 -1
- package/features/aiChats/index.d.ts +0 -2
- package/features/aiChats/index.js +0 -1
- package/index.d.ts +1 -1
- package/modules/AccessManagementExtension.js +6 -0
- package/modules/AccessManagementExtension.js.map +1 -1
- package/package.json +20 -20
- package/features/aiChats/AiChatSaveError.d.ts +0 -6
- package/features/aiChats/AiChatSaveError.js +0 -8
- package/features/aiChats/AiChatSaveError.js.map +0 -1
- package/features/aiChats/AiChatsRequestError.d.ts +0 -9
- package/features/aiChats/AiChatsRequestError.js +0 -8
- package/features/aiChats/AiChatsRequestError.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"features/adminAssistant/AdminAssistantPresenter.js","sources":["../../../src/features/adminAssistant/AdminAssistantPresenter.ts"],"sourcesContent":["import { makeAutoObservable } from \"mobx\";\nimport { AdminAssistantGateway } from \"./abstractions.js\";\nimport type { AdminAssistantMessage, AdminAssistantRequest } from \"./abstractions.js\";\nimport {\n AdminAssistantPresenter as Abstraction,\n type AiTurnViewModel,\n type IAdminAssistantViewModel\n} from \"./abstractions.js\";\nimport { AiChatsRepository } from \"~/features/aiChats/abstractions.js\";\nimport type { AiChatSaveFailure } from \"~/features/aiChats/abstractions.js\";\nimport { AiChatSaveError } from \"~/features/aiChats/AiChatSaveError.js\";\nimport { messageOf } from \"~/features/aiChats/messageOf.js\";\nimport { turnsFromMessages } from \"./turnsFromMessages.js\";\n\n/** A turn plus the conversation state the view never sees. `needsSetup` is derived from `errorCode`. */\ninterface Turn extends Omit<AiTurnViewModel, \"needsSetup\"> {\n /** Server messages replayed to continue this conversation or resume its approval. */\n messages: AdminAssistantMessage[];\n /** The server's code for the failure, when it sent one. */\n errorCode?: string;\n}\n\n/** The code a run fails with when the project's AI settings give the assistant no model. */\nconst NOT_CONFIGURED = \"AI_CAPABILITY_NOT_CONFIGURED\";\n\n/** The repository says why a save failed; anything else it threw never reached the server. */\nconst saveFailureOf = (error: unknown): AiChatSaveFailure => {\n return error instanceof AiChatSaveError ? error.failure : \"unreachable\";\n};\n\nconst emptyTurn = (question: string): Turn => ({\n question,\n text: \"\",\n answerStart: 0,\n tools: [],\n completed: [],\n failed: [],\n running: false,\n pendingApprovals: [],\n followUps: [],\n messages: [],\n settled: false\n});\n\n/**\n * Owns the palette's AI conversation.\n *\n * A presenter rather than component state: several pieces change together, a network stream drives\n * them, and an abort has to outlive any one render.\n *\n * Registered as a singleton, so `reset` genuinely clears rather than relying on unmount.\n *\n * The conversation is saved after every run that ends, so it is never more than one turn behind\n * what is on screen. The client saves rather than the stream route, which keeps the route\n * sessionless.\n */\nclass AdminAssistantPresenterImpl implements Abstraction.Interface {\n private turns: Turn[] = [];\n private busy = false;\n private model: string | undefined = undefined;\n private chatId: string | null = null;\n private opening = false;\n private storageError: string | null = null;\n private saveFailure: AiChatSaveFailure | null = null;\n private controller: AbortController | null = null;\n /*\n * Saves run one after another, so the second save of a new chat already has the id the first\n * one got back, rather than creating a second chat.\n */\n private saving: Promise<void> = Promise.resolve();\n /*\n * Bumped whenever the conversation is replaced. A save or an open that finishes after that\n * belongs to a conversation that is gone, and must not write its id onto the new one.\n */\n private generation = 0;\n\n constructor(\n private gateway: AdminAssistantGateway.Interface,\n private chats: AiChatsRepository.Interface\n ) {\n // Machinery, not state anything renders, so keep them out of the map.\n makeAutoObservable<\n AdminAssistantPresenterImpl,\n \"controller\" | \"saving\" | \"generation\" | \"chats\"\n >(this, { controller: false, saving: false, generation: false, chats: false });\n }\n\n get vm(): IAdminAssistantViewModel {\n const vm: IAdminAssistantViewModel = {\n busy: this.busy,\n chatId: this.chatId,\n opening: this.opening,\n storageError: this.storageError,\n saveFailure: this.saveFailure,\n savePaused: this.savePaused,\n setupRequired: this.setupRequired,\n turns: this.turns.map(turn => {\n const view: AiTurnViewModel = {\n question: turn.question,\n text: turn.text,\n answerStart: turn.answerStart,\n tools: turn.tools,\n completed: turn.completed,\n failed: turn.failed,\n running: turn.running,\n pendingApprovals: turn.pendingApprovals,\n followUps: turn.followUps,\n settled: turn.settled,\n needsSetup: turn.errorCode === NOT_CONFIGURED\n };\n\n if (turn.error !== undefined) {\n view.error = turn.error;\n }\n\n return view;\n })\n };\n\n if (this.model !== undefined) {\n vm.model = this.model;\n }\n\n return vm;\n }\n\n ask(question: string): void {\n const trimmed = question.trim();\n\n /*\n * While a saved chat loads, a question would land in a conversation about to be replaced.\n * With no model set up it would fail the same way, so only \"Try again\" asks.\n */\n if (!trimmed || this.busy || this.opening || this.setupRequired) {\n return;\n }\n\n const index = this.turns.length;\n this.addTurn(trimmed);\n\n void this.run(index, {\n messages: [...this.historyBefore(index), { role: \"user\", content: trimmed }]\n });\n }\n\n decide(turnIndex: number, approved: boolean): void {\n const turn = this.turns[turnIndex];\n\n if (!turn?.pendingApprovals.length || this.busy || this.opening) {\n return;\n }\n\n const approvals = turn.pendingApprovals.map(approval => ({\n approvalId: approval.approvalId,\n approved\n }));\n\n /*\n * The paused assistant message must be replayed unchanged: the approval request lives only in\n * the server's messages, so resuming means sending the same history back plus the decision.\n */\n const messages: AdminAssistantMessage[] = [\n ...this.historyBefore(turnIndex),\n { role: \"user\", content: turn.question },\n ...turn.messages\n ];\n\n // Clear the block immediately so the plan cannot be submitted twice.\n this.patch(turnIndex, {\n pendingApprovals: [],\n followUps: [],\n settled: false,\n running: true\n });\n\n void this.run(turnIndex, { messages, approvals }, true);\n }\n\n /*\n * The failed turn is run again in place, from an empty answer. Its history is everything\n * before it, which a failed turn never joins, so the retry asks with the same context.\n */\n retry(): void {\n const index = this.turns.length - 1;\n const turn = this.turns[index];\n\n if (!turn?.error || this.busy || this.opening) {\n return;\n }\n\n const fresh = emptyTurn(turn.question);\n this.replaceTurn(index, { ...fresh, running: true });\n\n const history = this.historyBefore(index);\n void this.run(index, {\n messages: [...history, { role: \"user\", content: turn.question }]\n });\n }\n\n /*\n * While a turn waits on an approval no save can run, so the warning stays until the save after\n * the decision clears it. The view shows `savePaused` instead of a Retry that would do nothing.\n */\n retrySave(): void {\n if (!this.saveFailure || this.savePaused) {\n return;\n }\n this.clearStorageError();\n this.queueSave();\n }\n\n /*\n * A turn waiting on an approval is not saved yet: its paused request has no answer, and\n * replaying it unanswered later would not resume it. The save after the decision covers it.\n */\n private get savePaused(): boolean {\n return this.turns.some(turn => turn.pendingApprovals.length > 0);\n }\n\n private get setupRequired(): boolean {\n const newest = this.turns[this.turns.length - 1];\n return newest?.errorCode === NOT_CONFIGURED;\n }\n\n reset(): void {\n this.controller?.abort();\n this.controller = null;\n this.generation++;\n this.clear();\n }\n\n async open(chatId: string): Promise<void> {\n this.reset();\n const generation = this.generation;\n this.setOpening(true);\n\n try {\n const chat = await this.chats.get(chatId);\n if (generation !== this.generation) {\n return;\n }\n const turns = turnsFromMessages(chat.messages);\n this.setConversation(chat.id, turns);\n } catch (error) {\n if (generation === this.generation) {\n const message = messageOf(error);\n this.setStorageError(message);\n }\n } finally {\n if (generation === this.generation) {\n this.setOpening(false);\n }\n }\n }\n\n // Queued behind any save still in flight. Nothing is saved while `savePaused`.\n private queueSave(): void {\n const messages = this.historyBefore(this.turns.length);\n\n if (this.savePaused || messages.length === 0) {\n return;\n }\n\n const generation = this.generation;\n this.saving = this.saving.then(() => this.save(generation, messages));\n }\n\n private async save(generation: number, messages: AdminAssistantMessage[]): Promise<void> {\n if (generation !== this.generation) {\n return;\n }\n\n try {\n const input: AiChatsRepository.SaveInput = { messages };\n if (this.chatId) {\n input.id = this.chatId;\n }\n\n const summary = await this.chats.save(input);\n if (generation === this.generation) {\n this.setSaved(summary.id);\n }\n } catch (error) {\n if (generation === this.generation) {\n const message = messageOf(error);\n const failure = saveFailureOf(error);\n this.setSaveFailed(message, failure);\n }\n }\n }\n\n /** Replays settled turns so a follow-up (\"and which of those is cheapest?\") has context. */\n private historyBefore(upTo: number): AdminAssistantMessage[] {\n const history: AdminAssistantMessage[] = [];\n\n for (const turn of this.turns.slice(0, upTo)) {\n if (!turn.settled || turn.error) {\n continue;\n }\n history.push({ role: \"user\", content: turn.question });\n history.push(...turn.messages);\n }\n\n return history;\n }\n\n private async run(\n index: number,\n request: AdminAssistantRequest,\n resuming = false\n ): Promise<void> {\n this.controller?.abort();\n const controller = new AbortController();\n this.controller = controller;\n\n this.setBusy(true);\n\n try {\n /*\n * Resuming continues the same turn: the tools already called, the text already shown and\n * the messages already collected all still belong to it. Starting from empty would strand\n * earlier chips as running and, worse, drop the assistant message carrying the `tool_use`\n * that the replayed `tool_result` refers to.\n */\n const existing = resuming ? this.turns[index] : undefined;\n let text = existing?.text ?? \"\";\n const tools: string[] = existing ? [...existing.tools] : [];\n const completed: string[] = existing ? [...existing.completed] : [];\n const failed: string[] = existing ? [...existing.failed] : [];\n const priorMessages: AdminAssistantMessage[] = existing ? [...existing.messages] : [];\n /*\n * A resumed run writes on after the text shown before the approval pause. Without a\n * break, the two ran together (\"...a new folder:Understood, no folder was created.\").\n */\n let separateFromExisting = text.length > 0;\n\n for await (const event of this.gateway.stream(request, controller.signal)) {\n if (event.type === \"start\") {\n this.setModel(event.model);\n continue;\n }\n\n if (event.type === \"text\") {\n text += separateFromExisting ? `\\n\\n${event.text}` : event.text;\n separateFromExisting = false;\n this.patch(index, { text, running: false });\n continue;\n }\n\n if (event.type === \"tool-call\") {\n tools.push(event.name);\n this.patch(index, {\n tools: [...tools],\n running: true,\n answerStart: text.length\n });\n continue;\n }\n\n if (event.type === \"tool-result\") {\n completed.push(event.name);\n this.patch(index, { completed: [...completed] });\n continue;\n }\n\n if (event.type === \"tool-error\") {\n failed.push(event.name);\n this.patch(index, { failed: [...failed] });\n continue;\n }\n\n if (event.type === \"follow-ups\") {\n this.patch(index, { followUps: event.questions });\n continue;\n }\n\n if (event.type === \"approval\") {\n this.patch(index, { pendingApprovals: event.approvals, running: false });\n continue;\n }\n\n if (event.type === \"done\") {\n this.patch(index, {\n messages: [...priorMessages, ...event.messages],\n settled: true,\n running: false\n });\n continue;\n }\n\n if (event.type === \"error\") {\n this.patch(index, {\n error: event.message,\n errorCode: event.code,\n settled: true,\n running: false\n });\n return;\n }\n }\n } catch (error) {\n // An abort is the palette closing, not a failure worth showing.\n if (!controller.signal.aborted) {\n this.patch(index, {\n error: error instanceof Error ? error.message : String(error),\n settled: true,\n running: false\n });\n }\n } finally {\n this.setBusy(false);\n }\n\n // A failed turn is left out of the history, so saving after it would change nothing.\n const turn = this.turns[index];\n if (!controller.signal.aborted && turn?.settled && !turn.error) {\n this.queueSave();\n }\n }\n\n /*\n * Every mutation below is its own method on purpose. `run` awaits, and a mutation after an await\n * has escaped the action it started in; `makeAutoObservable` makes these methods actions, so\n * calling them from there is correct.\n */\n private addTurn(question: string): void {\n this.turns = [...this.turns, { ...emptyTurn(question), running: true }];\n }\n\n private replaceTurn(index: number, turn: Turn): void {\n this.turns = this.turns.map((existing, i) => (i === index ? turn : existing));\n }\n\n private patch(index: number, change: Partial<Turn>): void {\n this.turns = this.turns.map((turn, i) => (i === index ? { ...turn, ...change } : turn));\n }\n\n private setBusy(busy: boolean): void {\n this.busy = busy;\n }\n\n private setModel(model: string): void {\n this.model = model;\n }\n\n private setOpening(opening: boolean): void {\n this.opening = opening;\n }\n\n private setConversation(chatId: string, turns: Turn[]): void {\n this.chatId = chatId;\n this.turns = turns;\n }\n\n private setSaved(chatId: string): void {\n this.chatId = chatId;\n this.storageError = null;\n this.saveFailure = null;\n }\n\n private setStorageError(message: string): void {\n this.storageError = message;\n this.saveFailure = null;\n }\n\n private setSaveFailed(message: string, failure: AiChatSaveFailure): void {\n this.storageError = message;\n this.saveFailure = failure;\n }\n\n private clearStorageError(): void {\n this.storageError = null;\n this.saveFailure = null;\n }\n\n private clear(): void {\n this.turns = [];\n this.busy = false;\n this.chatId = null;\n this.opening = false;\n this.storageError = null;\n this.saveFailure = null;\n }\n}\n\nexport const AdminAssistantPresenter = Abstraction.createImplementation({\n implementation: AdminAssistantPresenterImpl,\n dependencies: [AdminAssistantGateway, AiChatsRepository]\n});\n"],"names":["NOT_CONFIGURED","saveFailureOf","error","AiChatSaveError","emptyTurn","question","AdminAssistantPresenterImpl","gateway","chats","undefined","Promise","makeAutoObservable","vm","turn","view","trimmed","index","turnIndex","approved","approvals","approval","messages","fresh","history","newest","chatId","generation","chat","turns","turnsFromMessages","message","messageOf","input","summary","failure","upTo","request","resuming","controller","AbortController","existing","text","tools","completed","failed","priorMessages","separateFromExisting","event","Error","String","i","change","busy","model","opening","AdminAssistantPresenter","Abstraction","AdminAssistantGateway","AiChatsRepository"],"mappings":";;;;;;AAuBA,MAAMA,iBAAiB;AAGvB,MAAMC,gBAAgB,CAACC,QACZA,iBAAiBC,kBAAkBD,MAAM,OAAO,GAAG;AAG9D,MAAME,YAAY,CAACC,WAA4B;QAC3CA;QACA,MAAM;QACN,aAAa;QACb,OAAO,EAAE;QACT,WAAW,EAAE;QACb,QAAQ,EAAE;QACV,SAAS;QACT,kBAAkB,EAAE;QACpB,WAAW,EAAE;QACb,UAAU,EAAE;QACZ,SAAS;IACb;AAcA,MAAMC;IAoBF,YACYC,OAAwC,EACxCC,KAAkC,CAC5C;aAFUD,OAAO,GAAPA;aACAC,KAAK,GAALA;aArBJ,KAAK,GAAW,EAAE;aAClB,IAAI,GAAG;aACP,KAAK,GAAuBC;aAC5B,MAAM,GAAkB;aACxB,OAAO,GAAG;aACV,YAAY,GAAkB;aAC9B,WAAW,GAA6B;aACxC,UAAU,GAA2B;QAI5C,KACO,MAAM,GAAkBC,QAAQ,OAAO;QAI9C,KACO,UAAU,GAAG;QAOjBC,mBAGE,IAAI,EAAE;YAAE,YAAY;YAAO,QAAQ;YAAO,YAAY;YAAO,OAAO;QAAM;IAChF;IAEA,IAAI,KAA+B;QAC/B,MAAMC,KAA+B;YACjC,MAAM,IAAI,CAAC,IAAI;YACf,QAAQ,IAAI,CAAC,MAAM;YACnB,SAAS,IAAI,CAAC,OAAO;YACrB,cAAc,IAAI,CAAC,YAAY;YAC/B,aAAa,IAAI,CAAC,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
{"version":3,"file":"features/adminAssistant/AdminAssistantPresenter.js","sources":["../../../src/features/adminAssistant/AdminAssistantPresenter.ts"],"sourcesContent":["import { makeAutoObservable } from \"mobx\";\nimport { AdminAssistantGateway } from \"./abstractions.js\";\nimport type { AdminAssistantRequest } from \"./abstractions.js\";\nimport { AdminAssistantPresenter as Abstraction } from \"./abstractions.js\";\nimport type { AiTurnViewModel } from \"./abstractions.js\";\nimport { AiChatsRepository } from \"~/features/aiChats/abstractions.js\";\nimport type { AiChatSaveFailure } from \"~/features/aiChats/abstractions.js\";\nimport { messageOf } from \"~/features/aiChats/messageOf.js\";\nimport { turnsFromMessages } from \"./turnsFromMessages.js\";\n\n/** A turn plus the state the view never sees. `needsSetup` is derived from `errorCode`. */\ninterface Turn extends Omit<AiTurnViewModel, \"needsSetup\"> {\n /** The server's code for the failure, when it sent one. */\n errorCode?: string;\n}\n\n/** The code a run fails with when the project's AI settings give the assistant no model. */\nconst NOT_CONFIGURED = \"AI_CAPABILITY_NOT_CONFIGURED\";\n\nconst emptyTurn = (question: string): Turn => ({\n question,\n text: \"\",\n answerStart: 0,\n tools: [],\n completed: [],\n failed: [],\n running: false,\n pendingApprovals: [],\n followUps: [],\n settled: false\n});\n\n/**\n * Owns the palette's AI conversation.\n *\n * A presenter rather than component state: several pieces change together, a network stream drives\n * them, and an abort has to outlive any one render.\n *\n * Registered as a singleton, so `reset` genuinely clears rather than relying on unmount.\n *\n * The server keeps the conversation: a question sends only the chat id and the question, and the\n * assistant reads the history from the saved chat and saves the run when it ends. The turns here\n * are what is shown, never what is sent.\n */\nclass AdminAssistantPresenterImpl implements Abstraction.Interface {\n private turns: Turn[] = [];\n private busy = false;\n private model: string | undefined = undefined;\n private chatId: string | null = null;\n private opening = false;\n private storageError: string | null = null;\n private saveFailure: AiChatSaveFailure | null = null;\n private controller: AbortController | null = null;\n /*\n * Bumped whenever the conversation is replaced. An open that finishes after that belongs to a\n * conversation that is gone, and must not write its turns onto the new one.\n */\n private generation = 0;\n\n constructor(\n private gateway: AdminAssistantGateway.Interface,\n private chats: AiChatsRepository.Interface\n ) {\n // Machinery, not state anything renders, so keep them out of the map.\n makeAutoObservable<AdminAssistantPresenterImpl, \"controller\" | \"generation\" | \"chats\">(\n this,\n { controller: false, generation: false, chats: false }\n );\n }\n\n get vm(): Abstraction.ViewModel {\n const vm: Abstraction.ViewModel = {\n busy: this.busy,\n chatId: this.chatId,\n opening: this.opening,\n storageError: this.storageError,\n saveFailure: this.saveFailure,\n setupRequired: this.setupRequired,\n turns: this.turns.map(turn => {\n const view: AiTurnViewModel = {\n question: turn.question,\n text: turn.text,\n answerStart: turn.answerStart,\n tools: turn.tools,\n completed: turn.completed,\n failed: turn.failed,\n running: turn.running,\n pendingApprovals: turn.pendingApprovals,\n followUps: turn.followUps,\n settled: turn.settled,\n needsSetup: turn.errorCode === NOT_CONFIGURED\n };\n\n if (turn.error !== undefined) {\n view.error = turn.error;\n }\n\n return view;\n })\n };\n\n if (this.model !== undefined) {\n vm.model = this.model;\n }\n\n return vm;\n }\n\n ask(question: string): void {\n const trimmed = question.trim();\n\n /*\n * While a saved chat loads, a question would land in a conversation about to be replaced.\n * With no model set up it would fail the same way, so only \"Try again\" asks.\n */\n if (!trimmed || this.busy || this.opening || this.setupRequired) {\n return;\n }\n\n // Asking something else rejects a change still waiting; the server does the same.\n this.dropPendingApprovals();\n this.clearStorageError();\n\n const index = this.turns.length;\n this.addTurn(trimmed);\n const request = this.request({ prompt: trimmed });\n void this.run(index, request);\n }\n\n decide(turnIndex: number, approved: boolean): void {\n const turn = this.turns[turnIndex];\n\n if (!turn?.pendingApprovals.length || this.busy || this.opening) {\n return;\n }\n\n // The paused run is resumed from the saved chat, so a run that was not saved cannot be.\n if (!this.chatId || this.saveFailure) {\n this.patch(turnIndex, {\n pendingApprovals: [],\n error: \"This change can't run because the chat wasn't saved. Ask again to retry.\"\n });\n return;\n }\n\n const approvals = turn.pendingApprovals.map(approval => ({\n approvalId: approval.approvalId,\n approved\n }));\n\n // Clear the block immediately so the plan cannot be submitted twice.\n this.patch(turnIndex, {\n pendingApprovals: [],\n followUps: [],\n settled: false,\n running: true\n });\n\n const request = this.request({ approvals });\n void this.run(turnIndex, request, true);\n }\n\n /*\n * The newest turn asked again in place, from an empty answer: one that failed, or one that ran\n * but was not saved. Either way the saved chat does not have it, so the server answers it again\n * with the same history it had the first time.\n */\n retry(): void {\n const index = this.turns.length - 1;\n const turn = this.turns[index];\n\n if (!turn || this.busy || this.opening) {\n return;\n }\n // A run that cannot be saved by asking again is left for a new chat.\n if (!turn.error && this.saveFailure !== \"retryable\") {\n return;\n }\n\n this.clearStorageError();\n const fresh = emptyTurn(turn.question);\n this.replaceTurn(index, { ...fresh, running: true });\n const request = this.request({ prompt: turn.question });\n void this.run(index, request);\n }\n\n private get setupRequired(): boolean {\n const newest = this.turns[this.turns.length - 1];\n return newest?.errorCode === NOT_CONFIGURED;\n }\n\n reset(): void {\n this.controller?.abort();\n this.controller = null;\n this.generation++;\n this.clear();\n }\n\n async open(chatId: string): Promise<void> {\n this.reset();\n const generation = this.generation;\n this.setOpening(true);\n\n try {\n const chat = await this.chats.get(chatId);\n if (generation !== this.generation) {\n return;\n }\n const turns = turnsFromMessages(chat.messages);\n this.setConversation(chat.id, turns);\n } catch (error) {\n if (generation === this.generation) {\n const message = messageOf(error);\n this.setStorageError(message);\n }\n } finally {\n if (generation === this.generation) {\n this.setOpening(false);\n }\n }\n }\n\n /** A request for the chat on screen: the server reads its history from the saved chat. */\n private request(rest: Omit<AdminAssistantRequest, \"chatId\">): AdminAssistantRequest {\n const request: AdminAssistantRequest = { ...rest };\n if (this.chatId) {\n request.chatId = this.chatId;\n }\n return request;\n }\n\n private async run(\n index: number,\n request: AdminAssistantRequest,\n resuming = false\n ): Promise<void> {\n this.controller?.abort();\n const controller = new AbortController();\n this.controller = controller;\n\n this.setBusy(true);\n\n try {\n /*\n * Resuming continues the same turn: the tools already called, the text already shown and\n * the messages already collected all still belong to it. Starting from empty would strand\n * earlier chips as running and, worse, drop the assistant message carrying the `tool_use`\n * that the replayed `tool_result` refers to.\n */\n const existing = resuming ? this.turns[index] : undefined;\n let text = existing?.text ?? \"\";\n const tools: string[] = existing ? [...existing.tools] : [];\n const completed: string[] = existing ? [...existing.completed] : [];\n const failed: string[] = existing ? [...existing.failed] : [];\n /*\n * A resumed run writes on after the text shown before the approval pause. Without a\n * break, the two ran together (\"...a new folder:Understood, no folder was created.\").\n */\n let separateFromExisting = text.length > 0;\n\n for await (const event of this.gateway.stream(request, controller.signal)) {\n if (event.type === \"start\") {\n this.setModel(event.model);\n continue;\n }\n\n if (event.type === \"text\") {\n text += separateFromExisting ? `\\n\\n${event.text}` : event.text;\n separateFromExisting = false;\n this.patch(index, { text, running: false });\n continue;\n }\n\n if (event.type === \"tool-call\") {\n tools.push(event.name);\n this.patch(index, {\n tools: [...tools],\n running: true,\n answerStart: text.length\n });\n continue;\n }\n\n if (event.type === \"tool-result\") {\n completed.push(event.name);\n this.patch(index, { completed: [...completed] });\n continue;\n }\n\n if (event.type === \"tool-error\") {\n failed.push(event.name);\n this.patch(index, { failed: [...failed] });\n continue;\n }\n\n if (event.type === \"follow-ups\") {\n this.patch(index, { followUps: event.questions });\n continue;\n }\n\n if (event.type === \"approval\") {\n this.patch(index, { pendingApprovals: event.approvals, running: false });\n continue;\n }\n\n if (event.type === \"saved\") {\n this.setSaved(event.chat);\n continue;\n }\n\n /*\n * A resumed run may have carried out the change the user approved. Asking again\n * would start before that change, so the model proposes it again and approving\n * twice makes it twice. Only a new chat is offered then.\n */\n if (event.type === \"not-saved\") {\n const failure = event.retryable && !resuming ? \"retryable\" : \"final\";\n this.setSaveFailed(event.message, failure);\n continue;\n }\n\n if (event.type === \"done\") {\n this.patch(index, { settled: true, running: false });\n continue;\n }\n\n if (event.type === \"error\") {\n this.patch(index, {\n error: event.message,\n errorCode: event.code,\n settled: true,\n running: false\n });\n return;\n }\n }\n } catch (error) {\n // An abort is the palette closing, not a failure worth showing.\n if (!controller.signal.aborted) {\n this.patch(index, {\n error: error instanceof Error ? error.message : String(error),\n settled: true,\n running: false\n });\n }\n } finally {\n this.setBusy(false);\n }\n }\n\n /*\n * Every mutation below is its own method on purpose. `run` awaits, and a mutation after an await\n * has escaped the action it started in; `makeAutoObservable` makes these methods actions, so\n * calling them from there is correct.\n */\n private addTurn(question: string): void {\n this.turns = [...this.turns, { ...emptyTurn(question), running: true }];\n }\n\n private replaceTurn(index: number, turn: Turn): void {\n this.turns = this.turns.map((existing, i) => (i === index ? turn : existing));\n }\n\n private patch(index: number, change: Partial<Turn>): void {\n this.turns = this.turns.map((turn, i) => (i === index ? { ...turn, ...change } : turn));\n }\n\n private setBusy(busy: boolean): void {\n this.busy = busy;\n }\n\n private setModel(model: string): void {\n this.model = model;\n }\n\n private setOpening(opening: boolean): void {\n this.opening = opening;\n }\n\n private setConversation(chatId: string, turns: Turn[]): void {\n this.chatId = chatId;\n this.turns = turns;\n }\n\n // The chats list learns of the chat from here, so it shows up without being read again.\n private setSaved(chat: AiChatsRepository.Summary): void {\n this.chatId = chat.id;\n this.storageError = null;\n this.saveFailure = null;\n this.chats.remember(chat);\n }\n\n private dropPendingApprovals(): void {\n this.turns = this.turns.map(turn => {\n if (turn.pendingApprovals.length === 0) {\n return turn;\n }\n return { ...turn, pendingApprovals: [] };\n });\n }\n\n private setStorageError(message: string): void {\n this.storageError = message;\n this.saveFailure = null;\n }\n\n private setSaveFailed(message: string, failure: AiChatSaveFailure): void {\n this.storageError = message;\n this.saveFailure = failure;\n }\n\n private clearStorageError(): void {\n this.storageError = null;\n this.saveFailure = null;\n }\n\n private clear(): void {\n this.turns = [];\n this.busy = false;\n this.chatId = null;\n this.opening = false;\n this.storageError = null;\n this.saveFailure = null;\n }\n}\n\nexport const AdminAssistantPresenter = Abstraction.createImplementation({\n implementation: AdminAssistantPresenterImpl,\n dependencies: [AdminAssistantGateway, AiChatsRepository]\n});\n"],"names":["NOT_CONFIGURED","emptyTurn","question","AdminAssistantPresenterImpl","gateway","chats","undefined","makeAutoObservable","vm","turn","view","trimmed","index","request","turnIndex","approved","approvals","approval","fresh","newest","chatId","generation","chat","turns","turnsFromMessages","error","message","messageOf","rest","resuming","controller","AbortController","existing","text","tools","completed","failed","separateFromExisting","event","failure","Error","String","i","change","busy","model","opening","AdminAssistantPresenter","Abstraction","AdminAssistantGateway","AiChatsRepository"],"mappings":";;;;;AAiBA,MAAMA,iBAAiB;AAEvB,MAAMC,YAAY,CAACC,WAA4B;QAC3CA;QACA,MAAM;QACN,aAAa;QACb,OAAO,EAAE;QACT,WAAW,EAAE;QACb,QAAQ,EAAE;QACV,SAAS;QACT,kBAAkB,EAAE;QACpB,WAAW,EAAE;QACb,SAAS;IACb;AAcA,MAAMC;IAeF,YACYC,OAAwC,EACxCC,KAAkC,CAC5C;aAFUD,OAAO,GAAPA;aACAC,KAAK,GAALA;aAhBJ,KAAK,GAAW,EAAE;aAClB,IAAI,GAAG;aACP,KAAK,GAAuBC;aAC5B,MAAM,GAAkB;aACxB,OAAO,GAAG;aACV,YAAY,GAAkB;aAC9B,WAAW,GAA6B;aACxC,UAAU,GAA2B;QAI5C,KACO,UAAU,GAAG;QAOjBC,mBACI,IAAI,EACJ;YAAE,YAAY;YAAO,YAAY;YAAO,OAAO;QAAM;IAE7D;IAEA,IAAI,KAA4B;QAC5B,MAAMC,KAA4B;YAC9B,MAAM,IAAI,CAAC,IAAI;YACf,QAAQ,IAAI,CAAC,MAAM;YACnB,SAAS,IAAI,CAAC,OAAO;YACrB,cAAc,IAAI,CAAC,YAAY;YAC/B,aAAa,IAAI,CAAC,WAAW;YAC7B,eAAe,IAAI,CAAC,aAAa;YACjC,OAAO,IAAI,CAAC,KAAK,CAAC,GAAG,CAACC,CAAAA;gBAClB,MAAMC,OAAwB;oBAC1B,UAAUD,KAAK,QAAQ;oBACvB,MAAMA,KAAK,IAAI;oBACf,aAAaA,KAAK,WAAW;oBAC7B,OAAOA,KAAK,KAAK;oBACjB,WAAWA,KAAK,SAA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,oBAAgC,CAAC;IACpE,gBAAgB7C;IAChB,cAAc;QAAC8C;QAAuBC;KAAkB;AAC5D"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import type { AiChatSaveFailure } from "../../features/aiChats/abstractions.js";
|
|
2
|
+
import type { AiChatsRepository } from "../../features/aiChats/abstractions.js";
|
|
2
3
|
/**
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
* agent loop to resume — the request exists nowhere else, since the server keeps no session.
|
|
4
|
+
* A message of a saved chat. Opaque on purpose: the admin only reads them to show an opened chat,
|
|
5
|
+
* and the server is the one that sends them to the model.
|
|
6
6
|
*/
|
|
7
7
|
export type AdminAssistantMessage = {
|
|
8
8
|
role: string;
|
|
@@ -27,9 +27,14 @@ export interface AdminAssistantDecision {
|
|
|
27
27
|
approved: boolean;
|
|
28
28
|
reason?: string;
|
|
29
29
|
}
|
|
30
|
+
/**
|
|
31
|
+
* A question, or the decisions on the calls a run paused on. The server reads the rest of the
|
|
32
|
+
* conversation from the saved chat, so only its id is sent; without one, a question starts a chat.
|
|
33
|
+
*/
|
|
30
34
|
export interface AdminAssistantRequest {
|
|
31
|
-
|
|
32
|
-
|
|
35
|
+
chatId?: string;
|
|
36
|
+
prompt?: string;
|
|
37
|
+
/** Approve or reject calls the server paused on. Needs the `chatId` of the paused run. */
|
|
33
38
|
approvals?: AdminAssistantDecision[];
|
|
34
39
|
}
|
|
35
40
|
/**
|
|
@@ -58,9 +63,15 @@ export type AdminAssistantStreamEvent = {
|
|
|
58
63
|
} | {
|
|
59
64
|
type: "approval";
|
|
60
65
|
approvals: AdminAssistantPendingApproval[];
|
|
66
|
+
} | {
|
|
67
|
+
type: "saved";
|
|
68
|
+
chat: AiChatsRepository.Summary;
|
|
69
|
+
} | {
|
|
70
|
+
type: "not-saved";
|
|
71
|
+
message: string;
|
|
72
|
+
retryable: boolean;
|
|
61
73
|
} | {
|
|
62
74
|
type: "done";
|
|
63
|
-
messages: AdminAssistantMessage[];
|
|
64
75
|
steps: number;
|
|
65
76
|
} | {
|
|
66
77
|
type: "error";
|
|
@@ -85,12 +96,7 @@ export declare namespace AdminAssistantGateway {
|
|
|
85
96
|
type Request = AdminAssistantRequest;
|
|
86
97
|
type StreamEvent = AdminAssistantStreamEvent;
|
|
87
98
|
}
|
|
88
|
-
/**
|
|
89
|
-
* One question and the answer to it, as the view needs it.
|
|
90
|
-
*
|
|
91
|
-
* The server messages that make a follow-up or a resumed approval work are deliberately absent: they
|
|
92
|
-
* are conversation state, not something rendered, so they stay inside the presenter.
|
|
93
|
-
*/
|
|
99
|
+
/** One question and the answer to it, as the view needs it. */
|
|
94
100
|
export interface AiTurnViewModel {
|
|
95
101
|
question: string;
|
|
96
102
|
/** Answer text so far. Grows as the stream arrives. */
|
|
@@ -136,17 +142,15 @@ export interface IAdminAssistantViewModel {
|
|
|
136
142
|
/** A saved chat is being read. */
|
|
137
143
|
opening: boolean;
|
|
138
144
|
/**
|
|
139
|
-
* Why the last
|
|
140
|
-
* only so the view can say it is not saved.
|
|
145
|
+
* Why the last run was not saved, or the last open failed. The conversation on screen carries
|
|
146
|
+
* on either way; this is only so the view can say it is not saved.
|
|
141
147
|
*/
|
|
142
148
|
storageError: string | null;
|
|
143
|
-
/** Set when it was a save that failed, so the view can offer what fixes it. Null for an open. */
|
|
144
|
-
saveFailure: AiChatSaveFailure | null;
|
|
145
149
|
/**
|
|
146
|
-
*
|
|
147
|
-
*
|
|
150
|
+
* Set when it was a run that was not saved, so the view can offer what fixes it. Null for an
|
|
151
|
+
* open.
|
|
148
152
|
*/
|
|
149
|
-
|
|
153
|
+
saveFailure: AiChatSaveFailure | null;
|
|
150
154
|
/**
|
|
151
155
|
* The newest turn needs a model set up first. No question is taken until "Try again" (`retry`)
|
|
152
156
|
* succeeds, so the view can stop taking input.
|
|
@@ -155,7 +159,10 @@ export interface IAdminAssistantViewModel {
|
|
|
155
159
|
}
|
|
156
160
|
export interface IAdminAssistantPresenter {
|
|
157
161
|
readonly vm: IAdminAssistantViewModel;
|
|
158
|
-
/**
|
|
162
|
+
/**
|
|
163
|
+
* Ask a question in the chat on screen. A change still waiting on a decision is rejected.
|
|
164
|
+
* Refused while `setupRequired`.
|
|
165
|
+
*/
|
|
159
166
|
ask(question: string): void;
|
|
160
167
|
/** Approve or reject the calls a turn paused on, then resume it. */
|
|
161
168
|
decide(turnIndex: number, approved: boolean): void;
|
|
@@ -163,10 +170,8 @@ export interface IAdminAssistantPresenter {
|
|
|
163
170
|
reset(): void;
|
|
164
171
|
/** Replace the conversation with a saved chat, so asking again continues it. */
|
|
165
172
|
open(chatId: string): Promise<void>;
|
|
166
|
-
/** Ask the newest question again, when its run failed. */
|
|
173
|
+
/** Ask the newest question again, when its run failed or was not saved. */
|
|
167
174
|
retry(): void;
|
|
168
|
-
/** Try the failed save again. */
|
|
169
|
-
retrySave(): void;
|
|
170
175
|
}
|
|
171
176
|
export declare const AdminAssistantPresenter: import("@webiny/di").Abstraction<IAdminAssistantPresenter>;
|
|
172
177
|
export declare namespace AdminAssistantPresenter {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"features/adminAssistant/abstractions.js","sources":["../../../src/features/adminAssistant/abstractions.ts"],"sourcesContent":["import { createAbstraction } from \"@webiny/feature/admin\";\nimport type { AiChatSaveFailure } from \"~/features/aiChats/abstractions.js\";\n\n/**\n *
|
|
1
|
+
{"version":3,"file":"features/adminAssistant/abstractions.js","sources":["../../../src/features/adminAssistant/abstractions.ts"],"sourcesContent":["import { createAbstraction } from \"@webiny/feature/admin\";\nimport type { AiChatSaveFailure } from \"~/features/aiChats/abstractions.js\";\nimport type { AiChatsRepository } from \"~/features/aiChats/abstractions.js\";\n\n/**\n * A message of a saved chat. Opaque on purpose: the admin only reads them to show an opened chat,\n * and the server is the one that sends them to the model.\n */\nexport type AdminAssistantMessage = { role: string; content: unknown };\n\n/** A tool the assistant invoked, so the UI can show its work rather than just an answer. */\nexport interface AdminAssistantToolCall {\n name: string;\n input: unknown;\n}\n\n/** A tool call the assistant wants to make but has not made, because it changes something. */\nexport interface AdminAssistantPendingApproval {\n approvalId: string;\n toolName: string;\n title?: string;\n input: unknown;\n /** The tool declared itself destructive — the UI should say so more loudly. */\n destructive: boolean;\n}\n\nexport interface AdminAssistantDecision {\n approvalId: string;\n approved: boolean;\n reason?: string;\n}\n\n/**\n * A question, or the decisions on the calls a run paused on. The server reads the rest of the\n * conversation from the saved chat, so only its id is sent; without one, a question starts a chat.\n */\nexport interface AdminAssistantRequest {\n chatId?: string;\n prompt?: string;\n /** Approve or reject calls the server paused on. Needs the `chatId` of the paused run. */\n approvals?: AdminAssistantDecision[];\n}\n\n/**\n * What the assistant emits while it works. Mirrors the server's `AdminAssistantEvent`; declared here so the\n * admin bundle carries no server or AI SDK code.\n */\nexport type AdminAssistantStreamEvent =\n // The run is going ahead, on this model (\"anthropic/claude-sonnet-4-5\").\n | { type: \"start\"; model: string }\n | { type: \"text\"; text: string }\n | { type: \"tool-call\"; name: string }\n | { type: \"tool-result\"; name: string }\n // A tool threw. Pairs with `tool-call` by name, and does not end the run.\n | { type: \"tool-error\"; name: string; message: string }\n | { type: \"follow-ups\"; questions: string[] }\n | { type: \"approval\"; approvals: AdminAssistantPendingApproval[] }\n // The run was saved, as a new chat or onto the one asked about.\n | { type: \"saved\"; chat: AiChatsRepository.Summary }\n // The run finished but the server could not save it. `retryable` says whether asking again could.\n | { type: \"not-saved\"; message: string; retryable: boolean }\n // Comes after `saved` or `not-saved`.\n | { type: \"done\"; steps: number }\n | { type: \"error\"; message: string; code?: \"AI_CAPABILITY_NOT_CONFIGURED\" };\n\nexport interface IAdminAssistantGateway {\n /**\n * Run and yield progress as it arrives. Preferred in the UI: a multi-tool question takes tens of\n * seconds, and an approval request is worth showing the moment it appears.\n */\n stream(\n request: AdminAssistantRequest,\n signal?: AbortSignal\n ): AsyncIterable<AdminAssistantStreamEvent>;\n}\n\n/** Sends a question to the server-side AI assistant (`POST /ai/chat`). */\nexport const AdminAssistantGateway =\n createAbstraction<IAdminAssistantGateway>(\"AdminAssistantGateway\");\n\nexport namespace AdminAssistantGateway {\n export type Interface = IAdminAssistantGateway;\n export type Message = AdminAssistantMessage;\n export type ToolCall = AdminAssistantToolCall;\n export type PendingApproval = AdminAssistantPendingApproval;\n export type Decision = AdminAssistantDecision;\n export type Request = AdminAssistantRequest;\n export type StreamEvent = AdminAssistantStreamEvent;\n}\n\n/** One question and the answer to it, as the view needs it. */\nexport interface AiTurnViewModel {\n question: string;\n /** Answer text so far. Grows as the stream arrives. */\n text: string;\n /**\n * Where the answer proper starts in `text`: after the last tool call. Text before it is the\n * model saying what it is about to look up, which is no summary of the answer.\n */\n answerStart: number;\n /** Tools called this turn, in call order. */\n tools: string[];\n /**\n * Tools that returned. A call pending approval still emits `tool-call`, so this is the only way\n * to tell a completed tool from one merely proposed.\n */\n completed: string[];\n /** Tools that threw. Settles the chip as a failure; the run continues. */\n failed: string[];\n /** Set while a tool is running and no answer text has arrived yet. */\n running: boolean;\n pendingApprovals: AdminAssistantPendingApproval[];\n /** Questions the assistant suggests asking next. Empty until the answer is in. */\n followUps: string[];\n settled: boolean;\n error?: string;\n /**\n * The turn failed because the project has no model set up. Shown as a setup screen rather\n * than an error; `error` holds the server's reason, which names the setting to fix.\n */\n needsSetup: boolean;\n}\n\nexport interface IAdminAssistantViewModel {\n turns: AiTurnViewModel[];\n /** A run is in flight. Asking again or deciding again is refused while true. */\n busy: boolean;\n /**\n * The model the last run used, fully qualified. Absent before the first run, since the admin\n * only learns it from the server.\n */\n model?: string;\n /** The saved chat this conversation is, once its first turn is saved or a chat is opened. */\n chatId: string | null;\n /** A saved chat is being read. */\n opening: boolean;\n /**\n * Why the last run was not saved, or the last open failed. The conversation on screen carries\n * on either way; this is only so the view can say it is not saved.\n */\n storageError: string | null;\n /**\n * Set when it was a run that was not saved, so the view can offer what fixes it. Null for an\n * open.\n */\n saveFailure: AiChatSaveFailure | null;\n /**\n * The newest turn needs a model set up first. No question is taken until \"Try again\" (`retry`)\n * succeeds, so the view can stop taking input.\n */\n setupRequired: boolean;\n}\n\nexport interface IAdminAssistantPresenter {\n readonly vm: IAdminAssistantViewModel;\n /**\n * Ask a question in the chat on screen. A change still waiting on a decision is rejected.\n * Refused while `setupRequired`.\n */\n ask(question: string): void;\n /** Approve or reject the calls a turn paused on, then resume it. */\n decide(turnIndex: number, approved: boolean): void;\n /** Drop the conversation and stop anything in flight. The saved chat is kept. */\n reset(): void;\n /** Replace the conversation with a saved chat, so asking again continues it. */\n open(chatId: string): Promise<void>;\n /** Ask the newest question again, when its run failed or was not saved. */\n retry(): void;\n}\n\nexport const AdminAssistantPresenter =\n createAbstraction<IAdminAssistantPresenter>(\"AdminAssistantPresenter\");\n\nexport namespace AdminAssistantPresenter {\n export type Interface = IAdminAssistantPresenter;\n export type ViewModel = IAdminAssistantViewModel;\n export type Turn = AiTurnViewModel;\n}\n"],"names":["AdminAssistantGateway","createAbstraction","AdminAssistantPresenter"],"mappings":";AA6EO,MAAMA,wBACTC,kBAA0C;AA4FvC,MAAMC,0BACTD,kBAA4C"}
|
|
@@ -1,15 +1,12 @@
|
|
|
1
1
|
import type { AdminAssistantMessage } from "./abstractions.js";
|
|
2
2
|
import type { AiTurnViewModel } from "./abstractions.js";
|
|
3
|
-
/** A rebuilt turn
|
|
4
|
-
export
|
|
5
|
-
messages: AdminAssistantMessage[];
|
|
6
|
-
}
|
|
3
|
+
/** A rebuilt turn. The server keeps the messages, so carrying on needs none of them here. */
|
|
4
|
+
export type RestoredTurn = Omit<AiTurnViewModel, "needsSetup">;
|
|
7
5
|
/**
|
|
8
6
|
* Turns a saved conversation back into the turns the palette shows.
|
|
9
7
|
*
|
|
10
8
|
* The inverse of how the assistant replays a conversation: every user message starts a turn, and
|
|
11
|
-
* the assistant and tool messages after it are that turn's
|
|
12
|
-
*
|
|
13
|
-
* reopened chat offers the same ones it ended with.
|
|
9
|
+
* the assistant and tool messages after it are that turn's. The follow-up questions come from the
|
|
10
|
+
* call that suggested them, so a reopened chat offers the same ones it ended with.
|
|
14
11
|
*/
|
|
15
12
|
export declare const turnsFromMessages: (messages: AdminAssistantMessage[]) => RestoredTurn[];
|
|
@@ -31,11 +31,9 @@ const startTurn = (question)=>({
|
|
|
31
31
|
running: false,
|
|
32
32
|
pendingApprovals: [],
|
|
33
33
|
followUps: [],
|
|
34
|
-
messages: [],
|
|
35
34
|
settled: true
|
|
36
35
|
});
|
|
37
36
|
const addToTurn = (turn, message)=>{
|
|
38
|
-
turn.messages.push(message);
|
|
39
37
|
if ("assistant" === message.role) {
|
|
40
38
|
const text = textOf(message);
|
|
41
39
|
if (text) turn.text = turn.text ? `${turn.text}\n\n${text}` : text;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"features/adminAssistant/turnsFromMessages.js","sources":["../../../src/features/adminAssistant/turnsFromMessages.ts"],"sourcesContent":["import type { AdminAssistantMessage } from \"./abstractions.js\";\nimport type { AiTurnViewModel } from \"./abstractions.js\";\n\n/** A rebuilt turn
|
|
1
|
+
{"version":3,"file":"features/adminAssistant/turnsFromMessages.js","sources":["../../../src/features/adminAssistant/turnsFromMessages.ts"],"sourcesContent":["import type { AdminAssistantMessage } from \"./abstractions.js\";\nimport type { AiTurnViewModel } from \"./abstractions.js\";\n\n/** A rebuilt turn. The server keeps the messages, so carrying on needs none of them here. */\nexport type RestoredTurn = Omit<AiTurnViewModel, \"needsSetup\">;\n\ninterface Part {\n type?: unknown;\n text?: unknown;\n toolName?: unknown;\n input?: { questions?: unknown };\n output?: { type?: unknown };\n}\n\n/*\n * The tool the server's assistant calls to hand over follow-up questions. It is how the answer\n * ends, not work the user asked for, so the live stream never reports it as a tool, and neither does\n * a reopened chat. Mirrors `FOLLOW_UPS_TOOL` in `@webiny/ai-powerups`, which the admin cannot import.\n */\nconst FOLLOW_UPS_TOOL = \"suggestFollowUps\";\nconst MAX_FOLLOW_UPS = 3;\n\nconst followUpsOf = (part: Part): string[] => {\n const questions = part.input?.questions;\n if (!Array.isArray(questions)) {\n return [];\n }\n\n const result: string[] = [];\n for (const question of questions) {\n if (typeof question === \"string\" && question.trim()) {\n result.push(question.trim());\n }\n }\n return result.slice(0, MAX_FOLLOW_UPS);\n};\n\nconst partsOf = (message: AdminAssistantMessage): Part[] => {\n if (!Array.isArray(message.content)) {\n return [];\n }\n return message.content.filter(\n (part): part is Part => typeof part === \"object\" && part !== null\n );\n};\n\nconst textOf = (message: AdminAssistantMessage): string => {\n if (typeof message.content === \"string\") {\n return message.content;\n }\n\n const texts: string[] = [];\n for (const part of partsOf(message)) {\n if (part.type === \"text\" && typeof part.text === \"string\") {\n texts.push(part.text);\n }\n }\n return texts.join(\"\");\n};\n\nconst FAILED_OUTPUTS = new Set([\"error-text\", \"error-json\"]);\n\nconst startTurn = (question: string): RestoredTurn => ({\n question,\n text: \"\",\n answerStart: 0,\n tools: [],\n completed: [],\n failed: [],\n running: false,\n pendingApprovals: [],\n followUps: [],\n settled: true\n});\n\n/** Reads what an assistant or tool message adds to the turn it belongs to. */\nconst addToTurn = (turn: RestoredTurn, message: AdminAssistantMessage): void => {\n if (message.role === \"assistant\") {\n // Each assistant message is a step. Steps were streamed as one answer, a paragraph apart.\n const text = textOf(message);\n if (text) {\n turn.text = turn.text ? `${turn.text}\\n\\n${text}` : text;\n }\n\n for (const part of partsOf(message)) {\n if (part.type !== \"tool-call\" || typeof part.toolName !== \"string\") {\n continue;\n }\n if (part.toolName === FOLLOW_UPS_TOOL) {\n turn.followUps = followUpsOf(part);\n continue;\n }\n turn.tools.push(part.toolName);\n turn.answerStart = turn.text.length;\n }\n return;\n }\n\n if (message.role !== \"tool\") {\n return;\n }\n\n for (const part of partsOf(message)) {\n if (part.type !== \"tool-result\" || typeof part.toolName !== \"string\") {\n continue;\n }\n if (part.toolName === FOLLOW_UPS_TOOL) {\n continue;\n }\n const outputType = String(part.output?.type);\n if (FAILED_OUTPUTS.has(outputType)) {\n turn.failed.push(part.toolName);\n } else {\n turn.completed.push(part.toolName);\n }\n }\n};\n\n/**\n * Turns a saved conversation back into the turns the palette shows.\n *\n * The inverse of how the assistant replays a conversation: every user message starts a turn, and\n * the assistant and tool messages after it are that turn's. The follow-up questions come from the\n * call that suggested them, so a reopened chat offers the same ones it ended with.\n */\nexport const turnsFromMessages = (messages: AdminAssistantMessage[]): RestoredTurn[] => {\n const turns: RestoredTurn[] = [];\n\n for (const message of messages) {\n if (message.role === \"user\") {\n const question = textOf(message);\n const turn = startTurn(question);\n turns.push(turn);\n continue;\n }\n\n const current = turns[turns.length - 1];\n if (current) {\n addToTurn(current, message);\n }\n }\n\n return turns;\n};\n"],"names":["FOLLOW_UPS_TOOL","MAX_FOLLOW_UPS","followUpsOf","part","questions","Array","result","question","partsOf","message","textOf","texts","FAILED_OUTPUTS","Set","startTurn","addToTurn","turn","text","outputType","String","turnsFromMessages","messages","turns","current"],"mappings":"AAmBA,MAAMA,kBAAkB;AACxB,MAAMC,iBAAiB;AAEvB,MAAMC,cAAc,CAACC;IACjB,MAAMC,YAAYD,KAAK,KAAK,EAAE;IAC9B,IAAI,CAACE,MAAM,OAAO,CAACD,YACf,OAAO,EAAE;IAGb,MAAME,SAAmB,EAAE;IAC3B,KAAK,MAAMC,YAAYH,UACnB,IAAI,AAAoB,YAApB,OAAOG,YAAyBA,SAAS,IAAI,IAC7CD,OAAO,IAAI,CAACC,SAAS,IAAI;IAGjC,OAAOD,OAAO,KAAK,CAAC,GAAGL;AAC3B;AAEA,MAAMO,UAAU,CAACC;IACb,IAAI,CAACJ,MAAM,OAAO,CAACI,QAAQ,OAAO,GAC9B,OAAO,EAAE;IAEb,OAAOA,QAAQ,OAAO,CAAC,MAAM,CACzB,CAACN,OAAuB,AAAgB,YAAhB,OAAOA,QAAqBA,AAAS,SAATA;AAE5D;AAEA,MAAMO,SAAS,CAACD;IACZ,IAAI,AAA2B,YAA3B,OAAOA,QAAQ,OAAO,EACtB,OAAOA,QAAQ,OAAO;IAG1B,MAAME,QAAkB,EAAE;IAC1B,KAAK,MAAMR,QA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eAAe,GAAG,CAACM,aACnBF,KAAK,MAAM,CAAC,IAAI,CAACb,KAAK,QAAQ;aAE9Ba,KAAK,SAAS,CAAC,IAAI,CAACb,KAAK,QAAQ;IAEzC;AACJ;AASO,MAAMiB,oBAAoB,CAACC;IAC9B,MAAMC,QAAwB,EAAE;IAEhC,KAAK,MAAMb,WAAWY,SAAU;QAC5B,IAAIZ,AAAiB,WAAjBA,QAAQ,IAAI,EAAa;YACzB,MAAMF,WAAWG,OAAOD;YACxB,MAAMO,OAAOF,UAAUP;YACvBe,MAAM,IAAI,CAACN;YACX;QACJ;QAEA,MAAMO,UAAUD,KAAK,CAACA,MAAM,MAAM,GAAG,EAAE;QACvC,IAAIC,SACAR,UAAUQ,SAASd;IAE3B;IAEA,OAAOa;AACX"}
|
|
@@ -1,15 +1,12 @@
|
|
|
1
1
|
import { MainGraphQLClient } from "@webiny/app/features/mainGraphQLClient/index.js";
|
|
2
2
|
import { AiChatsGateway as GatewayAbstraction } from "./abstractions.js";
|
|
3
3
|
import type { AiChat } from "./abstractions.js";
|
|
4
|
-
import type { AiChatSummary } from "./abstractions.js";
|
|
5
4
|
import type { AiChatsPage } from "./abstractions.js";
|
|
6
|
-
import type { SaveAiChatInput } from "./abstractions.js";
|
|
7
5
|
declare class AiChatsGatewayImpl implements GatewayAbstraction.Interface {
|
|
8
6
|
private client;
|
|
9
7
|
constructor(client: MainGraphQLClient.Interface);
|
|
10
8
|
list(after?: string): Promise<AiChatsPage>;
|
|
11
9
|
get(id: string): Promise<AiChat>;
|
|
12
|
-
save(input: SaveAiChatInput): Promise<AiChatSummary>;
|
|
13
10
|
delete(id: string): Promise<void>;
|
|
14
11
|
}
|
|
15
12
|
export declare const AiChatsGateway: typeof AiChatsGatewayImpl & {
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { MainGraphQLClient } from "@webiny/app/features/mainGraphQLClient/index.js";
|
|
2
2
|
import { AiChatsGateway } from "./abstractions.js";
|
|
3
|
-
import { AiChatsRequestError } from "./AiChatsRequestError.js";
|
|
4
3
|
const ERROR_FIELDS = `
|
|
5
4
|
error {
|
|
6
5
|
code
|
|
@@ -42,21 +41,6 @@ const GET_AI_CHAT = `
|
|
|
42
41
|
}
|
|
43
42
|
}
|
|
44
43
|
`;
|
|
45
|
-
const SAVE_AI_CHAT = `
|
|
46
|
-
mutation SaveAiChat($data: AiChatInput!) {
|
|
47
|
-
aiPowerUps {
|
|
48
|
-
saveAiChat(data: $data) {
|
|
49
|
-
data {
|
|
50
|
-
id
|
|
51
|
-
title
|
|
52
|
-
createdOn
|
|
53
|
-
savedOn
|
|
54
|
-
}
|
|
55
|
-
${ERROR_FIELDS}
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
`;
|
|
60
44
|
const DELETE_AI_CHAT = `
|
|
61
45
|
mutation DeleteAiChat($id: ID!) {
|
|
62
46
|
aiPowerUps {
|
|
@@ -68,7 +52,7 @@ const DELETE_AI_CHAT = `
|
|
|
68
52
|
}
|
|
69
53
|
`;
|
|
70
54
|
function unwrap(response) {
|
|
71
|
-
if (response.error) throw new
|
|
55
|
+
if (response.error) throw new Error(response.error.message);
|
|
72
56
|
if (null === response.data) throw new Error("The API returned no data.");
|
|
73
57
|
return response.data;
|
|
74
58
|
}
|
|
@@ -102,15 +86,6 @@ class AiChatsGatewayImpl {
|
|
|
102
86
|
});
|
|
103
87
|
return unwrap(response.aiPowerUps.getAiChat);
|
|
104
88
|
}
|
|
105
|
-
async save(input) {
|
|
106
|
-
const response = await this.client.execute({
|
|
107
|
-
query: SAVE_AI_CHAT,
|
|
108
|
-
variables: {
|
|
109
|
-
data: input
|
|
110
|
-
}
|
|
111
|
-
});
|
|
112
|
-
return unwrap(response.aiPowerUps.saveAiChat);
|
|
113
|
-
}
|
|
114
89
|
async delete(id) {
|
|
115
90
|
const response = await this.client.execute({
|
|
116
91
|
query: DELETE_AI_CHAT,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"features/aiChats/AiChatsGateway.js","sources":["../../../src/features/aiChats/AiChatsGateway.ts"],"sourcesContent":["import { MainGraphQLClient } from \"@webiny/app/features/mainGraphQLClient/index.js\";\nimport { AiChatsGateway as GatewayAbstraction } from \"./abstractions.js\";\nimport type { AiChat } from \"./abstractions.js\";\nimport type { AiChatSummary } from \"./abstractions.js\";\nimport type { AiChatsPage } from \"./abstractions.js\";\
|
|
1
|
+
{"version":3,"file":"features/aiChats/AiChatsGateway.js","sources":["../../../src/features/aiChats/AiChatsGateway.ts"],"sourcesContent":["import { MainGraphQLClient } from \"@webiny/app/features/mainGraphQLClient/index.js\";\nimport { AiChatsGateway as GatewayAbstraction } from \"./abstractions.js\";\nimport type { AiChat } from \"./abstractions.js\";\nimport type { AiChatSummary } from \"./abstractions.js\";\nimport type { AiChatsPage } from \"./abstractions.js\";\n\nconst ERROR_FIELDS = /* GraphQL */ `\n error {\n code\n message\n }\n`;\n\nconst LIST_AI_CHATS = /* GraphQL */ `\n query ListAiChats($after: String) {\n aiPowerUps {\n listAiChats(after: $after) {\n data {\n id\n title\n createdOn\n savedOn\n }\n meta {\n cursor\n hasMoreItems\n }\n ${ERROR_FIELDS}\n }\n }\n }\n`;\n\nconst GET_AI_CHAT = /* GraphQL */ `\n query GetAiChat($id: ID!) {\n aiPowerUps {\n getAiChat(id: $id) {\n data {\n id\n title\n createdOn\n savedOn\n messages\n }\n ${ERROR_FIELDS}\n }\n }\n }\n`;\n\nconst DELETE_AI_CHAT = /* GraphQL */ `\n mutation DeleteAiChat($id: ID!) {\n aiPowerUps {\n deleteAiChat(id: $id) {\n data\n ${ERROR_FIELDS}\n }\n }\n }\n`;\n\ninterface GraphQLError {\n code: string;\n message: string;\n}\n\ninterface Response<TData, TMeta = undefined> {\n data: TData | null;\n meta?: TMeta;\n error: GraphQLError | null;\n}\n\ninterface ListResponse {\n aiPowerUps: {\n listAiChats: Response<AiChatSummary[], { cursor: string | null; hasMoreItems: boolean }>;\n };\n}\n\ninterface GetResponse {\n aiPowerUps: { getAiChat: Response<AiChat> };\n}\n\ninterface DeleteResponse {\n aiPowerUps: { deleteAiChat: Response<boolean> };\n}\n\n/**\n * Every operation answers `{ data, error }`; a missing `data` without an error is still a failure.\n */\nfunction unwrap<TData, TMeta>(response: Response<TData, TMeta>): TData {\n if (response.error) {\n throw new Error(response.error.message);\n }\n if (response.data === null) {\n throw new Error(\"The API returned no data.\");\n }\n return response.data;\n}\n\nclass AiChatsGatewayImpl implements GatewayAbstraction.Interface {\n constructor(private client: MainGraphQLClient.Interface) {}\n\n async list(after?: string): Promise<AiChatsPage> {\n const response = await this.client.execute<ListResponse>({\n query: LIST_AI_CHATS,\n variables: { after }\n });\n\n const result = response.aiPowerUps.listAiChats;\n const chats = unwrap(result);\n const meta = result.meta;\n\n let cursor: string | null = null;\n if (meta?.hasMoreItems) {\n cursor = meta.cursor;\n }\n\n return { chats, cursor };\n }\n\n async get(id: string): Promise<AiChat> {\n const response = await this.client.execute<GetResponse>({\n query: GET_AI_CHAT,\n variables: { id }\n });\n\n return unwrap(response.aiPowerUps.getAiChat);\n }\n\n async delete(id: string): Promise<void> {\n const response = await this.client.execute<DeleteResponse>({\n query: DELETE_AI_CHAT,\n variables: { id }\n });\n\n unwrap(response.aiPowerUps.deleteAiChat);\n }\n}\n\nexport const AiChatsGateway = GatewayAbstraction.createImplementation({\n implementation: AiChatsGatewayImpl,\n dependencies: [MainGraphQLClient]\n});\n"],"names":["ERROR_FIELDS","LIST_AI_CHATS","GET_AI_CHAT","DELETE_AI_CHAT","unwrap","response","Error","AiChatsGatewayImpl","client","after","result","chats","meta","cursor","id","AiChatsGateway","GatewayAbstraction","MainGraphQLClient"],"mappings":";;AAMA,MAAMA,eAA6B,CAAC;;;;;AAKpC,CAAC;AAED,MAAMC,gBAA8B,CAAC;;;;;;;;;;;;;;gBAcrB,EAAED,aAAa;;;;AAI/B,CAAC;AAED,MAAME,cAA4B,CAAC;;;;;;;;;;;gBAWnB,EAAEF,aAAa;;;;AAI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2
2
|
import { AiChatsRepository as RepositoryAbstraction } from "./abstractions.js";
|
|
3
3
|
import type { AiChat } from "./abstractions.js";
|
|
4
4
|
import type { AiChatSummary } from "./abstractions.js";
|
|
5
|
-
import type { SaveAiChatInput } from "./abstractions.js";
|
|
6
5
|
/**
|
|
7
6
|
* Registered as a singleton, so the assistant and the chats panel see one list.
|
|
8
7
|
*
|
|
@@ -21,13 +20,12 @@ declare class AiChatsRepositoryImpl implements RepositoryAbstraction.Interface {
|
|
|
21
20
|
load(): Promise<void>;
|
|
22
21
|
loadMore(): Promise<void>;
|
|
23
22
|
get(id: string): Promise<AiChat>;
|
|
24
|
-
|
|
23
|
+
remember(chat: AiChatSummary): void;
|
|
25
24
|
delete(id: string): Promise<void>;
|
|
26
25
|
private read;
|
|
27
26
|
private startReading;
|
|
28
27
|
private addPage;
|
|
29
28
|
private failReading;
|
|
30
|
-
private upsert;
|
|
31
29
|
private remove;
|
|
32
30
|
}
|
|
33
31
|
export declare const AiChatsRepository: typeof AiChatsRepositoryImpl & {
|
|
@@ -1,13 +1,6 @@
|
|
|
1
1
|
import { makeAutoObservable } from "mobx";
|
|
2
2
|
import { AiChatsGateway, AiChatsRepository } from "./abstractions.js";
|
|
3
3
|
import { messageOf } from "./messageOf.js";
|
|
4
|
-
import { AiChatSaveError } from "./AiChatSaveError.js";
|
|
5
|
-
import { AiChatsRequestError } from "./AiChatsRequestError.js";
|
|
6
|
-
const CHAT_TOO_LARGE = "AiChat/TooLarge";
|
|
7
|
-
const saveFailureOf = (error)=>{
|
|
8
|
-
if (!(error instanceof AiChatsRequestError)) return "unreachable";
|
|
9
|
-
return error.code === CHAT_TOO_LARGE ? "too-large" : "rejected";
|
|
10
|
-
};
|
|
11
4
|
class AiChatsRepositoryImpl {
|
|
12
5
|
constructor(gateway){
|
|
13
6
|
this.gateway = gateway;
|
|
@@ -33,17 +26,16 @@ class AiChatsRepositoryImpl {
|
|
|
33
26
|
get(id) {
|
|
34
27
|
return this.gateway.get(id);
|
|
35
28
|
}
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
29
|
+
remember(chat) {
|
|
30
|
+
const known = this.chats.some((existing)=>existing.id === chat.id);
|
|
31
|
+
if (!known) {
|
|
32
|
+
this.chats = [
|
|
33
|
+
chat,
|
|
34
|
+
...this.chats
|
|
35
|
+
];
|
|
36
|
+
return;
|
|
44
37
|
}
|
|
45
|
-
this.
|
|
46
|
-
return summary;
|
|
38
|
+
this.chats = this.chats.map((existing)=>existing.id === chat.id ? chat : existing);
|
|
47
39
|
}
|
|
48
40
|
async delete(id) {
|
|
49
41
|
await this.gateway.delete(id);
|
|
@@ -84,17 +76,6 @@ class AiChatsRepositoryImpl {
|
|
|
84
76
|
this.error = message;
|
|
85
77
|
this.loading = false;
|
|
86
78
|
}
|
|
87
|
-
upsert(summary) {
|
|
88
|
-
const known = this.chats.some((chat)=>chat.id === summary.id);
|
|
89
|
-
if (!known) {
|
|
90
|
-
this.chats = [
|
|
91
|
-
summary,
|
|
92
|
-
...this.chats
|
|
93
|
-
];
|
|
94
|
-
return;
|
|
95
|
-
}
|
|
96
|
-
this.chats = this.chats.map((chat)=>chat.id === summary.id ? summary : chat);
|
|
97
|
-
}
|
|
98
79
|
remove(id) {
|
|
99
80
|
this.chats = this.chats.filter((chat)=>chat.id !== id);
|
|
100
81
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"features/aiChats/AiChatsRepository.js","sources":["../../../src/features/aiChats/AiChatsRepository.ts"],"sourcesContent":["import { makeAutoObservable } from \"mobx\";\nimport { AiChatsGateway } from \"./abstractions.js\";\nimport { AiChatsRepository as RepositoryAbstraction } from \"./abstractions.js\";\nimport type { AiChat } from \"./abstractions.js\";\nimport type { AiChatSummary } from \"./abstractions.js\";\nimport type { AiChatsPage } from \"./abstractions.js\";\nimport
|
|
1
|
+
{"version":3,"file":"features/aiChats/AiChatsRepository.js","sources":["../../../src/features/aiChats/AiChatsRepository.ts"],"sourcesContent":["import { makeAutoObservable } from \"mobx\";\nimport { AiChatsGateway } from \"./abstractions.js\";\nimport { AiChatsRepository as RepositoryAbstraction } from \"./abstractions.js\";\nimport type { AiChat } from \"./abstractions.js\";\nimport type { AiChatSummary } from \"./abstractions.js\";\nimport type { AiChatsPage } from \"./abstractions.js\";\nimport { messageOf } from \"./messageOf.js\";\n\n/**\n * Registered as a singleton, so the assistant and the chats panel see one list.\n *\n * Each mutation after an `await` is its own method, because `makeAutoObservable` makes those\n * actions and a bare assignment after an `await` would have left the one it started in.\n */\nclass AiChatsRepositoryImpl implements RepositoryAbstraction.Interface {\n chats: AiChatSummary[] = [];\n loading = false;\n error: string | null = null;\n private cursor: string | null = null;\n // Counts reads, so a read that a later one replaced cannot write its result over the newer one.\n private reads = 0;\n\n constructor(private gateway: AiChatsGateway.Interface) {\n makeAutoObservable<AiChatsRepositoryImpl, \"gateway\">(this, { gateway: false });\n }\n\n get hasMore(): boolean {\n return this.cursor !== null;\n }\n\n async load(): Promise<void> {\n await this.read(undefined, true);\n }\n\n async loadMore(): Promise<void> {\n if (this.cursor === null || this.loading) {\n return;\n }\n await this.read(this.cursor, false);\n }\n\n get(id: string): Promise<AiChat> {\n return this.gateway.get(id);\n }\n\n /*\n * The server lists chats by when they were created, so a chat saved again keeps its place. Only\n * a new chat goes first, which is also where the server puts it.\n */\n remember(chat: AiChatSummary): void {\n const known = this.chats.some(existing => existing.id === chat.id);\n if (!known) {\n this.chats = [chat, ...this.chats];\n return;\n }\n this.chats = this.chats.map(existing => (existing.id === chat.id ? chat : existing));\n }\n\n async delete(id: string): Promise<void> {\n await this.gateway.delete(id);\n this.remove(id);\n }\n\n /*\n * `load()` can start while a read is still in flight, since opening the history view reads the\n * first page again. Only the newest read updates the list, `loading` and `error`; an older one\n * finishing late is dropped.\n */\n private async read(after: string | undefined, replace: boolean): Promise<void> {\n const read = this.startReading();\n\n try {\n const page = await this.gateway.list(after);\n if (read === this.reads) {\n this.addPage(page, replace);\n }\n } catch (error) {\n if (read === this.reads) {\n const message = messageOf(error);\n this.failReading(message);\n }\n }\n }\n\n private startReading(): number {\n this.loading = true;\n this.error = null;\n this.reads++;\n return this.reads;\n }\n\n private addPage(page: AiChatsPage, replace: boolean): void {\n if (replace) {\n this.chats = page.chats;\n } else {\n // A chat created since the first page shifts the server's pages, so the next can repeat one.\n const known = new Set(this.chats.map(chat => chat.id));\n const fresh = page.chats.filter(chat => !known.has(chat.id));\n this.chats = [...this.chats, ...fresh];\n }\n this.cursor = page.cursor;\n this.loading = false;\n }\n\n private failReading(message: string): void {\n this.error = message;\n this.loading = false;\n }\n\n private remove(id: string): void {\n this.chats = this.chats.filter(chat => chat.id !== id);\n }\n}\n\nexport const AiChatsRepository = RepositoryAbstraction.createImplementation({\n implementation: AiChatsRepositoryImpl,\n dependencies: [AiChatsGateway]\n});\n"],"names":["AiChatsRepositoryImpl","gateway","makeAutoObservable","undefined","id","chat","known","existing","after","replace","read","page","error","message","messageOf","Set","fresh","AiChatsRepository","RepositoryAbstraction","AiChatsGateway"],"mappings":";;;AAcA,MAAMA;IAQF,YAAoBC,OAAiC,CAAE;aAAnCA,OAAO,GAAPA;aAPpB,KAAK,GAAoB,EAAE;aAC3B,OAAO,GAAG;aACV,KAAK,GAAkB;aACf,MAAM,GAAkB;aAExB,KAAK,GAAG;QAGZC,mBAAqD,IAAI,EAAE;YAAE,SAAS;QAAM;IAChF;IAEA,IAAI,UAAmB;QACnB,OAAO,AAAgB,SAAhB,IAAI,CAAC,MAAM;IACtB;IAEA,MAAM,OAAsB;QACxB,MAAM,IAAI,CAAC,IAAI,CAACC,QAAW;IAC/B;IAEA,MAAM,WAA0B;QAC5B,IAAI,AAAgB,SAAhB,IAAI,CAAC,MAAM,IAAa,IAAI,CAAC,OAAO,EACpC;QAEJ,MAAM,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE;IACjC;IAEA,IAAIC,EAA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