@webiny/app-admin 6.6.0-alpha.10 → 6.6.0-alpha.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (176) hide show
  1. package/base/Admin.js +2 -0
  2. package/base/Admin.js.map +1 -1
  3. package/base/createRootContainer.js +2 -0
  4. package/base/createRootContainer.js.map +1 -1
  5. package/base/resolveApiUrl.js +3 -2
  6. package/base/resolveApiUrl.js.map +1 -1
  7. package/components/SimpleForm/SimpleForm.js +2 -2
  8. package/components/SimpleForm/SimpleForm.js.map +1 -1
  9. package/features/accessManagement/roles/roleEvents/ApplyRoleChangeToCache.d.ts +17 -0
  10. package/features/accessManagement/roles/roleEvents/ApplyRoleChangeToCache.js +26 -0
  11. package/features/accessManagement/roles/roleEvents/ApplyRoleChangeToCache.js.map +1 -0
  12. package/features/accessManagement/roles/roleEvents/RefreshRoleInCacheRepository.d.ts +18 -0
  13. package/features/accessManagement/roles/roleEvents/RefreshRoleInCacheRepository.js +26 -0
  14. package/features/accessManagement/roles/roleEvents/RefreshRoleInCacheRepository.js.map +1 -0
  15. package/features/accessManagement/roles/roleEvents/abstractions.d.ts +8 -0
  16. package/features/accessManagement/roles/roleEvents/abstractions.js +5 -0
  17. package/features/accessManagement/roles/roleEvents/abstractions.js.map +1 -0
  18. package/features/accessManagement/roles/roleEvents/feature.d.ts +5 -0
  19. package/features/accessManagement/roles/roleEvents/feature.js +13 -0
  20. package/features/accessManagement/roles/roleEvents/feature.js.map +1 -0
  21. package/features/accessManagement/roles/roleEvents/index.d.ts +1 -0
  22. package/features/accessManagement/roles/roleEvents/index.js +1 -0
  23. package/features/accessManagement/teams/teamEvents/ApplyTeamChangeToCache.d.ts +17 -0
  24. package/features/accessManagement/teams/teamEvents/ApplyTeamChangeToCache.js +26 -0
  25. package/features/accessManagement/teams/teamEvents/ApplyTeamChangeToCache.js.map +1 -0
  26. package/features/accessManagement/teams/teamEvents/RefreshTeamInCacheRepository.d.ts +18 -0
  27. package/features/accessManagement/teams/teamEvents/RefreshTeamInCacheRepository.js +26 -0
  28. package/features/accessManagement/teams/teamEvents/RefreshTeamInCacheRepository.js.map +1 -0
  29. package/features/accessManagement/teams/teamEvents/abstractions.d.ts +8 -0
  30. package/features/accessManagement/teams/teamEvents/abstractions.js +5 -0
  31. package/features/accessManagement/teams/teamEvents/abstractions.js.map +1 -0
  32. package/features/accessManagement/teams/teamEvents/feature.d.ts +5 -0
  33. package/features/accessManagement/teams/teamEvents/feature.js +13 -0
  34. package/features/accessManagement/teams/teamEvents/feature.js.map +1 -0
  35. package/features/accessManagement/teams/teamEvents/index.d.ts +1 -0
  36. package/features/accessManagement/teams/teamEvents/index.js +1 -0
  37. package/features/adminAssistant/AdminAssistantGateway.js +4 -3
  38. package/features/adminAssistant/AdminAssistantGateway.js.map +1 -1
  39. package/features/adminAssistant/AdminAssistantPresenter.d.ts +16 -13
  40. package/features/adminAssistant/AdminAssistantPresenter.js +57 -91
  41. package/features/adminAssistant/AdminAssistantPresenter.js.map +1 -1
  42. package/features/adminAssistant/abstractions.d.ts +31 -23
  43. package/features/adminAssistant/abstractions.js.map +1 -1
  44. package/features/adminAssistant/turnsFromMessages.d.ts +4 -7
  45. package/features/adminAssistant/turnsFromMessages.js +0 -2
  46. package/features/adminAssistant/turnsFromMessages.js.map +1 -1
  47. package/features/adminUsers/users/userEvents/MarkUsersChanged.d.ts +16 -0
  48. package/features/adminUsers/users/userEvents/MarkUsersChanged.js +23 -0
  49. package/features/adminUsers/users/userEvents/MarkUsersChanged.js.map +1 -0
  50. package/features/adminUsers/users/userEvents/UsersRevision.d.ts +13 -0
  51. package/features/adminUsers/users/userEvents/UsersRevision.js +25 -0
  52. package/features/adminUsers/users/userEvents/UsersRevision.js.map +1 -0
  53. package/features/adminUsers/users/userEvents/abstractions.d.ts +17 -0
  54. package/features/adminUsers/users/userEvents/abstractions.js +5 -0
  55. package/features/adminUsers/users/userEvents/abstractions.js.map +1 -0
  56. package/features/adminUsers/users/userEvents/feature.d.ts +4 -0
  57. package/features/adminUsers/users/userEvents/feature.js +19 -0
  58. package/features/adminUsers/users/userEvents/feature.js.map +1 -0
  59. package/features/adminUsers/users/userEvents/index.d.ts +1 -0
  60. package/features/adminUsers/users/userEvents/index.js +1 -0
  61. package/features/aiChats/AiChatsGateway.d.ts +0 -3
  62. package/features/aiChats/AiChatsGateway.js +1 -26
  63. package/features/aiChats/AiChatsGateway.js.map +1 -1
  64. package/features/aiChats/AiChatsRepository.d.ts +1 -3
  65. package/features/aiChats/AiChatsRepository.js +9 -28
  66. package/features/aiChats/AiChatsRepository.js.map +1 -1
  67. package/features/aiChats/abstractions.d.ts +7 -19
  68. package/features/aiChats/abstractions.js.map +1 -1
  69. package/features/aiChats/index.d.ts +0 -2
  70. package/features/aiChats/index.js +0 -1
  71. package/features/assistantPageContext/AssistantPageContext.d.ts +12 -0
  72. package/features/assistantPageContext/AssistantPageContext.js +32 -0
  73. package/features/assistantPageContext/AssistantPageContext.js.map +1 -0
  74. package/features/assistantPageContext/abstractions.d.ts +33 -0
  75. package/features/assistantPageContext/abstractions.js +5 -0
  76. package/features/assistantPageContext/abstractions.js.map +1 -0
  77. package/features/assistantPageContext/feature.d.ts +3 -0
  78. package/features/assistantPageContext/feature.js +17 -0
  79. package/features/assistantPageContext/feature.js.map +1 -0
  80. package/features/assistantPageContext/index.d.ts +2 -0
  81. package/features/assistantPageContext/index.js +2 -0
  82. package/index.d.ts +2 -1
  83. package/index.js +2 -1
  84. package/modules/AccessManagementExtension.js +6 -0
  85. package/modules/AccessManagementExtension.js.map +1 -1
  86. package/package.json +20 -20
  87. package/presentation/accessManagement/apiKeys/ApiKeysDataSource.d.ts +5 -6
  88. package/presentation/accessManagement/apiKeys/ApiKeysDataSource.js +12 -13
  89. package/presentation/accessManagement/apiKeys/ApiKeysDataSource.js.map +1 -1
  90. package/presentation/accessManagement/apiKeys/ApiKeysPresenter.d.ts +5 -0
  91. package/presentation/accessManagement/apiKeys/ApiKeysPresenter.js +32 -2
  92. package/presentation/accessManagement/apiKeys/ApiKeysPresenter.js.map +1 -1
  93. package/presentation/accessManagement/apiKeys/ApiKeysPresenter.test.d.ts +1 -0
  94. package/presentation/accessManagement/apiKeys/ApiKeysPresenter.test.js +87 -0
  95. package/presentation/accessManagement/apiKeys/ApiKeysPresenter.test.js.map +1 -0
  96. package/presentation/accessManagement/apiKeys/abstractions.d.ts +2 -0
  97. package/presentation/accessManagement/apiKeys/abstractions.js.map +1 -1
  98. package/presentation/accessManagement/apiKeys/components/ApiKeysView.js +13 -37
  99. package/presentation/accessManagement/apiKeys/components/ApiKeysView.js.map +1 -1
  100. package/presentation/accessManagement/roles/RolesDataSource.d.ts +5 -6
  101. package/presentation/accessManagement/roles/RolesDataSource.js +12 -13
  102. package/presentation/accessManagement/roles/RolesDataSource.js.map +1 -1
  103. package/presentation/accessManagement/roles/RolesPresenter.d.ts +5 -0
  104. package/presentation/accessManagement/roles/RolesPresenter.js +32 -2
  105. package/presentation/accessManagement/roles/RolesPresenter.js.map +1 -1
  106. package/presentation/accessManagement/roles/RolesPresenter.test.d.ts +1 -0
  107. package/presentation/accessManagement/roles/RolesPresenter.test.js +168 -0
  108. package/presentation/accessManagement/roles/RolesPresenter.test.js.map +1 -0
  109. package/presentation/accessManagement/roles/abstractions.d.ts +2 -0
  110. package/presentation/accessManagement/roles/abstractions.js.map +1 -1
  111. package/presentation/accessManagement/roles/components/RolesDataList.js +12 -37
  112. package/presentation/accessManagement/roles/components/RolesDataList.js.map +1 -1
  113. package/presentation/accessManagement/roles/components/RolesView.js +1 -0
  114. package/presentation/accessManagement/roles/components/RolesView.js.map +1 -1
  115. package/presentation/accessManagement/teams/TeamsDataSource.d.ts +5 -6
  116. package/presentation/accessManagement/teams/TeamsDataSource.js +12 -13
  117. package/presentation/accessManagement/teams/TeamsDataSource.js.map +1 -1
  118. package/presentation/accessManagement/teams/TeamsPresenter.d.ts +5 -0
  119. package/presentation/accessManagement/teams/TeamsPresenter.js +33 -2
  120. package/presentation/accessManagement/teams/TeamsPresenter.js.map +1 -1
  121. package/presentation/accessManagement/teams/TeamsPresenter.test.d.ts +1 -0
  122. package/presentation/accessManagement/teams/TeamsPresenter.test.js +97 -0
  123. package/presentation/accessManagement/teams/TeamsPresenter.test.js.map +1 -0
  124. package/presentation/accessManagement/teams/abstractions.d.ts +2 -0
  125. package/presentation/accessManagement/teams/abstractions.js.map +1 -1
  126. package/presentation/accessManagement/teams/components/TeamsDataList.js +12 -37
  127. package/presentation/accessManagement/teams/components/TeamsDataList.js.map +1 -1
  128. package/presentation/accessManagement/teams/components/TeamsView.js +1 -0
  129. package/presentation/accessManagement/teams/components/TeamsView.js.map +1 -1
  130. package/presentation/adminUsers/AdminUsers.js +3 -0
  131. package/presentation/adminUsers/AdminUsers.js.map +1 -1
  132. package/presentation/adminUsers/views/Users/UsersDataList.js +22 -1
  133. package/presentation/adminUsers/views/Users/UsersDataList.js.map +1 -1
  134. package/presentation/adminUsers/views/Users/hooks/useUserForm.js +39 -9
  135. package/presentation/adminUsers/views/Users/hooks/useUserForm.js.map +1 -1
  136. package/presentation/adminUsers/views/Users/hooks/useUserForm.test.d.ts +1 -0
  137. package/presentation/adminUsers/views/Users/hooks/useUserForm.test.js +149 -0
  138. package/presentation/adminUsers/views/Users/hooks/useUserForm.test.js.map +1 -0
  139. package/presentation/listPresenter/ListPresenter.d.ts +12 -1
  140. package/presentation/listPresenter/ListPresenter.js +60 -4
  141. package/presentation/listPresenter/ListPresenter.js.map +1 -1
  142. package/presentation/listPresenter/ListPresenter.test.js +82 -0
  143. package/presentation/listPresenter/ListPresenter.test.js.map +1 -1
  144. package/presentation/listPresenter/LocalDataSource.d.ts +34 -0
  145. package/presentation/listPresenter/LocalDataSource.js +75 -0
  146. package/presentation/listPresenter/LocalDataSource.js.map +1 -0
  147. package/presentation/listPresenter/LocalDataSource.test.d.ts +1 -0
  148. package/presentation/listPresenter/LocalDataSource.test.js +124 -0
  149. package/presentation/listPresenter/LocalDataSource.test.js.map +1 -0
  150. package/presentation/listPresenter/QueryMatcher.js +1 -12
  151. package/presentation/listPresenter/QueryMatcher.js.map +1 -1
  152. package/presentation/listPresenter/abstractions.d.ts +21 -0
  153. package/presentation/listPresenter/abstractions.js.map +1 -1
  154. package/presentation/listPresenter/compareValues.d.ts +7 -0
  155. package/presentation/listPresenter/compareValues.js +15 -0
  156. package/presentation/listPresenter/compareValues.js.map +1 -0
  157. package/presentation/listPresenter/index.d.ts +2 -0
  158. package/presentation/listPresenter/index.js +2 -0
  159. package/presentation/listPresenter/sortOption.d.ts +7 -0
  160. package/presentation/listPresenter/sortOption.js +16 -0
  161. package/presentation/listPresenter/sortOption.js.map +1 -0
  162. package/presentation/listPresenter/sortOption.test.d.ts +1 -0
  163. package/presentation/listPresenter/sortOption.test.js +26 -0
  164. package/presentation/listPresenter/sortOption.test.js.map +1 -0
  165. package/presentation/trashBin/TrashBinPresenter.js +9 -0
  166. package/presentation/trashBin/TrashBinPresenter.js.map +1 -1
  167. package/presentation/trashBin/TrashBinPresenter.test.js +75 -0
  168. package/presentation/trashBin/TrashBinPresenter.test.js.map +1 -1
  169. package/presentation/trashBin/abstractions.d.ts +9 -0
  170. package/presentation/trashBin/abstractions.js.map +1 -1
  171. package/features/aiChats/AiChatSaveError.d.ts +0 -6
  172. package/features/aiChats/AiChatSaveError.js +0 -8
  173. package/features/aiChats/AiChatSaveError.js.map +0 -1
  174. package/features/aiChats/AiChatsRequestError.d.ts +0 -9
  175. package/features/aiChats/AiChatsRequestError.js +0 -8
  176. package/features/aiChats/AiChatsRequestError.js.map +0 -1
