Skip to content

feat(automations): configurable per-agent config + reusable user templates - #5619

Open
Ptah-CT wants to merge 2 commits into
stablyai:mainfrom
Ptah-CT:pr/configurable-agents-templates
Open

Ptah-CT wants to merge 2 commits into
stablyai:mainfrom
Ptah-CT:pr/configurable-agents-templates

Conversation

@Ptah-CT

@Ptah-CT Ptah-CT commented Jun 17, 2026 •

Copy link
Copy Markdown
Contributor

What

Makes automations configurable per agent and adds reusable user templates:

  • Per-automation agent config: pick the agent model, extra launch args, and environment variables for an automation's runs (AutomationAgentConfigSection, shared automation-agent-config + automation-agent-launch + tui-agent-models).
  • User templates: save an automation's soft config (prompt, agent config, schedule shape) as a named, reusable template and apply it when creating new automations (AutomationTemplateSaveDialog, shared automation-user-templates, automation-user-template-draft).
  • Refactors the automation editor header/footer and the automations types to support both.
  • Adds external-automations-types to cleanly separate third-party-owned (Hermes/OpenClaw) automation jobs from Orca-owned ones.

Why

Different automations want different models/args/env, and teams re-create similar automations repeatedly. Agent config + user templates remove that friction.

Testing

  • pnpm run typecheck ✓ (exit 0)
  • Unit tests: agent-config, agent-launch, user-templates, tui-agent-models, automations service, persistence, editor components (431 tests) ✓

⚠️ Dependency

This is stacked on #5617 (webhook triggers) — it builds on the automations type/UI refactor introduced there. Please review/merge after #5617; until then this PR's diff will also show the webhook changes. Once #5617 merges into main, this diff narrows to just the agent-config + templates work.


Open in Stage

ELI5

Automations can now pick per-agent model, extra launch args, and env vars. You can also save an automation’s setup as a reusable template and apply it when creating new ones.

@coderabbitai

coderabbitai Bot commented Jun 17, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR adds three capabilities to Orca automations. First, automations can now be triggered by inbound HTTP webhooks: a configurable WebhookServer binds to a loopback or LAN address, rate-limits requests, verifies shared secrets via token or HMAC-SHA256, captures the request body as a webhookDelivery, and routes it through a new AutomationService.triggerWebhook path that creates a webhook-triggered run and appends the delivery body to the agent dispatch prompt. Second, each automation can carry per-automation agent launch overrides (agentConfig: model, CLI args, env) that are resolved against global defaults at run time. Third, users can save, apply, edit, and delete custom automation templates. All three features are wired through shared type contracts, Store persistence, OrcaRuntimeService, IPC channels, preload bridge, and renderer UI components including AutomationWebhookSection, AutomationAgentConfigSection, AutomationTemplateSaveDialog, and WebhookServerSetting.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 39.22% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The PR description covers summary, why, and tests, but it omits required template sections like Screenshots, AI Review Report, Security Audit, and Notes. Add the missing template sections with concise content, include screenshot notes, and format Testing as checklist items matching the repository template.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the main changes: per-agent configuration and reusable user templates for automations, which are the primary features introduced.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 8

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/main/persistence.ts (1)

4038-4043: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Restrict deduplication to scheduled runs only.

The current lookup deduplicates all triggers by (automationId, scheduledFor). For webhook/manual bursts, two distinct invocations in the same millisecond can collapse into one run and lose an event payload.

