Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 37 additions & 29 deletions chatbot/src/SopDesigner.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,6 @@ function modelsFor(catalog, engine) {
return engine === defaultEngine ? models.filter((m) => !m.engine || m.engine === defaultEngine) : engineModels(models, engine);
}

function enginesOf(catalog) {
if (catalog.engines?.length) return catalog.engines;
const ids = [...new Set((catalog.models || []).map((m) => m.engine || defaultEngine))];
return ids.map((id) => ({ id, name: id === defaultEngine ? "CodeBuddy" : id, configured: true }));
}

function DraftNote({ draft, onPlace, onConfigureRole }) {
return (
<div className="sop-designer-draft">
Expand Down Expand Up @@ -128,27 +122,42 @@ export default function SopDesigner({ search = location.search, canvas = window.

useEffect(() => {
let current = true;
api("/api/assistant/models")
.then((data) => current && setCatalog(data || {}))
.catch((e) => current && setError(e.message));
let revision = 0;
const load = () => {
const requested = ++revision;
api("/api/assistant/models")
.then((data) => current && requested === revision && setCatalog(data || {}))
.catch((e) => current && requested === revision && setError(e.message));
};
const onCredentialsChanged = (event) => {
if (event.source !== canvas || event.origin !== location.origin ||
event.data?.type !== "agentflow-credentials-changed") return;
setCatalog({});
setMenu(null);
load();
};
load();
window.addEventListener("message", onCredentialsChanged);
return () => {
current = false;
window.removeEventListener("message", onCredentialsChanged);
};
}, []);
}, [canvas]);

const engine = engineOfModel(model, catalog.models);
const engineList = enginesOf(catalog);
const models = modelsFor(catalog, engine);
// Fall back to the catalog default once it loads.
const engineList = useMemo(() => (catalog.engines || []).filter((item) =>
item.configured && modelsFor(catalog, item.id).length), [catalog]);
const models = engineList.some((item) => item.id === engine) ? modelsFor(catalog, engine) : [];
const modelAvailable = models.some((item) => item.id === model);
// Fall back to an available model when the saved model is no longer selectable.
useEffect(() => {
if (!catalog.models?.length || catalog.models.some((m) => m.id === model)) return;
if (modelAvailable || !engineList.length) return;
const preferredEngine = catalog.preferences?.executor;
const preferredModel = catalog.preferences?.model;
const preferred = modelsFor(catalog, preferredEngine).find((m) =>
m.id === preferredModel || m.id === preferredEngine + ":" + preferredModel);
const configured = new Set(enginesOf(catalog).filter((item) => item.configured !== false).map((item) => item.id));
setModel(preferred?.id || catalog.models.find((m) => configured.has(m.engine || defaultEngine))?.id || catalog.models[0].id);
}, [catalog, model]);
const preferred = engineList.some((item) => item.id === preferredEngine) &&
modelsFor(catalog, preferredEngine).find((m) => m.id === preferredModel || m.id === preferredEngine + ":" + preferredModel);
setModel(preferred?.id || modelsFor(catalog, engineList[0].id)[0].id);
}, [catalog, engineList, modelAvailable]);