@@ -1,6 +1,7 @@
1
1
  import { AdminAssistantGateway } from "./abstractions.js";
2
- import { AdminAssistantPresenter as Abstraction, type IAdminAssistantViewModel } from "./abstractions.js";
2
+ import { AdminAssistantPresenter as Abstraction } from "./abstractions.js";
3
3
  import { AiChatsRepository } from "../../features/aiChats/abstractions.js";
4
+ import { AssistantPageContext } from "../../features/assistantPageContext/abstractions.js";
4
5
  /**
5
6
  * Owns the palette's AI conversation.
6
7
  *
@@ -9,13 +10,14 @@ import { AiChatsRepository } from "../../features/aiChats/abstractions.js";
9
10
  *
10
11
  * Registered as a singleton, so `reset` genuinely clears rather than relying on unmount.
11
12
  *
12
- * The conversation is saved after every run that ends, so it is never more than one turn behind
13
- * what is on screen. The client saves rather than the stream route, which keeps the route
14
- * sessionless.
13
+ * The server keeps the conversation: a question sends only the chat id and the question, and the
14
+ * assistant reads the history from the saved chat and saves the run when it ends. The turns here
15
+ * are what is shown, never what is sent.
15
16
  */
16
17
  declare class AdminAssistantPresenterImpl implements Abstraction.Interface {
17
18
  private gateway;
18
19
  private chats;
20
+ private pageContext;
19
21
  private turns;
20
22
  private busy;
21
23
  private model;
@@ -24,22 +26,22 @@ declare class AdminAssistantPresenterImpl implements Abstraction.Interface {
24
26
  private storageError;
25
27
  private saveFailure;
26
28
  private controller;
27
- private saving;
28
29
  private generation;
29
- constructor(gateway: AdminAssistantGateway.Interface, chats: AiChatsRepository.Interface);
30
- get vm(): IAdminAssistantViewModel;
30
+ constructor(gateway: AdminAssistantGateway.Interface, chats: AiChatsRepository.Interface, pageContext: AssistantPageContext.Interface);
31
+ get vm(): Abstraction.ViewModel;
31
32
  ask(question: string): void;
32
33
  decide(turnIndex: number, approved: boolean): void;
33
34
  retry(): void;
34
- retrySave(): void;
35
- private get savePaused();
36
35
  private get setupRequired();
37
36
  reset(): void;
38
37
  open(chatId: string): Promise<void>;
39
- private queueSave;
40
- private save;
41
- /** Replays settled turns so a follow-up ("and which of those is cheapest?") has context. */
42
- private historyBefore;
38
+ /**
39
+ * A question, with whatever the screen behind the palette says about itself. Read at the moment
40
+ * of asking, so a retry describes the screen the user is on now.
41
+ */
42
+ private question;
43
+ /** A request for the chat on screen: the server reads its history from the saved chat. */
44
+ private request;
43
45
  private run;
44
46
  private addTurn;
45
47
  private replaceTurn;
@@ -49,6 +51,7 @@ declare class AdminAssistantPresenterImpl implements Abstraction.Interface {
49
51
  private setOpening;
50
52
  private setConversation;
51
53
  private setSaved;
54
+ private dropPendingApprovals;
52
55
  private setStorageError;
53
56
  private setSaveFailed;
54
57
  private clearStorageError;
@@ -1,11 +1,10 @@
1
1
  import { makeAutoObservable } from "mobx";
2
2
  import { AdminAssistantGateway, AdminAssistantPresenter } from "./abstractions.js";
3
3
  import { AiChatsRepository } from "../aiChats/abstractions.js";
4
- import { AiChatSaveError } from "../aiChats/AiChatSaveError.js";
4
+ import { AssistantPageContext } from "../assistantPageContext/abstractions.js";
5
5
  import { messageOf } from "../aiChats/messageOf.js";
6
6
  import { turnsFromMessages } from "./turnsFromMessages.js";
7
7
  const NOT_CONFIGURED = "AI_CAPABILITY_NOT_CONFIGURED";
8
- const saveFailureOf = (error)=>error instanceof AiChatSaveError ? error.failure : "unreachable";
9
8
  const emptyTurn = (question)=>({
10
9
  question,
11
10
  text: "",
@@ -16,13 +15,13 @@ const emptyTurn = (question)=>({
16
15
  running: false,
17
16
  pendingApprovals: [],
18
17
  followUps: [],
19
- messages: [],
20
18
  settled: false
21
19
  });
22
20
  class AdminAssistantPresenterImpl {
23
- constructor(gateway, chats){
21
+ constructor(gateway, chats, pageContext){
24
22
  this.gateway = gateway;
25
23
  this.chats = chats;
24
+ this.pageContext = pageContext;
26
25
  this.turns = [];
27
26
  this.busy = false;
28
27
  this.model = void 0;
@@ -31,13 +30,12 @@ class AdminAssistantPresenterImpl {
31
30
  this.storageError = null;
32
31
  this.saveFailure = null;
33
32
  this.controller = null;
34
- this.saving = Promise.resolve();
35
33
  this.generation = 0;
36
34
  makeAutoObservable(this, {
37
35
  controller: false,
38
- saving: false,
39
36
  generation: false,
40
- chats: false
37
+ chats: false,
38
+ pageContext: false
41
39
  });
42
40
  }
43
41
  get vm() {
@@ -47,7 +45,6 @@ class AdminAssistantPresenterImpl {
47
45
  opening: this.opening,
48
46
  storageError: this.storageError,
49
47
  saveFailure: this.saveFailure,
50
- savePaused: this.savePaused,
51
48
  setupRequired: this.setupRequired,
52
49
  turns: this.turns.map((turn)=>{
53
50
  const view = {
@@ -73,71 +70,48 @@ class AdminAssistantPresenterImpl {
73
70
  ask(question) {
74
71
  const trimmed = question.trim();
75
72
  if (!trimmed || this.busy || this.opening || this.setupRequired) return;
73
+ this.dropPendingApprovals();
74
+ this.clearStorageError();
76
75
  const index = this.turns.length;
77
76
  this.addTurn(trimmed);
78
- this.run(index, {
79
- messages: [
80
- ...this.historyBefore(index),
81
- {
82
- role: "user",
83
- content: trimmed
84
- }
85
- ]
86
- });
77
+ const request = this.question(trimmed);
78
+ this.run(index, request);
87
79
  }
88
80
  decide(turnIndex, approved) {
89
81
  const turn = this.turns[turnIndex];
90
82
  if (!turn?.pendingApprovals.length || this.busy || this.opening) return;
83
+ if (!this.chatId || this.saveFailure) return void this.patch(turnIndex, {
84
+ pendingApprovals: [],
85
+ error: "This change can't run because the chat wasn't saved. Ask again to retry."
86
+ });
91
87
  const approvals = turn.pendingApprovals.map((approval)=>({
92
88
  approvalId: approval.approvalId,
93
89
  approved
94
90
  }));
95
- const messages = [
96
- ...this.historyBefore(turnIndex),
97
- {
98
- role: "user",
99
- content: turn.question
100
- },
101
- ...turn.messages
102
- ];
103
91
  this.patch(turnIndex, {
104
92
  pendingApprovals: [],
105
93
  followUps: [],
106
94
  settled: false,
107
95
  running: true
108
96
  });
109
- this.run(turnIndex, {
110
- messages,
97
+ const request = this.request({
111
98
  approvals
112
- }, true);
99
+ });
100
+ this.run(turnIndex, request, true);
113
101
  }
114
102
  retry() {
115
103
  const index = this.turns.length - 1;
116
104
  const turn = this.turns[index];
117
- if (!turn?.error || this.busy || this.opening) return;
105
+ if (!turn || this.busy || this.opening) return;
106
+ if (!turn.error && "retryable" !== this.saveFailure) return;
107
+ this.clearStorageError();
118
108
  const fresh = emptyTurn(turn.question);
119
109
  this.replaceTurn(index, {
120
110
  ...fresh,
121
111
  running: true
122
112
  });
123
- const history = this.historyBefore(index);
124
- this.run(index, {
125
- messages: [
126
- ...history,
127
- {
128
- role: "user",
129
- content: turn.question
130
- }
131
- ]
132
- });
133
- }
134
- retrySave() {
135
- if (!this.saveFailure || this.savePaused) return;
136
- this.clearStorageError();
137
- this.queueSave();
138
- }
139
- get savePaused() {
140
- return this.turns.some((turn)=>turn.pendingApprovals.length > 0);
113
+ const request = this.question(turn.question);
114
+ this.run(index, request);
141
115
  }
142
116
  get setupRequired() {
143
117
  const newest = this.turns[this.turns.length - 1];
@@ -167,39 +141,20 @@ class AdminAssistantPresenterImpl {
167
141
  if (generation === this.generation) this.setOpening(false);
168
142
  }
169
143
  }
170
- queueSave() {
171
- const messages = this.historyBefore(this.turns.length);
172
- if (this.savePaused || 0 === messages.length) return;
173
- const generation = this.generation;
174
- this.saving = this.saving.then(()=>this.save(generation, messages));
175
- }
176
- async save(generation, messages) {
177
- if (generation !== this.generation) return;
178
- try {
179
- const input = {
180
- messages
181
- };
182
- if (this.chatId) input.id = this.chatId;
183
- const summary = await this.chats.save(input);
184
- if (generation === this.generation) this.setSaved(summary.id);
185
- } catch (error) {
186
- if (generation === this.generation) {
187
- const message = messageOf(error);
188
- const failure = saveFailureOf(error);
189
- this.setSaveFailed(message, failure);
190
- }
191
- }
144
+ question(prompt) {
145
+ const request = this.request({
146
+ prompt
147
+ });
148
+ const pageContext = this.pageContext.get();
149
+ if (pageContext) request.pageContext = pageContext;
150
+ return request;
192
151
  }
193
- historyBefore(upTo) {
194
- const history = [];
195
- for (const turn of this.turns.slice(0, upTo))if (turn.settled && !turn.error) {
196
- history.push({
197
- role: "user",
198
- content: turn.question
199
- });
200
- history.push(...turn.messages);
201
- }
202
- return history;
152
+ request(rest) {
153
+ const request = {
154
+ ...rest
155
+ };
156
+ if (this.chatId) request.chatId = this.chatId;
157
+ return request;
203
158
  }
204
159
  async run(index, request, resuming = false) {
205
160
  this.controller?.abort();
@@ -218,9 +173,6 @@ class AdminAssistantPresenterImpl {
218
173
  const failed = existing ? [
219
174
  ...existing.failed
220
175
  ] : [];
221
- const priorMessages = existing ? [
222
- ...existing.messages
223
- ] : [];
224
176
  let separateFromExisting = text.length > 0;
225
177
  for await (const event of this.gateway.stream(request, controller.signal)){
226
178
  if ("start" === event.type) {
@@ -278,12 +230,17 @@ class AdminAssistantPresenterImpl {
278
230
  });
279
231
  continue;
280
232
  }
233
+ if ("saved" === event.type) {
234
+ this.setSaved(event.chat);
235
+ continue;
236
+ }
237
+ if ("not-saved" === event.type) {
238
+ const failure = event.retryable && !resuming ? "retryable" : "final";
239
+ this.setSaveFailed(event.message, failure);
240
+ continue;
241
+ }
281
242
  if ("done" === event.type) {
282
243
  this.patch(index, {
283
- messages: [
284
- ...priorMessages,
285
- ...event.messages
286
- ],
287
244
  settled: true,
288
245
  running: false
289
246
  });
@@ -305,8 +262,6 @@ class AdminAssistantPresenterImpl {
305
262
  } finally{
306
263
  this.setBusy(false);
307
264
  }
308
- const turn = this.turns[index];
309
- if (!controller.signal.aborted && turn?.settled && !turn.error) this.queueSave();
310
265
  }
311
266
  addTurn(question) {
312
267
  this.turns = [
@@ -339,10 +294,20 @@ class AdminAssistantPresenterImpl {
339
294
  this.chatId = chatId;
340
295
  this.turns = turns;
341
296
  }
342
- setSaved(chatId) {
343
- this.chatId = chatId;
297
+ setSaved(chat) {
298
+ this.chatId = chat.id;
344
299
  this.storageError = null;
345
300
  this.saveFailure = null;
301
+ this.chats.remember(chat);
302
+ }
303
+ dropPendingApprovals() {
304
+ this.turns = this.turns.map((turn)=>{
305
+ if (0 === turn.pendingApprovals.length) return turn;
306
+ return {
307
+ ...turn,
308
+ pendingApprovals: []
309
+ };
310
+ });
346
311
  }
347
312
  setStorageError(message) {
348
313
  this.storageError = message;
@@ -369,7 +334,8 @@ const AdminAssistantPresenter_AdminAssistantPresenter = AdminAssistantPresenter.
369
334
  implementation: AdminAssistantPresenterImpl,
370
335
  dependencies: [
371
336
  AdminAssistantGateway,
372
- AiChatsRepository
337
+ AiChatsRepository,
338
+ AssistantPageContext
373
339
  ]
374
340
  });
375
341
  export { AdminAssistantPresenter_AdminAssistantPresenter as AdminAssistantPresenter };
@@ -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,kBAAkB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zD,IAAI,CAAC,MAAM,GAAGH;QACd,IAAI,CAAC,KAAK,GAAGG;IACjB;IAEQ,SAASH,MAAc,EAAQ;QACnC,IAAI,CAAC,MAAM,GAAGA;QACd,IAAI,CAAC,YAAY,GAAG;QACpB,IAAI,CAAC,WAAW,GAAG;IACvB;IAEQ,gBAAgBK,OAAe,EAAQ;QAC3C,IAAI,CAAC,YAAY,GAAGA;QACpB,IAAI,CAAC,WAAW,GAAG;IACvB;IAEQ,cAAcA,OAAe,EAAEI,OAA0B,EAAQ;QACrE,IAAI,CAAC,YAAY,GAAGJ;QACpB,IAAI,CAAC,WAAW,GAAGI;IACvB;IAEQ,oBAA0B;QAC9B,IAAI,CAAC,YAAY,GAAG;QACpB,IAAI,CAAC,WAAW,GAAG;IACvB;IAEQ,QAAc;QAClB,IAAI,CAAC,KAAK,GAAG,EAAE;QACf,IAAI,CAAC,IAAI,GAAG;QACZ,IAAI,CAAC,MAAM,GAAG;QACd,IAAI,CAAC,OAAO,GAAG;QACf,IAAI,CAAC,YAAY,GAAG;QACpB,IAAI,CAAC,WAAW,GAAG;IACvB;AACJ;AAEO,MAAMqB,kDAA0BC,wBAAAA,oBAAgC,CAAC;IACpE,gBAAgBlD;IAChB,cAAc;QAACmD;QAAuBC;KAAkB;AAC5D"}
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 { 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 { AssistantPageContext } from \"~/features/assistantPageContext/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 private pageContext: AssistantPageContext.Interface\n ) {\n // Machinery, not state anything renders, so keep them out of the map.\n makeAutoObservable<\n AdminAssistantPresenterImpl,\n \"controller\" | \"generation\" | \"chats\" | \"pageContext\"\n >(this, { controller: false, generation: false, chats: false, pageContext: false });\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.question(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.question(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 /**\n * A question, with whatever the screen behind the palette says about itself. Read at the moment\n * of asking, so a retry describes the screen the user is on now.\n */\n private question(prompt: string): AdminAssistantRequest {\n const request = this.request({ prompt });\n const pageContext = this.pageContext.get();\n if (pageContext) {\n request.pageContext = pageContext;\n }\n return request;\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, AssistantPageContext]\n});\n"],"names":["NOT_CONFIGURED","emptyTurn","question","AdminAssistantPresenterImpl","gateway","chats","pageContext","undefined","makeAutoObservable","vm","turn","view","trimmed","index","request","turnIndex","approved","approvals","approval","fresh","newest","chatId","generation","chat","turns","turnsFromMessages","error","message","messageOf","prompt","rest","resuming","controller","AbortController","existing","text","tools","completed","failed","separateFromExisting","event","failure","Error","String","i","change","busy","model","opening","AdminAssistantPresenter","Abstraction","AdminAssistantGateway","AiChatsRepository","AssistantPageContext"],"mappings":";;;;;;AAkBA,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,EAClCC,WAA2C,CACrD;aAHUF,OAAO,GAAPA;aACAC,KAAK,GAALA;aACAC,WAAW,GAAXA;aAjBJ,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;QAQjBC,mBAGE,IAAI,EAAE;YAAE,YAAY;YAAO,YAAY;YAAO,OAAO;YAAO,aAAa;QAAM;IACrF;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,SAAS;oBACzB,QAAQA,KAAK,MAAM;oBACnB,SAASA,KAAK,OAAO;oBACrB,kBAAkBA,KAAK,gBAAgB;oBACvC,WAAW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AAI,CAAC,WAAW,GAAG;IACvB;AACJ;AAEO,MAAMQ,kDAA0BC,wBAAAA,oBAAgC,CAAC;IACpE,gBAAgB/C;IAChB,cAAc;QAACgD;QAAuBC;QAAmBC;KAAqB;AAClF"}
@@ -1,8 +1,9 @@
1
1
  import type { AiChatSaveFailure } from "../../features/aiChats/abstractions.js";
2
+ import type { AiChatsRepository } from "../../features/aiChats/abstractions.js";
3
+ import type { AssistantPageContext } from "../../features/assistantPageContext/abstractions.js";
2
4
  /**
3
- * Messages are opaque here on purpose. Beyond plain user/assistant turns the server also returns
4
- * assistant and tool messages carrying approval requests, which must be replayed VERBATIM for the
5
- * agent loop to resume — the request exists nowhere else, since the server keeps no session.
5
+ * A message of a saved chat. Opaque on purpose: the admin only reads them to show an opened chat,
6
+ * and the server is the one that sends them to the model.
6
7
  */
7
8
  export type AdminAssistantMessage = {
8
9
  role: string;
@@ -27,10 +28,17 @@ export interface AdminAssistantDecision {
27
28
  approved: boolean;
28
29
  reason?: string;
29
30
  }
31
+ /**
32
+ * A question, or the decisions on the calls a run paused on. The server reads the rest of the
33
+ * conversation from the saved chat, so only its id is sent; without one, a question starts a chat.
34
+ */
30
35
  export interface AdminAssistantRequest {
31
- messages: AdminAssistantMessage[];
32
- /** Approve or reject calls the server paused on. */
36
+ chatId?: string;
37
+ prompt?: string;
38
+ /** Approve or reject calls the server paused on. Needs the `chatId` of the paused run. */
33
39
  approvals?: AdminAssistantDecision[];
40
+ /** What the user had on screen when they asked. Sent with questions only. */
41
+ pageContext?: AssistantPageContext.Data;
34
42
  }
35
43
  /**
36
44
  * What the assistant emits while it works. Mirrors the server's `AdminAssistantEvent`; declared here so the
@@ -58,9 +66,15 @@ export type AdminAssistantStreamEvent = {
58
66
  } | {
59
67
  type: "approval";
60
68
  approvals: AdminAssistantPendingApproval[];
69
+ } | {
70
+ type: "saved";
71
+ chat: AiChatsRepository.Summary;
72
+ } | {
73
+ type: "not-saved";
74
+ message: string;
75
+ retryable: boolean;
61
76
  } | {
62
77
  type: "done";
63
- messages: AdminAssistantMessage[];
64
78
  steps: number;
65
79
  } | {
66
80
  type: "error";
@@ -85,12 +99,7 @@ export declare namespace AdminAssistantGateway {
85
99
  type Request = AdminAssistantRequest;
86
100
  type StreamEvent = AdminAssistantStreamEvent;
87
101
  }
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
- */
102
+ /** One question and the answer to it, as the view needs it. */
94
103
  export interface AiTurnViewModel {
95
104
  question: string;
96
105
  /** Answer text so far. Grows as the stream arrives. */
@@ -136,17 +145,15 @@ export interface IAdminAssistantViewModel {
136
145
  /** A saved chat is being read. */
137
146
  opening: boolean;
138
147
  /**
139
- * Why the last save or open failed. The conversation on screen carries on either way; this is
140
- * only so the view can say it is not saved.
148
+ * Why the last run was not saved, or the last open failed. The conversation on screen carries
149
+ * on either way; this is only so the view can say it is not saved.
141
150
  */
142
151
  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
152
  /**
146
- * A turn waits on an approval, so no save runs until it is decided. Retrying a failed save
147
- * would do nothing, so the view can say the save follows the decision instead.
153
+ * Set when it was a run that was not saved, so the view can offer what fixes it. Null for an
154
+ * open.
148
155
  */
149
- savePaused: boolean;
156
+ saveFailure: AiChatSaveFailure | null;
150
157
  /**
151
158
  * The newest turn needs a model set up first. No question is taken until "Try again" (`retry`)
152
159
  * succeeds, so the view can stop taking input.
@@ -155,7 +162,10 @@ export interface IAdminAssistantViewModel {
155
162
  }
156
163
  export interface IAdminAssistantPresenter {
157
164
  readonly vm: IAdminAssistantViewModel;
158
- /** Ask a question, carrying the settled turns before it as context. Refused while `setupRequired`. */
165
+ /**
166
+ * Ask a question in the chat on screen. A change still waiting on a decision is rejected.
167
+ * Refused while `setupRequired`.
168
+ */
159
169
  ask(question: string): void;
160
170
  /** Approve or reject the calls a turn paused on, then resume it. */
161
171
  decide(turnIndex: number, approved: boolean): void;
@@ -163,10 +173,8 @@ export interface IAdminAssistantPresenter {
163
173
  reset(): void;
164
174
  /** Replace the conversation with a saved chat, so asking again continues it. */
165
175
  open(chatId: string): Promise<void>;
166
- /** Ask the newest question again, when its run failed. */
176
+ /** Ask the newest question again, when its run failed or was not saved. */
167
177
  retry(): void;
168
- /** Try the failed save again. */
169
- retrySave(): void;
170
178
  }
171
179
  export declare const AdminAssistantPresenter: import("@webiny/di").Abstraction<IAdminAssistantPresenter>;
172
180
  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 * Messages are opaque here on purpose. Beyond plain user/assistant turns the server also returns\n * assistant and tool messages carrying approval requests, which must be replayed VERBATIM for the\n * agent loop to resume — the request exists nowhere else, since the server keeps no session.\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\nexport interface AdminAssistantRequest {\n messages: AdminAssistantMessage[];\n /** Approve or reject calls the server paused on. */\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 | { type: \"done\"; messages: AdminAssistantMessage[]; 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/**\n * One question and the answer to it, as the view needs it.\n *\n * The server messages that make a follow-up or a resumed approval work are deliberately absent: they\n * are conversation state, not something rendered, so they stay inside the presenter.\n */\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 save or open failed. The conversation on screen carries on either way; this is\n * only so the view can say it is not saved.\n */\n storageError: string | null;\n /** Set when it was a save that failed, so the view can offer what fixes it. Null for an open. */\n saveFailure: AiChatSaveFailure | null;\n /**\n * A turn waits on an approval, so no save runs until it is decided. Retrying a failed save\n * would do nothing, so the view can say the save follows the decision instead.\n */\n savePaused: boolean;\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 /** Ask a question, carrying the settled turns before it as context. Refused while `setupRequired`. */\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. */\n retry(): void;\n /** Try the failed save again. */\n retrySave(): 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":";AAmEO,MAAMA,wBACTC,kBAA0C;AAkGvC,MAAMC,0BACTD,kBAA4C"}
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\";\nimport type { AssistantPageContext } from \"~/features/assistantPageContext/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 /** What the user had on screen when they asked. Sent with questions only. */\n pageContext?: AssistantPageContext.Data;\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":";AAgFO,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, with the messages that let the conversation carry on from it. */
4
- export interface RestoredTurn extends Omit<AiTurnViewModel, "needsSetup"> {
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, kept verbatim so a follow-up replays
12
- * exactly what was saved. The follow-up questions come from the call that suggested them, so a
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;