Skip to content
Open
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ Platform releases use `vX.Y.Z` tags and publish `ghcr.io/tencent/loopforge`. Loo
- The orchestrator panel embeds the chatbot (`/chatbot/?surface=sop-designer`) instead of its own hand-written chat. Replies render Markdown with the execution trace, a running turn can be stopped, the turn runs as a background generation, so closing the panel or reloading the page no longer loses it, and reopening a SOP shows its earlier conversation. The CLI and model choice keeps its own memory as before. Each reply's draft shows its warnings and can be put on the canvas again. The canvas and the chat talk only through `agentflow-sop-designer-*` window messages; the canvas still animates nodes and wires as the draft streams in.
- Editing a SOP in the orchestrator no longer rewrites the whole graph. On a canvas with steps the model submits `operations` (`add_node`, `update_node`, `remove_node`, `add_edge`, `remove_edge`, `update_workflow`) and the server applies them to the canvas it received, so steps, prompts, scripts, layout and the 「构建静态站点」 node the user did not mention stay exactly as they were. An operation that does not fit the canvas (an unknown node, a duplicate edge, removing a node another step rejects to) goes back to the model with the reason instead of reaching the canvas. The canvas no longer guesses intent from the wording: it no longer matches 「重新…」 or 「去掉预览」 phrases or SOP names in the message; the server lists the project's SOPs and the model reads the one the user means. A draft with a different SOP id replaces the canvas only after the user confirms.
- The orchestrator offers the model only roles a SOP save accepts: roles of this project and roles another project shares. A built-in role that belongs to no project used to be offered, and the draft then failed on save with 「角色 … 不属于当前项目且尚未共享」. `workflows_save` drafts from any conversation now warn about such a role before saving. A script longer than 400 characters reaches the model as a marker that says it is omitted, not as an empty string; the model used to report the script as empty and offer to write one, and a marker copied back into a draft is replaced by the canvas's script.
- 「CLI 默认模型」(`default`) is gone. `GET /api/assistant/models`, `?executor=…` and `/api/executor-models` no longer list it. Every picker (AI 对话, roles, schedules, Bots, clarification, run evals, the SOP preview) starts on the first listed model, and a setting without a model runs on the first model its catalog lists. Settings saved earlier with `default` read as no model chosen (`domain.ChosenModel`).
- Scheduled tasks keep an execution history with a session mode, keep conversations per job and gain row actions (#958). AI jobs run with the key of the user who saved them and fall back to the shared key (#966).
- Requirements can be created directly and clarified in a chat (#965). Settled execution history can be force-deleted (#210).
- Conversation workspaces open by sandbox with agent-owned Git (#947), run native agent CLIs on bound execution machines (#494), can be bound to project SOP workspaces through `workspaceRunId` (#974), and install a missing CLI from the failure message (#183).
Expand Down
32 changes: 16 additions & 16 deletions chatbot/src/useChat.js
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ export function useChat() {
[revealId, setRevealId] = useState(activeId),
[projectId, setProjectId] = useState(initialProject),
[selection, setSelection] = useState(() => ({ executor: storedExecutor(), model: null, effort: null })),
[codeBuddyDefault, setCodeBuddyDefault] = useState({ id: "default", name: "默认" }),
[codeBuddyDefault, setCodeBuddyDefault] = useState({ id: "", name: "" }),
[sponsoredModels, setSponsoredModels] = useState([]),
[providerCatalogs, setProviderCatalogs] = useState({}),
[generation, setGeneration] = useState(null),
Expand Down Expand Up @@ -251,7 +251,7 @@ export function useChat() {
}
const applyModelCatalog = useCallback((catalog) => {
setModels(catalog.models || []);
setCodeBuddyDefault({ id: catalog.default || "default", name: "默认", efforts: catalog.defaultEfforts });
setCodeBuddyDefault({ id: catalog.default || "", name: catalog.default || "", efforts: catalog.defaultEfforts });
setSponsoredModels(sponsoredModelList(catalog));
}, []);
useEffect(() => {
Expand Down Expand Up @@ -1024,11 +1024,6 @@ export function useChat() {
setError("会话仍在加载,请稍候再发送。");
return false;
}
const modelError = composerModelError(composerModel);
if (modelError) {
setError(modelError);
return false;
}
const currentProjectId = sessionRef.current?.projectId || "";
const approval = fromQueue
? queuedApproval({ approvalMode, approvalUserId, approvalProjectId }, user?.id, currentProjectId)
Expand All @@ -1038,6 +1033,11 @@ export function useChat() {
generation?.status === "running" ||
steeringRef.current?.sessionId === currentId.current
) {
const modelError = composerModelError(composerModel);
if (modelError) {
setError(modelError);
return false;
}
// Internal follow-ups (confirmed drafts) never queue or interrupt.
if (messagesOverride || fromQueue || !currentId.current) {
setError("当前回复仍在生成,请稍后再试。");
Expand Down Expand Up @@ -1080,20 +1080,20 @@ export function useChat() {
try {
// Recheck credentials before creating the session in case the user
// configured a key elsewhere after this tab loaded.
if (
codeBuddy &&
!sponsoredModel &&
users.find((u) => u.id === user?.id)?.codeBuddyApiKeyConfigured === undefined &&
user &&
!user.isGuest
) {
const account = users.find((member) => member.id === user?.id);
if (codeBuddy && user && !user.isGuest && !sponsoredModel && !account?.codeBuddyApiKeyConfigured) {
const rows = await api("/api/users").catch(() => null);
if (rows) setUsers(rows);
const fresh = rows?.find((u) => u.id === user.id);
if (fresh && !fresh.codeBuddyApiKeyConfigured) {
const fresh = rows?.find((u) => u.id === user.id) ?? user;
if (!fresh.codeBuddyApiKeyConfigured) {
if (viewingTarget()) setError("请先在个人配置中配置自己的 CodeBuddy API Key");
return false;
}
if (missingKey || !composerModel.activeModel) requestModelCatalogRefresh((revision) => revision + 1);
if (!composerModel.activeModel) {
if (viewingTarget()) setError("CodeBuddy 凭证已更新,正在刷新模型列表,请稍后重试。");
return false;
}
}
const chosen = await modelForRequest({ executor, model, effort }, s, composerModel);
if (!s) {
Expand Down
24 changes: 24 additions & 0 deletions chatbot/tests/hooks.test.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -713,6 +713,30 @@ describe("conversation hooks", () => {
}
});

test.each([
[false, "请先在个人配置中配置自己的 CodeBuddy API Key"],
[true, "当前 CLI 暂无可用模型"],
])("explains how to send with an empty catalog (key configured: %s)", async (configured, reason) => {
localStorage.removeItem("loopforge.assistant.executor");
const original = apiMock.getMockImplementation();
const user = { id: 1, loginName: "tester", codeBuddyApiKeyConfigured: configured };
apiMock.mockImplementation(async (path, options) => {
if (path === "/api/auth/current") return { user };
if (path === "/api/users") return [user];
if (path === "/api/assistant/models") return { default: "", models: [] };
return original(path, options);
});
try {
const { result } = renderHook(() => useChat());
await waitFor(() => expect(result.current.ready).toBe(true));
await act(async () => expect(await result.current.send({ text: "草稿" })).toBe(false));
expect(result.current.error).toContain(reason);
expect(writeMock).not.toHaveBeenCalled();
} finally {
apiMock.mockImplementation(original);
}
});

test("without an own key chat is limited to the administrator's shared models", async () => {
localStorage.removeItem("loopforge.assistant.executor");
const original = apiMock.getMockImplementation();
Expand Down
2 changes: 1 addition & 1 deletion e2e/api/62-integrations.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ test('notification bots: create, update, secret stays write-only, delete', async
assert.equal(bot.secretConfigured, true);
assert.equal(bot.ownerId, me.id);
assert.equal(bot.health, 'unchecked');
assert.ok(bot.model, 'a default report model is assigned');
assert.equal(bot.model || '', '', 'an unselected model is resolved for the responsible account when the report runs');

const bots = await api('GET', `/api/notification-bots?projectId=${P}`, undefined, { raw: true });
assert.ok(list(bots.data).some(b => b.id === bot.id));
Expand Down
6 changes: 4 additions & 2 deletions e2e/public/executors.spec.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,10 @@ test('executor selection has independent models, credentials and a persistent ch
expect(models.ok()).toBe(true);
const catalog=await models.json();
expect(Array.isArray(catalog.models)).toBe(true);
if(id==='codebuddy')expect(catalog.default).toBeTruthy();
else expect(catalog.models.length).toBeGreaterThan(0);
if(id==='codebuddy'){
const first=catalog.models.find(model=>!model.engine||model.engine==='codebuddy');
expect(catalog.default).toBe(first?.id??'');
}else expect(catalog.models.length).toBeGreaterThan(0);
}
await choose('Codex');
await page.reload();
Expand Down
15 changes: 15 additions & 0 deletions internal/domain/model.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package domain

import "strings"

// ChosenModel returns the model a setting names, or "" when it names none.
// A setting without a model runs on the first model its picker lists.
// Settings saved by earlier versions may hold "default", the retired
// placeholder for "let the CLI pick"; it reads as no model chosen.
func ChosenModel(id string) string {
id = strings.TrimSpace(id)
if id == "default" {
return ""
}
return id
}
2 changes: 0 additions & 2 deletions internal/domain/notification.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,6 @@ type NotificationBinding struct {
}
type NodeNotification = NotificationBinding

const DefaultNotificationReportModel = "default"

type NotificationReportRequest struct {
Binding NotificationBinding
Context NotificationContext
Expand Down
18 changes: 7 additions & 11 deletions internal/domain/preview.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ const (
PreviewBuildNodeID = "af-preview-build"
PreviewBuildAgentID = "af-preview-builder"
PreviewBuildExecutor = "codebuddy"
PreviewDefaultModel = "default"
PreviewDefaultSource = "dist"
PreviewBuildEdgeID = "af-preview-build-edge"
PreviewMaxRetentionSec = int64(30 * 24 * 3600)
Expand Down Expand Up @@ -105,14 +104,14 @@ func (c *PreviewContract) ExecutorOrCodeBuddy() string {
return PreviewBuildExecutor
}

func (c *PreviewContract) ModelOrDefault() string {
// ChosenModel is the model the preview build runs on. Saving an SOP fills
// in the first listed CodeBuddy model when none is chosen (see
// attachPreviewBuild in internal/httpapi/catalog.go).
func (c *PreviewContract) ChosenModel() string {
if c == nil {
return PreviewDefaultModel
return ""
}
if model := strings.TrimSpace(c.Model); model != "" {
return model
}
return PreviewDefaultModel
return ChosenModel(c.Model)
}

func (c *PreviewContract) Retention() time.Duration {
Expand All @@ -136,7 +135,7 @@ func (c *PreviewContract) Normalize() {
}
c.Kind = c.KindOrStatic()
c.ExecutorID = c.ExecutorOrCodeBuddy()
c.Model = c.ModelOrDefault()
c.Model = c.ChosenModel()
c.SourcePath = c.SourceOrDist()
c.IndexFile = c.Index()
if c.RetentionSec <= 0 || c.RetentionSec > PreviewMaxRetentionSec {
Expand All @@ -155,9 +154,6 @@ func (c *PreviewContract) Validate() error {
if !strings.EqualFold(c.ExecutorID, PreviewBuildExecutor) {
return fmt.Errorf("frontend preview currently supports CodeBuddy CLI only")
}
if strings.TrimSpace(c.Model) == "" {
return fmt.Errorf("frontend preview requires a CodeBuddy model")
}
if strings.Contains(c.SourcePath, "..") || strings.HasPrefix(c.SourcePath, "/") {
return fmt.Errorf("frontend preview sourcePath %q is invalid", c.SourcePath)
}
Expand Down
2 changes: 1 addition & 1 deletion internal/domain/preview_build.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ func PreviewBuildAgent(contract *PreviewContract) AgentDefinition {
Name: "构建静态站点",
Description: "系统步骤:用 CodeBuddy 产出可托管的静态站点,再由预览收尾归档。",
ExecutorID: PreviewBuildExecutor,
Model: contract.ModelOrDefault(),
Model: contract.ChosenModel(),
Prompt: PreviewBuildPrompt(contract),
ArtifactOutputs: []ArtifactContract{PreviewBuildArtifact(contract)},
Loop: AgentLoopPolicy{
Expand Down
2 changes: 1 addition & 1 deletion internal/httpapi/agent_tool_native_terminal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ func TestCodeBuddyWaitsForSessionGatewayBeforeFirstRequest(t *testing.T) {
}
}
h := &streamHandlers{}
_, out, _, err := h.runClarifyTurn(context.Background(), root, bin, clarifyDefaultModel, "p", "clarify-wait", "af-wait", filepath.Join(root, "clarify-home"), false,
_, out, _, err := h.runClarifyTurn(context.Background(), root, bin, clarifyTestModel, "p", "clarify-wait", "af-wait", filepath.Join(root, "clarify-home"), false,
runtime.RunCredentials{CodeBuddy: runtime.CodeBuddyCredential{APIKey: "test-key"}}, func(string, any) {}, clarifyTurnOpts{Native: true, MCPConfig: files.MCPConfig, Settings: files.Settings})
if err != nil || !strings.Contains(out, want) {
t.Fatalf("clarify: got %q err=%v, want %q", out, err, want)
Expand Down
2 changes: 1 addition & 1 deletion internal/httpapi/agent_tool_session_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ func TestNativeClarifyCommandKeepsReadAndSessionMCP(t *testing.T) {
}
t.Cleanup(files.Cleanup)
command, err := prepareClarifyCommandWith(clarifyCommandOpts{
Bin: "codebuddy", Model: clarifyDefaultModel, Prompt: "p", RunID: "r", SessionID: "af1",
Bin: "codebuddy", Model: clarifyTestModel, Prompt: "p", RunID: "r", SessionID: "af1",
Native: true, MCPConfig: files.MCPConfig, Settings: files.Settings,
})
if err != nil {
Expand Down
13 changes: 6 additions & 7 deletions internal/httpapi/assistant.go
Original file line number Diff line number Diff line change
Expand Up @@ -234,12 +234,12 @@ func (h *assistantHandlers) chat(c *gin.Context) {
return
}
catalogEngine, _ := assistantModelEngine(req.Model)
catalog := assistantChatCatalog(c.Request.Context(), user.CodeBuddyInternetEnvironment, nil)
catalog := assistantChatCatalog(c.Request.Context(), user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey, nil)
if catalogEngine == assistantEngineCodeBuddy {
catalog = h.turnCatalog(c.Request.Context(), user, req.Model)
}
if !runnerLogin {
selected, err := assistantTurnCatalogModel(req.Model, catalog, user, req.RequireExactModel)
selected, err := assistantTurnCatalogModel(c.Request.Context(), req.Model, catalog, user, req.RequireExactModel)
if err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
Expand Down Expand Up @@ -473,11 +473,10 @@ func (h *assistantHandlers) chat(c *gin.Context) {
nativeContinuationReady := false
var turnUsage assistantTurnUsage
replyModel := strings.TrimSpace(req.Model)
if replyModel == "" {
replyModel = assistantDefaultModel
}
if report, ok := modelCtx.Value(scheduledUsageReportKey{}).(scheduledUsageReport); ok && report.GenerationID == assistantControlScopeFrom(modelCtx).GenerationID && report.Report != nil {
defer func() { report.Report(replyModel, turnUsage.snapshot()) }()
// Preserve the usage record for CLIs that use their own default and
// do not report a concrete model.
defer func() { report.Report(firstNonEmpty(replyModel, assistantDefaultModel), turnUsage.snapshot()) }()
}
var turn string
generate := h.generate
Expand Down Expand Up @@ -1884,7 +1883,7 @@ type assistantCommandOpts struct {
}

func prepareAssistantCommand(opts assistantCommandOpts) (runtime.CommandSpec, error) {
model := strings.TrimSpace(opts.Model)
model := domain.ChosenModel(opts.Model)
if model == "" {
model = assistantFixedCatalog().Default
}
Expand Down
4 changes: 2 additions & 2 deletions internal/httpapi/assistant_approval_review_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ func TestAssistantApprovalReviewUsesConfiguredDefaultWithoutPrices(t *testing.T)

func TestAssistantChatCatalogPreselectsSponsoredModelOnlyWithSponsor(t *testing.T) {
t.Setenv("AGENTFLOW_ASSISTANT_MODEL", "team-model")
catalog := assistantChatCatalog(context.Background(), "", nil)
catalog := assistantChatCatalog(context.Background(), "", "", nil)
if catalog.Default != "team-model" {
t.Fatal("chat default without sponsor", catalog)
}
Expand All @@ -55,7 +55,7 @@ func TestAssistantChatCatalogPreselectsSponsoredModelOnlyWithSponsor(t *testing.
t.Fatal("sponsored model listed without sponsor", catalog)
}
}
catalog = assistantChatCatalog(context.Background(), "", []string{assistantSponsoredModel, "shared-extra"})
catalog = assistantChatCatalog(context.Background(), "", "", []string{assistantSponsoredModel, "shared-extra"})
listed := 0
for _, model := range catalog.Models {
if model.ID == assistantSponsoredModel || model.ID == "shared-extra" {
Expand Down
4 changes: 2 additions & 2 deletions internal/httpapi/assistant_codebuddy_default_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,11 @@ func TestCodeBuddyPersonalModelsDefaultMatchesPicker(t *testing.T) {
t.Fatalf("default = %q, want the first saved model", catalog.Default)
}
for _, id := range []string{"env-default", "env-other", "personal-a", "personal-b"} {
if got := assistantAllowedUserModel(id, catalog, user); got != id {
if got := assistantAllowedUserModel(context.Background(), id, catalog, user); got != id {
t.Fatalf("model %s not accepted: %q", id, got)
}
}
if got := assistantAllowedUserModel("", catalog, user); got != "personal-a" {
if got := assistantAllowedUserModel(context.Background(), "", catalog, user); got != "personal-a" {
t.Fatalf("empty request runs on %q, want personal-a", got)
}

Expand Down
2 changes: 1 addition & 1 deletion internal/httpapi/assistant_effort_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (
)

func TestAssistantEffortReachesNativeCLIAndPersists(t *testing.T) {
t.Setenv("AGENTFLOW_ASSISTANT_MODELS", assistantChatDefaultModel)
t.Setenv("AGENTFLOW_ASSISTANT_MODELS", assistantChatDefaultModel+",hy4-preview-ioa")
h, user := workbenchFixture(t)
_, calls := nativeCLIRecorder(t)
// calls counts conversation turns; keep model discovery off the fake CLI.
Expand Down
Loading
Loading