useEffect(() => {
let current = true;
Expand Down Expand Up @@ -299,6 +308,10 @@ export default function SopDesigner({ search = location.search, canvas = window.
setError("先在顶栏选择项目");
return;
}
if (!modelAvailable) {
setError("请先在个人配置中添加可用的执行器和模型");
return;
}
setError("");
setStarting(true);
let canvasRequested = false;
Expand Down Expand Up @@ -425,28 +438,23 @@ export default function SopDesigner({ search = location.search, canvas = window.
label="CLI"
options={engineList.map((item) => {
const brand = engineBrand(item.id);
const disabled = item.configured === false || !modelsFor(catalog, item.id).length;
return {
...item,
icon: "terminal",
label: item.name,
detail: item.configured === false ? "未配置 API Key,先到个人配置里添加" : disabled ? "暂无可用模型" : `使用 ${item.name} 与个人 API Key`,
disabled,
detail: `使用 ${item.name} 模型`,
glyph: hasProviderLogo(brand) ? <ModelProviderIcon brand={brand} size={16} /> : null,
};
})}
value={engine}
onSelect={(id) => {
const item = engineList.find((e) => e.id === id);
if (!busy && item?.configured !== false) selectEngine(id);
}}
onSelect={(id) => { if (!busy) selectEngine(id); }}
open={menu === "engine"}
onOpenChange={(open) => setMenu(open && !busy ? "engine" : null)}
/> : null}
<ModelPicker
models={models}
value={model}
label={models.find((m) => m.id === model)?.name || model || "模型"}
label={models.find((m) => m.id === model)?.name || "模型"}
open={menu === "model"}
onOpenChange={(open) => setMenu(open && !busy ? "model" : null)}
onSelect={(id) => {
Expand All @@ -461,13 +469,13 @@ export default function SopDesigner({ search = location.search, canvas = window.
<HarnessIcon name="chat-stop" size={14} />
</button>
) : (
<button type="submit" className="send-button" aria-label="发送编排要求" disabled={busy || !text.trim()}>
<button type="submit" className="send-button" aria-label="发送编排要求" disabled={busy || !text.trim() || !modelAvailable}>
<HarnessIcon name="chat-send" size={20} />
</button>
)}
</footer>
</div>
<small>仅生成草稿,确认后在画布上保存 · 切换 CLI 会开启新对话,画布保留</small>
<small>{catalog.engines?.length && !engineList.length ? "请先在个人配置中添加可用的执行器和模型" : "仅生成草稿,确认后在画布上保存 · 切换 CLI 会开启新对话,画布保留"}</small>
</form>
</div>
);
Expand Down
19 changes: 19 additions & 0 deletions chatbot/tests/sop-designer.test.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -286,4 +286,23 @@ describe("SopDesigner", () => {
expect(request.model).toBe("codex:gpt");
expect(request.sessionId).not.toBe("chat-old");
});

test("the composer drops a CLI after its credential is removed even if its models remain", async () => {
localStorage.setItem("agentflow.orchestratorModel", "codex:gpt");
render(<SopDesigner search="?surface=sop-designer&projectId=p1&workflowId=sop-a" canvas={canvas} />);
const cli = await screen.findByRole("button", { name: "CLI" });
await waitFor(() => expect(cli.textContent).toContain("Codex"));
const original = read.getMockImplementation();
read.mockImplementation(async (path) => {
const data = await original(path);
if (path !== "/api/assistant/models") return data;
return { ...data, engines: data.engines.map((item) => item.id === "codex" ? { ...item, configured: false } : item) };
});
reply({ type: "agentflow-credentials-changed" });
const refreshed = await screen.findByRole("button", { name: "CLI" });
await waitFor(() => expect(refreshed.textContent).toContain("CodeBuddy"));
fireEvent.click(refreshed);
expect(await screen.findByRole("menuitemradio", { name: "CodeBuddy" })).toBeTruthy();
expect(screen.queryByRole("menuitemradio", { name: "Codex" })).toBeNull();
});
});
7 changes: 6 additions & 1 deletion docs/api/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2506,7 +2506,12 @@ paths:
get:
tags: [Assets]
operationId: listExecutorModels
description: Returns, per built-in CLI, the selectable model IDs, the default model and the reasoning-effort levels. An Agent's model should be one of these IDs.
description: Returns, per built-in CLI, the selectable model IDs, the default model and the reasoning-effort levels. An Agent's model should be one of these IDs. `configured` reports whether a SOP run can use the CLI for the caller, and `personal` whether the caller saved their own key for it.
parameters:
- name: projectId
in: query
schema: {type: string}
description: Resolve `configured` against the execution machine a SOP in this project uses, which is the caller's project default before the personal default. Omit it for personal SOPs.
responses:
"200":
description: Model catalog keyed by CLI id
Expand Down
68 changes: 62 additions & 6 deletions internal/engine/sop_executors.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,61 @@ type sopExecutorAccess struct {
}

func (e *Engine) sopExecutorAccess(ec domain.TelemetryContext) sopExecutorAccess {
user, _ := e.repo.User(ec.ResponsibleUserID)
runner, _ := e.repo.Runner(ec.ExecutionRunnerID)
return newSOPExecutorAccess(e.repo, ec)
}

func newSOPExecutorAccess(s *repo.Store, ec domain.TelemetryContext) sopExecutorAccess {
user, _ := s.User(ec.ResponsibleUserID)
runner, _ := s.Runner(ec.ExecutionRunnerID)
return sopExecutorAccess{
user: user, runner: runner, usesRunner: ec.ExecutionRunnerID != "", execution: ec,
sharedCodeBuddy: resolveCodeBuddyCredential(e.repo, user.ID).Sponsored,
sharedCodeBuddy: resolveCodeBuddyCredential(s, user.ID).Sponsored,
}
}

// ExecutorCredentials reports which CLIs have a credential for a SOP run that
// userID starts in projectID (empty for a personal SOP). It resolves the
// machine the same way a new SOP run does: the user's project default first,
// then the personal default when the project may use it. Pickers use it before
// the run's machine is known, so the run-time check still verifies that the
// machine provides the CLI.
func ExecutorCredentials(s *repo.Store, userID int64, projectID string) func(kind string) bool {
runnerID := s.ResolveRunnerDefaults(userID, projectID).Runner.ID
Comment thread
crispinhu27 marked this conversation as resolved.
Resolved
return newSOPExecutorAccess(s, domain.TelemetryContext{ResponsibleUserID: userID, ProjectID: projectID, ExecutionRunnerID: runnerID}).hasCredential
}

// ExecutorCredentials also follows the cloud runner pool: a user without a
// default machine runs on a pool runner, like selectSOPExecutionTarget picks.
// The pick is random, so a CLI counts when any online pool runner logs it in;
// the run-time check still verifies the machine it lands on.
func (e *Engine) ExecutorCredentials(userID int64, projectID string) func(kind string) bool {
ec := domain.TelemetryContext{ResponsibleUserID: userID, ProjectID: projectID}
ec.ExecutionRunnerID = e.repo.ResolveRunnerDefaults(userID, projectID).Runner.ID
access := newSOPExecutorAccess(e.repo, ec)
if ec.ExecutionRunnerID != "" {
return access.hasCredential
}
e.mu.Lock()
pool := e.cloudPool
e.mu.Unlock()
if !pool.serves(projectID) {
return access.hasCredential
}
candidates := []sopExecutorAccess{access}
for _, runner := range e.eligiblePoolRunners(pool.Label) {
onRunner := access
onRunner.runner, onRunner.usesRunner = runner, true
onRunner.execution.ExecutionRunnerID = runner.ID
onRunner.execution.ExecutionPool = domain.ExecutionModeCloud
candidates = append(candidates, onRunner)
}
return func(kind string) bool {
for _, candidate := range candidates {
if candidate.hasCredential(kind) {
return true
}
}
return false
}
}

Expand All @@ -53,13 +103,19 @@ func (a sopExecutorAccess) configured(kind string) bool {
if !a.runner.SupportsProvider(kind) {
return false
}
if a.runnerLogin(kind) {
return true
}
if kind == "codebuddy" && strings.TrimSpace(a.user.CodeBuddyBaseURL) != "" && !a.runner.SupportsCodeBuddyBaseURL() {
return false
}
}
return a.hasCredential(kind)
}

// hasCredential accepts a personal key, the platform's shared CodeBuddy Key,
// or account login on the run's machine.
func (a sopExecutorAccess) hasCredential(kind string) bool {
if a.runner.SupportsProvider(kind) && a.runnerLogin(kind) {
return true
}
return a.user.HasExecutorCredential(kind) || kind == "codebuddy" && a.sharedCodeBuddy
}

Expand Down
Loading
Loading