Skip to content

Commit

Permalink
move the principal out of the bot model (#7146)
Browse files Browse the repository at this point in the history
  • Loading branch information
julianjelfs authored Jan 3, 2025
1 parent c088916 commit 38b1bfa
Show file tree
Hide file tree
Showing 32 changed files with 81 additions and 40 deletions.
13 changes: 9 additions & 4 deletions frontend/app/src/components/bots/AutoBotBuilder.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,15 @@
onUpdate: (bot: ExternalBot) => void;
candidate: ExternalBot;
nameDirty: boolean;
principal: string;
mode: "register" | "update";
}
let {
valid = $bindable(),
schemaLoaded = $bindable(),
onUpdate,
principal = $bindable(),
candidate,
nameDirty,
mode,
Expand All @@ -56,9 +58,9 @@
let errors = $derived.by(
debouncedDerived(
() => [$state.snapshot(candidate)],
() => [$state.snapshot(candidate), principal],
async () => {
const errors = validateBot(candidate, mode);
const errors = validateBot(principal, candidate, mode);
if (errors.get("bot_name").length == 0 && nameDirty) {
errors.addErrors("bot_name", await checkUsername(candidate.name));
}
Expand Down Expand Up @@ -182,15 +184,18 @@
</div>

{#if mode === "register"}
<Legend required label={i18nKey("bots.builder.principalLabel")}></Legend>
<Legend
required
label={i18nKey("bots.builder.principalLabel")}
rules={i18nKey("bots.builder.principalRules")}></Legend>
<ValidatingInput
autofocus
minlength={3}
maxlength={100}
invalid={errors.has("bot_principal")}
placeholder={i18nKey("bots.builder.principalPlaceholder")}
error={errors.get("bot_principal")}
bind:value={candidate.principal}>
bind:value={principal}>
</ValidatingInput>
{/if}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,15 @@
onUpdate: (bot: ExternalBot) => void;
schemaLoaded: boolean;
valid: boolean;
principal: string;
}
let { valid = $bindable(), schemaLoaded = $bindable(), onUpdate }: Props = $props();
let {
valid = $bindable(),
schemaLoaded = $bindable(),
onUpdate,
principal = $bindable(),
}: Props = $props();
let candidate = $state(emptyBotInstance($currentUser.userId));
</script>
Expand All @@ -20,6 +26,7 @@
{candidate}
bind:valid
bind:schemaLoaded
bind:principal
{onUpdate}
nameDirty={true}
mode={"register"} />
5 changes: 3 additions & 2 deletions frontend/app/src/components/bots/BotBuilder.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
}
let { valid = $bindable(), onUpdate }: Props = $props();
let principal = $state("");
let selectedCommand = $state<SlashCommandSchema | undefined>(undefined);
let selectedCommandIndex = $state<number | undefined>(undefined);
let debug = $state(false);
Expand All @@ -40,7 +41,7 @@
debouncedDerived(
() => [$state.snapshot(candidate)],
async () => {
const errors = validateBot(candidate, "register");
const errors = validateBot(principal, candidate, "register");
if (errors.get("bot_name").length == 0) {
errors.addErrors("bot_name", await checkUsername(candidate.name));
}
Expand Down Expand Up @@ -144,7 +145,7 @@
invalid={errors.has("bot_principal")}
placeholder={i18nKey("bots.builder.principalPlaceholder")}
error={errors.get("bot_principal")}
bind:value={candidate.id}>
bind:value={principal}>
</ValidatingInput>

<Legend
Expand Down
6 changes: 4 additions & 2 deletions frontend/app/src/components/bots/BotBuilderModal.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
let { onClose, mode = "register" }: Props = $props();
let principal = $state("");
let valid = $state(false);
let schemaLoaded = $state(false);
let busy = $state(false);
Expand Down Expand Up @@ -55,7 +56,7 @@
busy = true;
const snapshot = $state.snapshot(botState.current);
client
.registerBot({
.registerBot(principal, {
...snapshot,
ownerId: $currentUser.userId,
})
Expand Down Expand Up @@ -156,7 +157,8 @@
candidate={botState.current}
onUpdate={(b) => (botState.current = b)}
bind:schemaLoaded
bind:valid />
bind:valid
bind:principal />
{/if}
</div>
<div class="footer" slot="footer">
Expand Down
6 changes: 4 additions & 2 deletions frontend/app/src/components/home/MakeProposalModal.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@
let candidateBot: ExternalBot = emptyBotInstance($currentUser.userId);
let candidateBotValid = false;
let botSchemaLoaded = false;
let botPrincipal = "";
$: errorMessage =
error !== undefined ? i18nKey("proposal.maker." + error) : $pinNumberErrorMessageStore;
Expand Down Expand Up @@ -325,9 +326,9 @@
}
return {
kind: "execute_generic_nervous_system_function",
functionId: BigInt(1012),
functionId: BigInt(4004),
payload: createRegisterExternalBotPayload(
$user.userId,
botPrincipal,
$user.userId,
candidateBot,
),
Expand Down Expand Up @@ -515,6 +516,7 @@
{#if selectedProposalType === "register_bot"}
<BotBuilder
onUpdate={(bot) => (candidateBot = bot)}
bind:principal={botPrincipal}
bind:schemaLoaded={botSchemaLoaded}
bind:valid={candidateBotValid} />
{:else if selectedProposalType === "transfer_sns_funds"}
Expand Down
1 change: 1 addition & 0 deletions frontend/app/src/i18n/ar.json
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,7 @@
"permScopeThread": "خيط",
"principalLabel": "رئيسي",
"principalPlaceholder": "أدخل رئيس البوت",
"principalRules": "سيكون هذا هو canisterID لروبوت onchain",
"required": "المعلمة المطلوبة",
"requiredDesc": "هل هذه معلمة مطلوبة للأمر",
"title": "بناء بوت",
Expand Down
1 change: 1 addition & 0 deletions frontend/app/src/i18n/cn.json
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,7 @@
"permScopeThread": "线",
"principalLabel": "主要的",
"principalPlaceholder": "输入机器人主体",
"principalRules": "这将是链上机器人的 canisterID",
"required": "必需参数",
"requiredDesc": "这是命令的必需参数吗",
"title": "构建机器人",
Expand Down
1 change: 1 addition & 0 deletions frontend/app/src/i18n/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,7 @@
"permScopeThread": "Faden",
"principalLabel": "Rektor",
"principalPlaceholder": "Geben Sie den Bot-Hauptbenutzer ein",
"principalRules": "Dies ist die CanisterID für einen Onchain-Bot",
"required": "Erforderlicher Parameter",
"requiredDesc": "Ist dies ein erforderlicher Parameter für den Befehl",
"title": "Einen Bot erstellen",
Expand Down
5 changes: 3 additions & 2 deletions frontend/app/src/i18n/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -179,14 +179,14 @@
"descLabel": "Bot description",
"descPlaceholder": "Enter bot description",
"endpointLabel": "Bot endpoint",
"endpointRules": "Must be a valid origin or a canisterID",
"endpointRules": "Must be a valid origin",
"errors": {
"alphaOnly": "Must only contain alphanumerics and underscores",
"botNameInvalid": "This bot name is invalid",
"duplicateCommands": "Bot contains duplicate commands",
"duplicateName": "That bot name is already taken",
"duplicateParams": "Command contains duplicate params",
"endpoint": "Endpoint must be a valid origin or canisterID",
"endpoint": "Endpoint must be a valid origin",
"minLength": "Must have at least {n} characters",
"nameCheckError": "There was an error checking the bot name",
"noCommands": "A bot must contain at least one command",
Expand Down Expand Up @@ -224,6 +224,7 @@
"permScopeThread": "Thread",
"principalLabel": "Principal",
"principalPlaceholder": "Enter bot principal",
"principalRules": "This will be the canisterID for an onchain bot",
"required": "Required parameter",
"requiredDesc": "Is this a required parameter for the command",
"title": "Build a bot",
Expand Down
1 change: 1 addition & 0 deletions frontend/app/src/i18n/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,7 @@
"permScopeThread": "Hilo",
"principalLabel": "Principal",
"principalPlaceholder": "Ingresar el bot principal",
"principalRules": "Este será el canisterID para un bot en cadena",
"required": "Parámetro requerido",
"requiredDesc": "¿Es este un parámetro obligatorio para el comando?",
"title": "Construir un bot",
Expand Down
1 change: 1 addition & 0 deletions frontend/app/src/i18n/fa.json
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,7 @@
"permScopeThread": "موضوع",
"principalLabel": "اصلی",
"principalPlaceholder": "اصل ربات را وارد کنید",
"principalRules": "این شناسه canister برای یک ربات onchain خواهد بود",
"required": "پارامتر مورد نیاز",
"requiredDesc": "آیا این یک پارامتر لازم برای دستور است؟",
"title": "یک ربات بسازید",
Expand Down
1 change: 1 addition & 0 deletions frontend/app/src/i18n/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,7 @@
"permScopeThread": "Fil",
"principalLabel": "Principal",
"principalPlaceholder": "Entrez le principal du bot",
"principalRules": "Ce sera le canisterID pour un bot onchain",
"required": "Paramètre obligatoire",
"requiredDesc": "Est-ce un paramètre obligatoire pour la commande",
"title": "Construire un bot",
Expand Down
1 change: 1 addition & 0 deletions frontend/app/src/i18n/hi.json
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,7 @@
"permScopeThread": "धागा",
"principalLabel": "प्रधानाचार्य",
"principalPlaceholder": "बॉट प्रिंसिपल दर्ज करें",
"principalRules": "यह ऑनचेन बॉट के लिए कैनिस्टरआईडी होगी",
"required": "आवश्यक पैरामीटर",
"requiredDesc": "क्या यह कमांड के लिए आवश्यक पैरामीटर है",
"title": "एक बॉट बनाएँ",
Expand Down
1 change: 1 addition & 0 deletions frontend/app/src/i18n/it.json
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,7 @@
"permScopeThread": "Filo",
"principalLabel": "Principale",
"principalPlaceholder": "Inserisci il bot principale",
"principalRules": "Questo sarà il canisterID per un bot onchain",
"required": "Parametro obbligatorio",
"requiredDesc": "Questo è un parametro obbligatorio per il comando",
"title": "Costruisci un bot",
Expand Down
1 change: 1 addition & 0 deletions frontend/app/src/i18n/iw.json
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,7 @@
"permScopeThread": "פְּתִיל",
"principalLabel": "קֶרֶן",
"principalPlaceholder": "הכנס למנהל הבוט",
"principalRules": "זה יהיה ה-canisterID עבור בוט onchain",
"required": "פרמטר נדרש",
"requiredDesc": "האם זה פרמטר נדרש עבור הפקודה",
"title": "בנה בוט",
Expand Down
1 change: 1 addition & 0 deletions frontend/app/src/i18n/jp.json
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,7 @@
"permScopeThread": "",
"principalLabel": "主要",
"principalPlaceholder": "ボットプリンシパルを入力",
"principalRules": "これはオンチェーンボットのcanisterIDになります",
"required": "必須パラメータ",
"requiredDesc": "これはコマンドの必須パラメータですか",
"title": "ボットを構築する",
Expand Down
1 change: 1 addition & 0 deletions frontend/app/src/i18n/pl.json
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,7 @@
"permScopeThread": "Nitka",
"principalLabel": "Główny",
"principalPlaceholder": "Wprowadź dane bota",
"principalRules": "Będzie to identyfikator kanistra dla bota onchain",
"required": "Wymagany parametr",
"requiredDesc": "Czy jest to wymagany parametr dla polecenia?",
"title": "Zbuduj bota",
Expand Down
1 change: 1 addition & 0 deletions frontend/app/src/i18n/ru.json
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,7 @@
"permScopeThread": "Нить",
"principalLabel": "Главный",
"principalPlaceholder": "Введите принципала бота",
"principalRules": "Это будет canisterID для ончейн-бота.",
"required": "Обязательный параметр",
"requiredDesc": "Является ли это обязательным параметром для команды?",
"title": "Создать бота",
Expand Down
1 change: 1 addition & 0 deletions frontend/app/src/i18n/uk.json
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,7 @@
"permScopeThread": "Нитка",
"principalLabel": "Директор",
"principalPlaceholder": "Введіть принципала бота",
"principalRules": "Це буде canisterID для ончейн-бота",
"required": "Обов'язковий параметр",
"requiredDesc": "Чи є це обов'язковим параметром для команди",
"title": "Створіть бота",
Expand Down
1 change: 1 addition & 0 deletions frontend/app/src/i18n/vi.json
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,7 @@
"permScopeThread": "Chủ đề",
"principalLabel": "Hiệu trưởng",
"principalPlaceholder": "Nhập bot chính",
"principalRules": "Đây sẽ là canisterID cho một bot onchain",
"required": "Tham số bắt buộc",
"requiredDesc": "Đây có phải là tham số bắt buộc cho lệnh không?",
"title": "Xây dựng một bot",
Expand Down
1 change: 0 additions & 1 deletion frontend/app/src/utils/sns.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ function createTestBot(): ExternalBot {
name: "test_bot",
avatarUrl: "avatar_url",
id: "bot_id",
principal: "",
ownerId: "owner_id",
endpoint: "https://my_bot",
definition: {
Expand Down
4 changes: 2 additions & 2 deletions frontend/app/src/utils/sns.ts
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ function createPermissions(perm: SlashCommandPermissions): Record<string, any> {
}

export function createRegisterExternalBotPayload(
userId: string,
principal: string,
ownerId: string,
candidate: ExternalBot,
): Uint8Array {
Expand All @@ -302,7 +302,7 @@ export function createRegisterExternalBotPayload(
],
[
{
principal: Principal.fromText(userId),
principal: Principal.fromText(principal),
endpoint: candidate.endpoint,
owner: Principal.fromText(ownerId),
name: candidate.name,
Expand Down
4 changes: 2 additions & 2 deletions frontend/openchat-agent/src/services/openchatAgent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4055,9 +4055,9 @@ export class OpenChatAgent extends EventTarget {
return this._userIndexClient.exploreBots(searchTerm, pageIndex, pageSize);
}

registerBot(bot: ExternalBot): Promise<boolean> {
registerBot(principal: string, bot: ExternalBot): Promise<boolean> {
if (offline()) return Promise.resolve(false);
return this._userIndexClient.registerBot(bot);
return this._userIndexClient.registerBot(principal, bot);
}

updateRegisteredBot(
Expand Down
1 change: 0 additions & 1 deletion frontend/openchat-agent/src/services/userIndex/mappers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,6 @@ export function botSchema(
return {
kind: "external_bot",
id: botId,
principal: "",
name: bot.name,
avatarUrl: mapOptional(
bot.avatar_id,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -636,11 +636,11 @@ export class UserIndexClient extends CandidService {
);
}

registerBot(bot: ExternalBot): Promise<boolean> {
registerBot(principal: string, bot: ExternalBot): Promise<boolean> {
return this.executeMsgpackUpdate(
"register_bot",
{
principal: principalStringToBytes(bot.principal),
principal: principalStringToBytes(principal),
owner: principalStringToBytes(bot.ownerId),
name: bot.name,
avatar: mapOptional(bot.avatarUrl, identity),
Expand Down
3 changes: 2 additions & 1 deletion frontend/openchat-client/src/openchat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4686,9 +4686,10 @@ export class OpenChat extends EventTarget {
: this.getUser(this.#referralCode);
}

registerBot(bot: ExternalBot): Promise<boolean> {
registerBot(principal: string, bot: ExternalBot): Promise<boolean> {
return this.#sendRequest({
kind: "registerBot",
principal,
bot,
}).catch((err) => {
this.#logger.error("Failed to register bot: ", err);
Expand Down
6 changes: 6 additions & 0 deletions frontend/openchat-client/src/utils/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,12 @@ export function activeUserIdFromEvent(event: ChatEvent): string | undefined {
return event.updatedBy;
case "users_invited":
return event.invitedBy;
case "bot_updated":
return event.updatedBy;
case "bot_added":
return event.addedBy;
case "bot_removed":
return event.removedBy;
case "aggregate_common_events":
case "chat_frozen":
case "chat_unfrozen":
Expand Down
2 changes: 0 additions & 2 deletions frontend/openchat-client/src/utils/testBots.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,6 @@ export const testBots: Bot[] = [
avatarUrl:
"https://images.unsplash.com/photo-1529778873920-4da4926a72c2?fm=jpg&q=60&w=3000&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxleHBsb3JlLWZlZWR8NXx8fGVufDB8fHx8fA%3D%3D",
id: "bot_one",
principal: "",
ownerId: "",
endpoint: "https://some_bot_or_other",
definition: {
Expand All @@ -202,7 +201,6 @@ export const testBots: Bot[] = [
avatarUrl:
"https://t3.ftcdn.net/jpg/02/74/06/48/360_F_274064877_Tuq84kGOn5nhyIJeUFTUSvXaSeedAOTT.jpg",
id: "bot_two",
principal: "",
ownerId: "",
endpoint: "http://localhost:3000/execute",
definition: {
Expand Down
Loading

0 comments on commit 38b1bfa

Please sign in to comment.