Proposed fix
   createAutomationRun(
     automation: Automation,
     scheduledFor: number,
     trigger: AutomationRunTrigger = 'scheduled',
     webhookDelivery: AutomationWebhookDelivery | null = null
   ): AutomationRun {
-    const existing = (this.state.automationRuns ?? []).find(
-      (run) => run.automationId === automation.id && run.scheduledFor === scheduledFor
-    )
-    if (existing) {
-      return existing
-    }
+    if (trigger === 'scheduled') {
+      const existing = (this.state.automationRuns ?? []).find(
+        (run) =>
+          run.automationId === automation.id &&
+          run.trigger === 'scheduled' &&
+          run.scheduledFor === scheduledFor
+      )
+      if (existing) {
+        return existing
+      }
+    }
src/renderer/src/i18n/locales/en.json (1)

10899-11198: ⚠️ Potential issue | 🟡 Minor

Use auto-keyed catalog entries instead of literal keys.

The locale strings added to AutomationEditorDialogHeader, AutomationsPage, AutomationProjectCombobox, AutomationAgentConfigSection, and AutomationTemplateSaveDialog use literal keys (editTemplate, deleteTemplate, search, configure, label, etc.) instead of SHA1 auto-keys. These should be generated via pnpm run sync:localization-catalog to maintain catalog consistency.

Source: Learnings

🧹 Nitpick comments (3)
src/main/persistence.test.ts (1)

1256-1280: ⚡ Quick win

Assert webhook delivery survives disk round-trip, not just in-memory state.

This test currently validates immediate return data only. Add store.flush() + reload assertions so it catches serialization regressions in automationRuns.

src/shared/automation-webhook.test.ts (1)

1-9: ⚡ Quick win

Add a focused test for content-type truncation.

captureWebhookDelivery caps contentType, but this suite currently only asserts body truncation. A small test here will lock in that limit behavior.

Suggested diff
 import {
   captureWebhookDelivery,
   composeAutomationDispatchPrompt,
   isWebhookTriggerEnabled,
   MAX_WEBHOOK_BODY_CHARS,
+  MAX_WEBHOOK_CONTENT_TYPE_CHARS,
   normalizeAutomationWebhookConfig
 } from './automation-webhook'
@@
   it('truncates and flags oversize bodies', () => {
     const big = 'x'.repeat(MAX_WEBHOOK_BODY_CHARS + 100)
     const d = captureWebhookDelivery({ body: big, contentType: null, receivedAt: 1 })
     expect(d.truncated).toBe(true)
     expect(d.body.length).toBe(MAX_WEBHOOK_BODY_CHARS)
   })
+
+  it('truncates oversized content-type headers', () => {
+    const longType = 'a'.repeat(MAX_WEBHOOK_CONTENT_TYPE_CHARS + 32)
+    const d = captureWebhookDelivery({ body: '{}', contentType: longType, receivedAt: 1 })
+    expect(d.contentType).toHaveLength(MAX_WEBHOOK_CONTENT_TYPE_CHARS)
+  })
 })

Also applies to: 59-80

src/renderer/src/components/automations/automation-agent-config-draft.ts (1)

52-54: ⚡ Quick win

Return a fresh agentEnv array in the null-config branch.

Line 53 uses a shallow spread of EMPTY_AGENT_CONFIG_DRAFT_FIELDS, so agentEnv reuses the same array reference. Returning a new array avoids accidental cross-draft mutation if any caller mutates in place.

