Skip to content
Open
2 changes: 1 addition & 1 deletion chatbot/src/ChangesPanel.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ export default function ChangesPanel({ changes }) {
/>
))}
</div>
) : (
) : changes?.warning ? null : (
<EmptyChanges repository={repository} />
)}
{changes?.truncated ? (
Expand Down
15 changes: 7 additions & 8 deletions chatbot/src/MentionPicker.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -264,23 +264,22 @@ export default forwardRef(function MentionPicker(
left = Math.max(left, clip.left + 8);
right = Math.min(right, clip.right - 8);
}
const above = anchor.top - top - 8, below = bottom - anchor.bottom - 8;
// A resize can move the caret outside the visible part of the composer.
// Measure room from the nearest visible edge in that case.
const anchorTop = Math.max(top, Math.min(anchor.top, bottom));
const anchorBottom = Math.max(top, Math.min(anchor.bottom, bottom));
const above = anchorTop - top - 8, below = bottom - anchorBottom - 8;
// Keep the picker below the active line whenever it has enough room;
// only use the upper side when the lower side cannot show a useful list.
const minRoom = 160;
const up = below < minRoom && above > below;
let room = up ? above : below,
y = up ? anchor.top - 8 : anchor.bottom + 8;
y = up ? anchorTop - 8 : anchorBottom + 8;
// On short screens the picker overlays the editor rather than escaping
// its scroll container or shrinking the results to an unusable sliver.
if (room < minRoom) {
const useAbove = above > below;
room = Math.max(0, Math.max(above, below));
y = useAbove ? bottom : top;
}
if (room < minRoom) {
room = Math.max(0, bottom - top);
y = above > below ? bottom : top;
y = up ? bottom : top;
}
const origin = containerRect;
const width = editorRect?.width || containerRect.width;
Expand Down
4 changes: 2 additions & 2 deletions chatbot/src/changes.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,12 +82,12 @@ export function parseUnifiedDiff(text = "") {
continue;
}
if (line.startsWith("rename from ")) {
file.oldPath = line.slice(12).trim();
file.oldPath ||= line.slice(12).trim();
file.status = "R";
continue;
}
if (line.startsWith("rename to ")) {
file.path = line.slice(10).trim();
file.path ||= line.slice(10).trim();
file.status = "R";
continue;
}
Expand Down
3 changes: 2 additions & 1 deletion chatbot/tests/changes-panel.test.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ test("empty state points at the work branch on the code host", () => {
);
});

test("git failures surface above the empty state", () => {
test("git failures do not report a clean worktree", () => {
render(
<ChangesPanel
changes={readyChanges({
Expand All @@ -146,6 +146,7 @@ test("git failures surface above the empty state", () => {
/>,
);
expect(screen.getByRole("alert")).toHaveTextContent("Git 状态读取失败");
expect(screen.queryByText("工作区没有未提交改动。")).not.toBeInTheDocument();
});

// A reclaimed workspace is the usual state once the work is pushed, so the
Expand Down
30 changes: 30 additions & 0 deletions chatbot/tests/changes.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,36 @@ import {
statusLabel,
} from "../src/changes.js";

test("keeps same-named patches and renames in their own repositories", () => {
const patches = parseUnifiedDiff([
"diff --git a/api/README.md b/api/README.md",
"@@ -1 +1 @@",
"-original",
"+api",
"diff --git a/worker/README.md b/worker/START.md",
"rename from README.md",
"rename to START.md",
"@@ -1 +1 @@",
"-original",
"+worker",
"diff --git a/worker/README.md b/worker/README.md",
"@@ -1 +1 @@",
"-original",
"+new-worker-readme",
].join("\n"));
const files = mergeChanges([
{ path: "api/README.md", worktree: "M" },
{ path: "worker/START.md", index: "R" },
{ path: "worker/README.md", index: "A" },
], patches);
assert.deepEqual(files.map((file) => [file.path, file.patch.hunks[0].lines[1].text]), [
["api/README.md", "api"],
["worker/README.md", "new-worker-readme"],
["worker/START.md", "worker"],
]);
assert.equal(files[2].patch.oldPath, "worker/README.md");
});

const PATCH = [
"diff --git a/web/app/approvals.js b/web/app/approvals.js",
"index 1111111..2222222 100644",
Expand Down
5 changes: 3 additions & 2 deletions e2e/api/90-route-sweep.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,9 @@ test('read-only status endpoints answer for a signed-in user', async () => {
await status('GET', '/api/assistant/cli-install?engine=not-a-cli', undefined, [400]);
});

test('OTLP ingest accepts an empty export', async () => {
await status('POST', '/api/otel/v1/traces', {}, [200, 202]);
test('OTLP ingest accepts a local empty export and refuses non-loopback callers', async () => {
const res = await status('POST', '/api/otel/v1/traces', {}, [200, 202, 403]);
if (res.status === 403) assert.equal(res.data.error, 'otel collector is loopback-only');
});

test('platform admins and repository registration validate required fields', async () => {
Expand Down
16 changes: 15 additions & 1 deletion e2e/public/github-setup.spec.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -14,20 +14,34 @@ test('GitHub authorization has a separate manual token path',async({page},info)=
await appReady(page);
await page.waitForLoadState('networkidle');
const capability=await page.request.get('/api/auth/github').then(response=>response.json());
const {user}=await page.request.get('/api/auth/current').then(response=>response.json());
const users=await page.request.get('/api/users').then(response=>response.json());
const configured=users.find(item=>item.id===user.id)?.gitHubCredentialConfigured;
await page.goto('/#/settings');
await expect(page.locator('#personalSettingsContent > .personal-settings-card')).toHaveCount(0);
const panel=page.locator('#credentialPanel');
await expect(panel).toBeVisible();
const add=panel.getByRole('button',{name:'新增 Git 配置',exact:true});
const chooser=await add.isVisible();
const row=panel.locator('[data-credential-row="gitToken"]');
if(chooser)await expect(row).toHaveCount(0);
if(chooser&&!configured)await expect(row).toHaveCount(0);
else await expect(row).toContainText('GitHub');
await page.screenshot({path:info.outputPath('github-settings.png'),fullPage:true});
if(chooser){
await add.click();
await page.getByRole('listbox',{name:'新增 Git 配置',exact:true}).getByRole('option',{name:'GitHub',exact:true}).click();
}else await row.locator('[data-credential-act="setup"]').click();
if(chooser&&configured){
const replace=row.getByRole('button',{name:'手动更换令牌',exact:true});
await expect(replace).toBeVisible();
await expect(row.locator('input[name="secret"]:visible')).toHaveCount(0);
await replace.click();
await expect(row.locator('input[name="secret"]')).toBeVisible();
await expect(row.locator('input[name="secret"]')).toHaveValue('');
expect(errors).toEqual([]);
expect(failed).toEqual([]);
return;
}
const wizard=page.locator('#credentialWizard');
if(capability.enabled){
await expect(wizard.locator('[data-github-start]')).toBeVisible();
Expand Down
8 changes: 5 additions & 3 deletions e2e/unit/flow-designer.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import vm from 'node:vm';
import { fileURLToPath } from 'node:url';

const web = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'web', 'app');
const files = ['flow-history.js', 'flow-viewport.js', 'flow-palette.js', 'flows.js'];
const files = ['sops.js', 'flow-history.js', 'flow-viewport.js', 'flow-palette.js', 'flows.js'];

const fakeEl = (extra = {}) => ({
value: '', innerHTML: '', textContent: '', hidden: false, dataset: {},
Expand Down Expand Up @@ -230,8 +230,8 @@ test('the node library search filters roles and built-in items and shows an empt

test('the LOOP switcher query filters by name or id and reports no match', () => {
const workflows = [
{ id: 'wf-build', name: '构建发布', projectId: 'p1', nodes: [] },
{ id: 'wf-review', name: '代码评审', projectId: 'p2', nodes: [] },
{ id: 'wf-build', name: '构建发布', projectId: 'p1', status: 'published', version: 1, nodes: [] },
{ id: 'wf-review', name: '代码评审', projectId: 'p2', status: 'draft', version: 1, nodes: [] },
{ id: 'tpl', name: '通用发布模板', generic: true, nodes: [] },
];
const q = fakeEl(), list = fakeEl();
Expand All @@ -241,13 +241,15 @@ test('the LOOP switcher query filters by name or id and reports no match', () =>

run('flowPalette.renderSwitcher()');
assert.deepEqual(ids(), ['wf-build', 'wf-review', 'tpl']);
assert.match(list.innerHTML, /已发布 · v1 · 0 步/);
q.value = '发布';
run('flowPalette.renderSwitcher()');
assert.deepEqual(ids(), ['wf-build', 'tpl']);
assert.doesNotMatch(list.innerHTML, /共享给本项目/, 'empty groups drop their heading');
q.value = 'WF-REVIEW';
run('flowPalette.renderSwitcher()');
assert.deepEqual(ids(), ['wf-review']);
assert.doesNotMatch(list.innerHTML, /v1/, 'an unpublished draft has no version label');
q.value = 'zzz';
run('flowPalette.renderSwitcher()');
assert.deepEqual(ids(), []);
Expand Down
11 changes: 11 additions & 0 deletions internal/domain/runner_workspace.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,17 @@ type RunnerMaintenanceRequest struct {
StatusOnly bool `json:"statusOnly,omitempty"`
}

func (r RunnerWorkspaceRequest) IsGitBrowse() bool {
switch r.Operation {
case RunnerWorkspaceOperationInfo, RunnerWorkspaceOperationLog, RunnerWorkspaceOperationCommit, RunnerWorkspaceOperationDiff:
return true
case RunnerWorkspaceOperationFile:
return r.Ref != ""
default:
return false
}
}

type RunnerMaintenanceResult struct {
Status string `json:"status"`
Current string `json:"current,omitempty"`
Expand Down
42 changes: 42 additions & 0 deletions internal/engine/delete_run_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@ package engine

import (
"context"
"errors"
"os"
"path/filepath"
"strings"
"testing"
"time"

"agentflow/internal/domain"
"agentflow/internal/repo"
Expand Down Expand Up @@ -94,6 +96,46 @@ func TestDeleteRunRefusesTerminalRunWithUnfinishedNode(t *testing.T) {
}
}

func TestDeleteCancelledRunWithConcurrentMetadataWrite(t *testing.T) {
for _, retry := range []bool{false, true} {
name := "terminal metadata"
if retry {
name = "new execution generation"
}
t.Run(name, func(t *testing.T) {
st, err := repo.OpenTest()
if err != nil {
t.Fatal(err)
}
t.Cleanup(st.Close)
e := New(st, runtime.NewManager(t.TempDir()))
const id = "cancelled-run"
if err := st.PutRun(domain.Run{ID: id, Status: "cancelled", Generation: 1}); err != nil {
t.Fatal(err)
}
e.WorkspaceActive = func(previous domain.Run) bool {
var updateErr error
if retry {
updateErr = st.TryAcquireRunLease(id, "retry-worker", previous.Generation, time.Minute)
} else {
updateErr = st.PutRunAtRevision(previous, previous.Revision)
}
if updateErr != nil {
t.Fatal(updateErr)
}
return false
}
err = e.DeleteRun(id)
if retry && !errors.Is(err, repo.ErrWorkspaceInUse) || !retry && err != nil {
t.Fatalf("DeleteRun = %v", err)
}
if exists := st.RunExists(id); exists != retry {
t.Fatalf("run exists = %t, want %t", exists, retry)
}
})
}
}

func TestDeleteRunPreservesTerminalTaskOutcome(t *testing.T) {
t.Parallel()
for _, tc := range []struct {
Expand Down
24 changes: 23 additions & 1 deletion internal/engine/workspace_cleanup.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"agentflow/internal/domain"
"agentflow/internal/repo"
"context"
"errors"
"fmt"
"log"
"os"
Expand Down Expand Up @@ -410,7 +411,8 @@ func (e *Engine) DeleteRun(runID string) error {
if e.WorkspaceActive != nil && e.WorkspaceActive(run) || e.conversationGenerationRunning(run) {
return fmt.Errorf("工作区仍在使用,请先停止")
}
if err := e.repo.ClaimWorkspaceDeletion(runID, token, run.Revision, time.Now().UTC()); err != nil {
run, err = e.claimSettledWorkspaceDeletion(run, token)
if err != nil {
return err
}
// Preserve the terminal outcome on the durable Task before removing the
Expand Down Expand Up @@ -439,6 +441,26 @@ func (e *Engine) DeleteRun(runID string) error {
return nil
}

func (e *Engine) claimSettledWorkspaceDeletion(run domain.Run, token string) (domain.Run, error) {
// Cancellation may publish the terminal status before the worker's last
// metadata write. Read the latest revision under the workspace lease, but
// stop if a retry or another action has moved the run past this outcome.
previousRevision := -1
for attempt := 0; attempt < 3; attempt++ {
current, ok := e.repo.RunState(run.ID)
if !ok || current.Status != run.Status || current.Generation != run.Generation ||
current.HasActiveNode() || current.Revision == previousRevision {
break
}
err := e.repo.ClaimWorkspaceDeletion(run.ID, token, current.Revision, current.Generation, time.Now().UTC())
if !errors.Is(err, repo.ErrWorkspaceInUse) {
return current, err
}
previousRevision = current.Revision
}
return run, repo.ErrWorkspaceInUse
}

func (e *Engine) settleDeletedRunTasks(run domain.Run) error {
status := map[string]string{"succeeded": "completed", "failed": "failed", "cancelled": "cancelled"}[run.Status]
if status == "" {
Expand Down
31 changes: 31 additions & 0 deletions internal/engine/workspace_preparation.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"
"strings"
"time"

"agentflow/internal/domain"
"agentflow/internal/procwatch"
Expand Down Expand Up @@ -74,6 +75,36 @@ func (e *Engine) acquireConversationEnvironment(ctx context.Context, run domain.
return env, nil
}

// WorkspaceBrowseGit uses the conversation environment without running its
// preparation workflow or attaching credentials to a read-only Git request.
func (e *Engine) WorkspaceBrowseGit(ctx context.Context, run domain.Run) context.Context {
if !run.IsWorkspace() || e.defaultExecutionRunner(run) != "" {
return ctx
}
openCtx, cancel := context.WithTimeout(ctx, 4*time.Second)
defer cancel()
env, err := e.acquireConversationEnvironment(openCtx, run)
if err != nil || !domain.ConversationSandboxDriver(env.Driver()) {
return ctx
}
return runtime.WithSandboxGit(ctx, env.sandbox, runtime.RunCredentials{})
}

// RunnerWorkspaceBrowseRequest sends only the frozen sandbox needed by a Git
// reader. Readers do not need preparation recipes, MCP assets or credentials.
func (e *Engine) RunnerWorkspaceBrowseRequest(run domain.Run, request domain.RunnerWorkspaceRequest) domain.RunnerWorkspaceRequest {
if !run.IsWorkspace() || run.ExecutionContext.RunnerWorkspaceLayout != domain.RunnerWorkspaceLayoutShared {
return request
}
spec, err := e.runnerSandboxSpec(run)
if err != nil {
return request
}
request.RunKind = run.Kind
request.Sandbox = spec
return request
}

func (e *Engine) preparationSink(runID string) runtime.EventSink {
return func(event domain.TelemetryEvent) {
switch event.Name {
Expand Down
Loading
Loading