Repository navigation
Mattermost: add interactive model picker - #38767
Conversation
Greptile SummaryThis PR adds a Telegram-style interactive model picker to Mattermost for Key changes:
Notable concern: In the Confidence Score: 3/5
Last reviewed commit: c386768 |
| await runModelPickerCommand({ | ||
| commandText: `/model ${targetModelRef}`, | ||
| route, | ||
| channelId: params.payload.channel_id, | ||
| senderId: params.payload.user_id, | ||
| senderName: params.userName, | ||
| kind, | ||
| chatType, | ||
| channelName, | ||
| channelDisplay, | ||
| roomLabel, | ||
| teamId, | ||
| postId: params.payload.post_id, | ||
| deliverReplies: true, | ||
| }); | ||
| const updatedModel = resolveMattermostModelPickerCurrentModel({ | ||
| cfg, | ||
| route, | ||
| data, | ||
| }); | ||
| const view = renderMattermostModelsPickerView({ | ||
| ownerUserId: pickerState.ownerUserId, | ||
| data, | ||
| provider: pickerState.provider, | ||
| page: pickerState.page, | ||
| currentModel: updatedModel, | ||
| }); | ||
|
|
||
| return await updateModelPickerPost({ | ||
| channelId: params.payload.channel_id, | ||
| postId: params.payload.post_id, | ||
| message: view.text, | ||
| buttons: view.buttons, | ||
| }); |
There was a problem hiding this comment.
select action blocks HTTP response during full command dispatch
handleModelPickerInteraction is called synchronously from createMattermostInteractionHandler, and for the select action it awaits the full command dispatch pipeline (including a new sendMessageMattermost network call and a updateMattermostPost API call) before the HTTP response is sent. Mattermost closes interaction callbacks with an error after ~3 seconds.
While /model selection is typically fast (no LLM call), it still runs through withReplyDispatcher and dispatchReplyFromConfig, and the confirmation message requires a Mattermost API round-trip. Under slow disk, congested network, or session-store contention, this chain can exceed the timeout, causing the button click to appear as failed in the UI even though the model was actually changed.
Consider responding to Mattermost with {} immediately (before awaiting runModelPickerCommand) and performing the command dispatch + post update in a detached async task — matching the pattern already used by dispatchButtonClick in the generic handler path:
// Return early to Mattermost, then process asynchronously
if (pickerState.action === "select") {
const targetModelRef = `${pickerState.provider}/${pickerState.model}`;
if (!buildMattermostAllowedModelRefs(data).has(targetModelRef)) {
return { ephemeral_text: `That model is no longer available: ${targetModelRef}` };
}
// Kick off async, don't block the HTTP response
void (async () => {
await runModelPickerCommand({ ..., deliverReplies: true });
const updatedModel = resolveMattermostModelPickerCurrentModel({ ... });
const view = renderMattermostModelsPickerView({ ... });
await updateModelPickerPost({ ... });
})().catch((err) => runtime.error?.(`model picker select failed: ${String(err)}`));
return {}; // Acknowledge immediately
}Prompt To Fix With AI
This is a comment left during a code review.
Path: extensions/mattermost/src/mattermost/monitor.ts
Line: 1058-1091
Comment:
**`select` action blocks HTTP response during full command dispatch**
`handleModelPickerInteraction` is called synchronously from `createMattermostInteractionHandler`, and for the `select` action it awaits the full command dispatch pipeline (including a new `sendMessageMattermost` network call and a `updateMattermostPost` API call) before the HTTP response is sent. Mattermost closes interaction callbacks with an error after ~3 seconds.
While `/model` selection is typically fast (no LLM call), it still runs through `withReplyDispatcher` and `dispatchReplyFromConfig`, and the confirmation message requires a Mattermost API round-trip. Under slow disk, congested network, or session-store contention, this chain can exceed the timeout, causing the button click to appear as failed in the UI even though the model was actually changed.
Consider responding to Mattermost with `{}` immediately (before awaiting `runModelPickerCommand`) and performing the command dispatch + post update in a detached async task — matching the pattern already used by `dispatchButtonClick` in the generic handler path:
```typescript
// Return early to Mattermost, then process asynchronously
if (pickerState.action === "select") {
const targetModelRef = `${pickerState.provider}/${pickerState.model}`;
if (!buildMattermostAllowedModelRefs(data).has(targetModelRef)) {
return { ephemeral_text: `That model is no longer available: ${targetModelRef}` };
}
// Kick off async, don't block the HTTP response
void (async () => {
await runModelPickerCommand({ ..., deliverReplies: true });
const updatedModel = resolveMattermostModelPickerCurrentModel({ ... });
const view = renderMattermostModelsPickerView({ ... });
await updateModelPickerPost({ ... });
})().catch((err) => runtime.error?.(`model picker select failed: ${String(err)}`));
return {}; // Acknowledge immediately
}
```
How can I resolve this? If you propose a fix, please make it concise.There was a problem hiding this comment.
Addressed in 45d2c7038. Model selection now returns an empty interaction response immediately, then runs the /model dispatch and picker refresh in a detached async task so the Mattermost callback is acknowledged without waiting on the model change.
| }, | ||
| }) | ||
| : undefined; | ||
| const { dispatcher, replyOptions, markDispatchIdle } = |
There was a problem hiding this comment.
Missing humanDelay in runModelPickerCommand dispatcher
createReplyDispatcherWithTyping is called here without humanDelay, whereas the equivalent call in dispatchButtonClick (line ~593) does pass humanDelay: core.channel.reply.resolveHumanDelayConfig(cfg, route.agentId). If human-delay simulation is intentionally disabled for picker-triggered commands, a brief comment explaining the decision would help future maintainers.
| const { dispatcher, replyOptions, markDispatchIdle } = | |
| const { dispatcher, replyOptions, markDispatchIdle } = | |
| core.channel.reply.createReplyDispatcherWithTyping({ | |
| ...prefixOptions, | |
| // No humanDelay for picker commands: confirmation replies should be immediate. | |
| deliver: async (payload: ReplyPayload) => { |
Prompt To Fix With AI
This is a comment left during a code review.
Path: extensions/mattermost/src/mattermost/monitor.ts
Line: 895
Comment:
**Missing `humanDelay` in `runModelPickerCommand` dispatcher**
`createReplyDispatcherWithTyping` is called here without `humanDelay`, whereas the equivalent call in `dispatchButtonClick` (line ~593) does pass `humanDelay: core.channel.reply.resolveHumanDelayConfig(cfg, route.agentId)`. If human-delay simulation is intentionally disabled for picker-triggered commands, a brief comment explaining the decision would help future maintainers.
```suggestion
const { dispatcher, replyOptions, markDispatchIdle } =
core.channel.reply.createReplyDispatcherWithTyping({
...prefixOptions,
// No humanDelay for picker commands: confirmation replies should be immediate.
deliver: async (payload: ReplyPayload) => {
```
How can I resolve this? If you propose a fix, please make it concise.There was a problem hiding this comment.
Added a clarifying comment in 45d2c7038. Picker-triggered confirmation replies intentionally stay immediate here so the interaction path does not add humanDelay.
| try { | ||
| const storePath = resolveStorePath(params.cfg.session?.store, { | ||
| agentId: params.route.agentId, | ||
| }); | ||
| const sessionStore = loadSessionStore(storePath, { skipCache: true }); | ||
| const sessionEntry = sessionStore[params.route.sessionKey]; | ||
| const override = resolveStoredModelOverride({ | ||
| sessionEntry, | ||
| sessionStore, | ||
| sessionKey: params.route.sessionKey, | ||
| }); | ||
| if (!override?.model) { | ||
| return fallback; | ||
| } | ||
| const provider = (override.provider || params.data.resolvedDefault.provider).trim(); | ||
| return provider ? `${provider}/${override.model}` : fallback; | ||
| } catch { | ||
| return fallback; | ||
| } | ||
| } |
There was a problem hiding this comment.
resolveMattermostModelPickerCurrentModel performs a cold disk read on every render
loadSessionStore is called with skipCache: true both at the beginning of handleModelPickerInteraction (to get currentModel) and after runModelPickerCommand completes (to get updatedModel). Each call bypasses the session-store cache and hits disk. For the pre-select render this is fine, but for rapid navigation through many providers/pages it may accumulate noticeable latency.
Consider only using skipCache: true after the model-selection write path (the select action), and using the normal cached read for the read-only navigation paths (providers, back, list).
Prompt To Fix With AI
This is a comment left during a code review.
Path: extensions/mattermost/src/mattermost/model-picker.ts
Line: 220-239
Comment:
**`resolveMattermostModelPickerCurrentModel` performs a cold disk read on every render**
`loadSessionStore` is called with `skipCache: true` both at the beginning of `handleModelPickerInteraction` (to get `currentModel`) and after `runModelPickerCommand` completes (to get `updatedModel`). Each call bypasses the session-store cache and hits disk. For the pre-select render this is fine, but for rapid navigation through many providers/pages it may accumulate noticeable latency.
Consider only using `skipCache: true` after the model-selection write path (the `select` action), and using the normal cached read for the read-only navigation paths (`providers`, `back`, `list`).
How can I resolve this? If you propose a fix, please make it concise.There was a problem hiding this comment.
Addressed in 45d2c7038. Read-only provider and model browsing now uses cached session-store reads, and skipCache is only forced after a model selection when we need to verify the persisted update before rerendering.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c386768ab7
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| import { normalizeProviderId } from "../../../../src/agents/model-selection.js"; | ||
| import type { ModelsProviderData } from "../../../../src/auto-reply/reply/commands-models.js"; | ||
| import { resolveStoredModelOverride } from "../../../../src/auto-reply/reply/model-selection.js"; | ||
| import type { OpenClawConfig } from "../../../../src/config/config.js"; | ||
| import { loadSessionStore, resolveStorePath } from "../../../../src/config/sessions.js"; |
There was a problem hiding this comment.
Replace core-relative imports in mattermost plugin
These imports reach into ../../../../src/..., which works only inside the monorepo tree; when @openclaw/mattermost is installed from npm, the package contains only the extension files, so these paths resolve outside the package and fail with module resolution errors during plugin load. That makes the Mattermost channel unusable in normal plugin-install deployments, so the model picker feature regresses production installs unless these dependencies are exposed via openclaw/plugin-sdk (or another packaged boundary) instead of repo-internal relative paths.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Addressed in 45d2c7038. I exported the needed helpers from the packaged Mattermost plugin-sdk surface and switched the Mattermost extension files to import from openclaw/plugin-sdk/mattermost instead of private ../../../../src paths, so published plugin installs keep working.
|
Follow-up on the Aisle scanner comment:
Verification on the new head:
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 806a2a2c92
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| data: ModelsProviderData; | ||
| skipCache?: boolean; | ||
| }): string { | ||
| const fallback = `${params.data.resolvedDefault.provider}/${params.data.resolvedDefault.model}`; |
There was a problem hiding this comment.
Use route agent defaults for picker fallback model
When there is no stored override, this fallback uses data.resolvedDefault, but that value comes from buildModelsProviderData(cfg) and is global to the config, not scoped to route.agentId. In any Mattermost route pinned to a non-default agent with its own model default, the picker will show and highlight the wrong “Current” model until an override is explicitly saved, which makes /oc_model and /oc_models report inaccurate state for those sessions.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Addressed in 97faaab35.
buildModelsProviderData now accepts an optional agentId and resolves its fallback model via resolveDefaultModelForAgent(...) instead of the global default. The Mattermost picker now passes route.agentId in both the slash-entry and interaction paths, and I added a regression test covering the no-override case for a routed non-default agent.
97faaab to
053cba4
Compare
053cba4 to
e4930a7
Compare
e4930a7 to
b63d096
Compare
b63d096 to
0883654
Compare
|
Merged via squash. Thanks @mukhtharcm! |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0883654e88
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| if (pickerEntry) { | ||
| const data = await buildModelsProviderData(cfg, route.agentId); |
There was a problem hiding this comment.
Gate picker rendering on command authorization
handleSlashCommandAsync sends the interactive picker whenever resolveMattermostModelPickerEntry(commandText) matches, but it does not check commandAuthorized first. In configurations where authorizeSlashInvocation returns ok: true with commandAuthorized: false (for example native slash flow with commands.text=false and no access-group allowlist), /oc_model and /oc_models now expose provider/model inventory via picker views even though the same user is not allowed to run those commands, which is a regression from the prior command path that returned unauthorized.
Useful? React with 👍 / 👎.
🔒 Aisle Security AnalysisWe found 1 potential security issue(s) in this PR:
1. 🔵 Mattermost model picker bypasses command authorization (native /oc_model, /oc_models) when text commands are disabled
DescriptionThe Mattermost native slash-command handler renders and sends the model picker UI without checking This becomes an authorization bypass when
Impact:
Vulnerable code: const pickerEntry = resolveMattermostModelPickerEntry(commandText);
if (pickerEntry) {
const data = await buildModelsProviderData(cfg, route.agentId);
...
await sendMessageMattermost(to, view.text, {
accountId: account.accountId,
buttons: view.buttons,
});
return;
}RecommendationRequire command authorization before serving model picker content, and ensure
const pickerEntry = resolveMattermostModelPickerEntry(commandText);
if (pickerEntry) {
if (!commandAuthorized) {
await sendMessageMattermost(to, "Unauthorized.", { accountId: account.accountId });
return;
}
// render picker...
}
const allowTextCommands = core.channel.commands.shouldHandleTextCommands({
cfg,
surface: "mattermost",
commandSource: "native",
});Apply the same fix to the interaction handler path as well (model picker callbacks). Analyzed PR: #38767 at commit Last updated on: 2026-03-07T17:17:46Z |
Merged via squash. Prepared head SHA: 0883654 Co-authored-by: mukhtharcm <[email protected]> Co-authored-by: mukhtharcm <[email protected]> Reviewed-by: @mukhtharcm
Merged via squash. Prepared head SHA: 0883654 Co-authored-by: mukhtharcm <[email protected]> Co-authored-by: mukhtharcm <[email protected]> Reviewed-by: @mukhtharcm
Merged via squash. Prepared head SHA: 0883654 Co-authored-by: mukhtharcm <[email protected]> Co-authored-by: mukhtharcm <[email protected]> Reviewed-by: @mukhtharcm
Merged via squash. Prepared head SHA: 0883654 Co-authored-by: mukhtharcm <[email protected]> Co-authored-by: mukhtharcm <[email protected]> Reviewed-by: @mukhtharcm
Merged via squash. Prepared head SHA: 0883654 Co-authored-by: mukhtharcm <[email protected]> Co-authored-by: mukhtharcm <[email protected]> Reviewed-by: @mukhtharcm
Merged via squash. Prepared head SHA: 0883654 Co-authored-by: mukhtharcm <[email protected]> Co-authored-by: mukhtharcm <[email protected]> Reviewed-by: @mukhtharcm (cherry picked from commit 4f08dcc)
Merged via squash. Prepared head SHA: 0883654 Co-authored-by: mukhtharcm <[email protected]> Co-authored-by: mukhtharcm <[email protected]> Reviewed-by: @mukhtharcm (cherry picked from commit 4f08dcc)
Merged via squash. Prepared head SHA: 0883654 Co-authored-by: mukhtharcm <[email protected]> Co-authored-by: mukhtharcm <[email protected]> Reviewed-by: @mukhtharcm
Merged via squash. Prepared head SHA: 0883654 Co-authored-by: mukhtharcm <[email protected]> Co-authored-by: mukhtharcm <[email protected]> Reviewed-by: @mukhtharcm
Merged via squash. Prepared head SHA: 0883654 Co-authored-by: mukhtharcm <[email protected]> Co-authored-by: mukhtharcm <[email protected]> Reviewed-by: @mukhtharcm
Merged via squash. Prepared head SHA: 0883654 Co-authored-by: mukhtharcm <[email protected]> Co-authored-by: mukhtharcm <[email protected]> Reviewed-by: @mukhtharcm
Merged via squash. Prepared head SHA: 0883654 Co-authored-by: mukhtharcm <[email protected]> Co-authored-by: mukhtharcm <[email protected]> Reviewed-by: @mukhtharcm
Summary
Describe the problem and fix in 2–5 bullets:
/oc_modeland/oc_modelsdid not offer the interactive model picker flow available on other chat surfaces, and the first Mattermost picker iteration had broken callback/update behavior./oc_model,/oc_models, and/oc_models <provider>; sign and route picker button callbacks through the existing Mattermost interaction handler; make button action ids unique per post; refresh the picker post during browsing; and emit a normal/modelconfirmation reply when a model is selected./modelpersistence logic outside routing picker selections through the normal command path.Change Type (select all)
Scope (select all touched areas)
Linked Issue/PR
User-visible / Behavior Changes
/oc_model,/oc_models, and/oc_models <provider>.Security Impact (required)
Yes/No): YesYes/No): NoYes/No): YesYes/No): NoYes/No): NoYes, explain risk + mitigation:/modelcommand path and normal session authorization logic.Repro + Verification
Environment
Steps
/oc_modelor/oc_modelsin Mattermost.Expected
Actual
Evidence
Attach at least one:
Relevant verification commands:
pnpm exec vitest run extensions/mattermost/src/mattermost/model-picker.test.ts extensions/mattermost/src/mattermost/interactions.test.ts extensions/mattermost/src/mattermost/send.test.ts extensions/mattermost/src/mattermost/slash-http.test.tspnpm tsgopnpm buildHuman Verification (required)
What you personally verified (not just CI), and how:
Compatibility / Migration
Yes/No): YesYes/No): NoYes/No): NoFailure Recovery (if this breaks)
/oc_model <provider/model>//model <provider/model>commands.extensions/mattermost/src/mattermost/slash-http.ts,extensions/mattermost/src/mattermost/monitor.ts,extensions/mattermost/src/mattermost/model-picker.ts,extensions/mattermost/src/mattermost/interactions.ts,extensions/mattermost/src/mattermost/send.ts,extensions/mattermost/src/channel.ts.Risks and Mitigations
List only real risks for this PR. Add/remove entries as needed. If none, write
None.