Suggested patch
 export function agentConfigToDraftFields(
   config: AutomationAgentConfig | null | undefined
 ): AgentConfigDraftFields {
   if (!config) {
-    return { ...EMPTY_AGENT_CONFIG_DRAFT_FIELDS }
+    return { ...EMPTY_AGENT_CONFIG_DRAFT_FIELDS, agentEnv: [] }
   }
   return {

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 9e1777a9-00cb-424d-ad80-768694c3f226

📥 Commits

Reviewing files that changed from the base of the PR and between 2916f68 and 4d5a8f6.

📒 Files selected for processing (55)
  • src/main/automations/service.test.ts
  • src/main/automations/service.ts
  • src/main/index.ts
  • src/main/ipc/automations.ts
  • src/main/persistence.test.ts
  • src/main/persistence.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/rpc/methods/automations.ts
  • src/main/webhooks/webhook-rate-limiter.test.ts
  • src/main/webhooks/webhook-rate-limiter.ts
  • src/main/webhooks/webhook-secret.test.ts
  • src/main/webhooks/webhook-secret.ts
  • src/main/webhooks/webhook-server.test.ts
  • src/main/webhooks/webhook-server.ts
  • src/preload/api-types.ts
  • src/preload/index.ts
  • src/renderer/src/components/automations/AutomationAgentConfigSection.tsx
  • src/renderer/src/components/automations/AutomationEditorDialog.tsx
  • src/renderer/src/components/automations/AutomationEditorDialogFooter.tsx
  • src/renderer/src/components/automations/AutomationEditorDialogHeader.tsx
  • src/renderer/src/components/automations/AutomationEditorPromptSection.tsx
  • src/renderer/src/components/automations/AutomationSchedulePicker.test.ts
  • src/renderer/src/components/automations/AutomationTemplateSaveDialog.tsx
  • src/renderer/src/components/automations/AutomationWebhookSection.tsx
  • src/renderer/src/components/automations/AutomationsPage.tsx
  • src/renderer/src/components/automations/automation-agent-config-draft.test.ts
  • src/renderer/src/components/automations/automation-agent-config-draft.ts
  • src/renderer/src/components/automations/automation-user-template-draft.test.ts
  • src/renderer/src/components/automations/automation-user-template-draft.ts
  • src/renderer/src/components/settings/AdvancedPane.tsx
  • src/renderer/src/components/settings/WebhookServerSetting.tsx
  • src/renderer/src/hooks/useAutomationDispatchEvents.ts
  • src/renderer/src/i18n/locales/en.json
  • src/renderer/src/i18n/locales/es.json
  • src/renderer/src/i18n/locales/ja.json
  • src/renderer/src/i18n/locales/ko.json
  • src/renderer/src/i18n/locales/zh.json
  • src/renderer/src/lib/launch-agent-background-session.ts
  • src/shared/automation-agent-config.test.ts
  • src/shared/automation-agent-config.ts
  • src/shared/automation-agent-launch.test.ts
  • src/shared/automation-agent-launch.ts
  • src/shared/automation-run-status.ts
  • src/shared/automation-user-templates.test.ts
  • src/shared/automation-user-templates.ts
  • src/shared/automation-webhook.test.ts
  • src/shared/automation-webhook.ts
  • src/shared/automations-types.ts
  • src/shared/constants.test.ts
  • src/shared/constants.ts
  • src/shared/external-automations-types.ts
  • src/shared/tui-agent-launch-defaults.ts
  • src/shared/tui-agent-models.test.ts
  • src/shared/tui-agent-models.ts
  • src/shared/types.ts

Comment on lines +107 to +110
if (!isWebhookTriggerEnabled(automation)) {
throw new Error('Webhook trigger is not enabled for this automation.')
}
const run = this.store.createAutomationRun(automation, Date.now(), 'webhook', delivery)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Respect disabled automations before accepting webhook triggers.

triggerWebhook() only checks automation.webhook.enabled, so an automation with enabled: false and a still-enabled webhook can still create and dispatch runs. Scheduled runs already honor automation.enabled; webhook triggers should use the same kill switch for external invocations.

Proposed fix
-    if (!isWebhookTriggerEnabled(automation)) {
+    if (!automation.enabled) {
+      throw new Error('Automation is disabled.')
+    }
+    if (!isWebhookTriggerEnabled(automation)) {
       throw new Error('Webhook trigger is not enabled for this automation.')
     }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (!isWebhookTriggerEnabled(automation)) {
throw new Error('Webhook trigger is not enabled for this automation.')
}
const run = this.store.createAutomationRun(automation, Date.now(), 'webhook', delivery)
if (!automation.enabled) {
throw new Error('Automation is disabled.')
}
if (!isWebhookTriggerEnabled(automation)) {
throw new Error('Webhook trigger is not enabled for this automation.')
}
const run = this.store.createAutomationRun(automation, Date.now(), 'webhook', delivery)

Comment on lines +50 to +57
const AutomationWebhook = z
.object({
enabled: z.boolean(),
secretMode: z.enum(['none', 'token', 'hmac_sha256']),
secret: z.union([z.string(), z.null()])
})
.nullable()
.optional()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Enforce non-empty secrets for authenticated webhook modes.

AutomationWebhook currently accepts secret: '' for token / hmac_sha256. That makes webhook auth trivially guessable. Add a cross-field check requiring a non-empty secret when authenticated modes are used.

Suggested fix
 const AutomationWebhook = z
   .object({
     enabled: z.boolean(),
     secretMode: z.enum(['none', 'token', 'hmac_sha256']),
     secret: z.union([z.string(), z.null()])
   })
+  .superRefine((value, ctx) => {
+    if (
+      value.enabled &&
+      value.secretMode !== 'none' &&
+      (value.secret === null || value.secret.trim().length === 0)
+    ) {
+      ctx.addIssue({
+        code: 'custom',
+        path: ['secret'],
+        message: 'Missing webhook secret for authenticated mode'
+      })
+    }
+  })
   .nullable()
   .optional()

Comment on lines 1200 to +1207
scheduleWarning:
schedule || hasCustomSchedule
? null
: 'This automation has an unsupported saved schedule. Pick a supported schedule before saving changes.'
: 'This automation has an unsupported saved schedule. Pick a supported schedule before saving changes.',
webhookEnabled: latest.webhook?.enabled ?? false,
webhookSecretMode: latest.webhook?.secretMode ?? 'none',
webhookSecret: latest.webhook?.secret ?? '',
...agentConfigToDraftFields(latest.agentConfig)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Localize scheduleWarning strings instead of hardcoding English

The newly assigned warning messages are hardcoded and can leak untranslated copy in non-English flows. Use translate(...) for both assignments.

Suggested patch
-      scheduleWarning:
-        schedule || hasCustomSchedule
-          ? null
-          : 'This automation has an unsupported saved schedule. Pick a supported schedule before saving changes.',
+      scheduleWarning:
+        schedule || hasCustomSchedule
+          ? null
+          : translate(
+              'auto.components.automations.AutomationsPage.unsupportedSavedSchedule',
+              'This automation has an unsupported saved schedule. Pick a supported schedule before saving changes.'
+            ),
...
-      scheduleWarning: hasCustomSchedule
-        ? null
-        : 'This Hermes automation has an unsupported saved schedule. Pick a supported schedule before saving changes.',
+      scheduleWarning: hasCustomSchedule
+        ? null
+        : translate(
+            'auto.components.automations.AutomationsPage.unsupportedHermesSavedSchedule',
+            'This Hermes automation has an unsupported saved schedule. Pick a supported schedule before saving changes.'
+          ),

Also applies to: 1251-1254

Comment on lines +37 to +55
if (!automationId) {
return { url: null, hint: 'Save the automation to get its webhook URL.' }
}
if (!endpoint || !endpoint.running) {
return {
url: null,
hint: 'Enable the webhook receiver in Settings → Automations to get a URL.'
}
}
// Why: a 0.0.0.0 bind has no usable host in a URL; show a placeholder the
// user replaces with the machine's reachable address/hostname.
const host = endpoint.bindAddress === '0.0.0.0' ? 'YOUR-HOST' : endpoint.bindAddress
return {
url: `http://${host}:${endpoint.port}/webhook/${automationId}`,
hint:
endpoint.bindAddress === '0.0.0.0'
? 'Replace YOUR-HOST with this machine’s address reachable by the sender.'
: 'Point your provider’s webhook at this URL (POST).'
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Localize webhook readiness hints shown to users.

Line 38, Line 43, Line 53, and Line 54 return user-visible English strings directly. These bypass translations while the rest of this component is localized, so non-English users will see mixed-language UI.

Proposed fix
 function resolveWebhookUrl(
   endpoint: WebhookServerEndpoint | null,
   automationId: string | null
 ): { url: string | null; hint: string } {
   if (!automationId) {
-    return { url: null, hint: 'Save the automation to get its webhook URL.' }
+    return {
+      url: null,
+      hint: translate(
+        'auto.components.automations.AutomationWebhookSection.webhookUrlNeedsSave',
+        'Save the automation to get its webhook URL.'
+      )
+    }
   }
   if (!endpoint || !endpoint.running) {
     return {
       url: null,
-      hint: 'Enable the webhook receiver in Settings → Automations to get a URL.'
+      hint: translate(
+        'auto.components.automations.AutomationWebhookSection.webhookUrlNeedsReceiver',
+        'Enable the webhook receiver in Settings → Automations to get a URL.'
+      )
     }
   }
@@
   return {
     url: `http://${host}:${endpoint.port}/webhook/${automationId}`,
     hint:
       endpoint.bindAddress === '0.0.0.0'
-        ? 'Replace YOUR-HOST with this machine’s address reachable by the sender.'
-        : 'Point your provider’s webhook at this URL (POST).'
+        ? translate(
+            'auto.components.automations.AutomationWebhookSection.webhookUrlReplaceHost',
+            'Replace YOUR-HOST with this machine’s address reachable by the sender.'
+          )
+        : translate(
+            'auto.components.automations.AutomationWebhookSection.webhookUrlReady',
+            'Point your provider’s webhook at this URL (POST).'
+          )
   }
 }

Comment on lines +197 to +200
{!showSecret &&
webhookEndpoint?.running &&
webhookEndpoint.bindAddress !== '127.0.0.1' ? (
<p className="text-xs text-destructive">

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify the bindAddress domain and where it is validated/normalized.
# Expected: either only 127.0.0.1/0.0.0.0 are permitted, or this UI check should be broadened.

fd -i 'WebhookServerSetting.tsx'
fd -i 'types.ts'
fd -i 'automations-types.ts'
fd -i 'webhook-server.ts'
fd -i 'persistence.ts'

rg -n -C3 "bindAddress|WebhookServerSettings|WebhookServerEndpoint|normalizeWebhookServerSettings|127\\.0\\.0\\.1|0\\.0\\.0\\.0|::1|localhost" src

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

# Get the exact code at lines 197-200 and surrounding context in AutomationWebhookSection.tsx
find src/renderer/src/components/automations -name 'AutomationWebhookSection.tsx' -exec wc -l {} \;
head -210 src/renderer/src/components/automations/AutomationWebhookSection.tsx | tail -30

Repository: stablyai/orca

Length of output: 1322


🏁 Script executed:

# Check the WebhookServerSetting component for any validation on bindAddress input
cat src/renderer/src/components/settings/WebhookServerSetting.tsx

Repository: stablyai/orca

Length of output: 5647


Broaden loopback detection to include localhost and IPv6 loopback.

The warning at lines 197–200 only checks bindAddress !== '127.0.0.1' and treats all other addresses as non-local, but the settings UI accepts any free-form string (including localhost and ::1, which are valid loopback addresses). The normalization function does not convert these to 127.0.0.1, so the warning will incorrectly fire for legitimate local-only bindings. Either:

  • Validate/normalize localhost and ::1 to 127.0.0.1 before the warning check, or
  • Extend the check to recognize all loopback patterns (e.g., ^(localhost|127\.|::1)$).

Comment on lines +47 to +56
const title = 'Webhooks'
const description = 'Receive inbound webhooks that trigger automations.'

return (
<section className="space-y-3">
<SettingsSubsectionHeader title={title} description={description} />
<SearchableSetting
title={title}
description={description}
keywords={['webhook', 'automation', 'trigger', 'http', 'receiver']}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Translate the section header copy for locale consistency

title and description are hardcoded while adjacent UI strings use translate(...). Localize these two constants as well.

Suggested patch
-  const title = 'Webhooks'
-  const description = 'Receive inbound webhooks that trigger automations.'
+  const title = translate('auto.components.settings.WebhookServerSetting.sectionTitle', 'Webhooks')
+  const description = translate(
+    'auto.components.settings.WebhookServerSetting.sectionDescription',
+    'Receive inbound webhooks that trigger automations.'
+  )
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const title = 'Webhooks'
const description = 'Receive inbound webhooks that trigger automations.'
return (
<section className="space-y-3">
<SettingsSubsectionHeader title={title} description={description} />
<SearchableSetting
title={title}
description={description}
keywords={['webhook', 'automation', 'trigger', 'http', 'receiver']}
const title = translate('auto.components.settings.WebhookServerSetting.sectionTitle', 'Webhooks')
const description = translate(
'auto.components.settings.WebhookServerSetting.sectionDescription',
'Receive inbound webhooks that trigger automations.'
)
return (
<section className="space-y-3">
<SettingsSubsectionHeader title={title} description={description} />
<SearchableSetting
title={title}
description={description}
keywords={['webhook', 'automation', 'trigger', 'http', 'receiver']}

Comment on lines +66 to +67
if (typeof record.id !== 'string' || !record.id) {
return null

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Reject whitespace-only template IDs in normalization.

Line 66 currently accepts IDs like ' '. Since this function is the load-time structural gate, treat trimmed-empty IDs as invalid to avoid persisting unusable identifiers.

💡 Proposed fix
-  if (typeof record.id !== 'string' || !record.id) {
+  if (typeof record.id !== 'string' || record.id.trim().length === 0) {
     return null
   }
+  const id = record.id.trim()
   const createdAt = typeof record.createdAt === 'number' ? record.createdAt : 0
   return buildUserAutomationTemplate(
@@
     {
-      id: record.id,
+      id,
       createdAt,
       now: typeof record.updatedAt === 'number' ? record.updatedAt : createdAt
     }
   )

Comment on lines +48 to +61
const trimmedModel = (model ?? '').trim()
if (!trimmedModel) {
return args
}
const info = getAgentModelInfo(agent)
if (!info) {
return args
}
if (argContainsFlag(args, info.flag)) {
return args
}
const base = args.trim()
const suffix = `${info.flag} ${trimmedModel}`
return base ? `${base} ${suffix}` : suffix

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Prevent model text from becoming extra CLI arguments.

At Line 60, trimmedModel is concatenated raw; whitespace in model input (for example, opus --foo) is treated as additional flags. Model should be constrained to a single token before appending.

Suggested patch
 export function applyAgentModelToArgs(
   agent: TuiAgent,
   args: string,
   model: string | null | undefined
 ): string {
   const trimmedModel = (model ?? '').trim()
   if (!trimmedModel) {
     return args
   }
+  if (/\s/.test(trimmedModel)) {
+    return args
+  }
   const info = getAgentModelInfo(agent)
   if (!info) {
     return args
   }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const trimmedModel = (model ?? '').trim()
if (!trimmedModel) {
return args
}
const info = getAgentModelInfo(agent)
if (!info) {
return args
}
if (argContainsFlag(args, info.flag)) {
return args
}
const base = args.trim()
const suffix = `${info.flag} ${trimmedModel}`
return base ? `${base} ${suffix}` : suffix
export function applyAgentModelToArgs(
agent: TuiAgent,
args: string,
model: string | null | undefined
): string {
const trimmedModel = (model ?? '').trim()
if (!trimmedModel) {
return args
}
if (/\s/.test(trimmedModel)) {
return args
}
const info = getAgentModelInfo(agent)
if (!info) {
return args
}
if (argContainsFlag(args, info.flag)) {
return args
}
const base = args.trim()
const suffix = `${info.flag} ${trimmedModel}`
return base ? `${base} ${suffix}` : suffix
}

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants