Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 8711fc92db | |||
| e84bf3a4c6 | |||
| 376f78278d |
+12
-10
@@ -145,10 +145,10 @@ jobs:
|
||||
# the diagnostic step with its own continue-on-error: true (line 203).
|
||||
# Flip confirmed by CI / Platform (Go) status = success on main HEAD 363905d3.
|
||||
continue-on-error: false
|
||||
# Job-level ceiling. The go test step below runs with a per-step 10m timeout;
|
||||
# this cap catches any step that leaks past that. Set well above 10m so
|
||||
# Job-level ceiling. The go test step below runs with a per-step 30m timeout;
|
||||
# this cap catches any step that leaks past that. Set well above 30m so
|
||||
# the per-step timeout is the active constraint.
|
||||
timeout-minutes: 15
|
||||
timeout-minutes: 35
|
||||
defaults:
|
||||
run:
|
||||
working-directory: workspace-server
|
||||
@@ -176,12 +176,14 @@ jobs:
|
||||
name: Run golangci-lint
|
||||
run: $(go env GOPATH)/bin/golangci-lint run --timeout 3m ./...
|
||||
- if: always()
|
||||
name: Diagnostic — per-package verbose 60s
|
||||
name: Diagnostic — per-package verbose (300s timeout)
|
||||
run: |
|
||||
set +e
|
||||
go test -race -v -timeout 60s ./internal/handlers/... 2>&1 | tee /tmp/test-handlers.log
|
||||
# 300s allows handlers + pendinguploads packages to complete on cold
|
||||
# runners with -race instrumentation (~60-120s each vs ~14s non-race).
|
||||
go test -race -v -timeout 300s ./internal/handlers/... 2>&1 | tee /tmp/test-handlers.log
|
||||
handlers_exit=$?
|
||||
go test -race -v -timeout 60s ./internal/pendinguploads/... 2>&1 | tee /tmp/test-pu.log
|
||||
go test -race -v -timeout 300s ./internal/pendinguploads/... 2>&1 | tee /tmp/test-pu.log
|
||||
pu_exit=$?
|
||||
echo "::group::handlers exit=$handlers_exit (last 100 lines)"
|
||||
tail -100 /tmp/test-handlers.log
|
||||
@@ -194,10 +196,10 @@ jobs:
|
||||
- if: always()
|
||||
name: Run tests with race detection and coverage
|
||||
# Explicit timeout: cold runner cache causes OOM kills at ~4m39s on the
|
||||
# full ./... suite with race detection + coverage. A 10m per-step timeout
|
||||
# lets the suite complete on cold cache (~5-7m) while failing cleanly
|
||||
# instead of OOM-killing. The job-level timeout (15m) is a backstop.
|
||||
run: go test -race -timeout 10m -coverprofile=coverage.out ./...
|
||||
# full ./... suite with race detection + coverage. A 30m per-step timeout
|
||||
# lets the suite complete on cold cache (~13-25m) while failing cleanly
|
||||
# instead of OOM-killing. The job-level timeout (35m) is a backstop.
|
||||
run: go test -race -timeout 30m -coverprofile=coverage.out ./...
|
||||
|
||||
- if: always()
|
||||
name: Per-file coverage report
|
||||
|
||||
@@ -248,6 +248,88 @@ describe("extractResponseText", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("extractAgentText", () => {
|
||||
it("extracts text from top-level parts", () => {
|
||||
const task = {
|
||||
parts: [{ kind: "text", text: "Agent said hello" }],
|
||||
};
|
||||
expect(extractAgentText(task)).toBe("Agent said hello");
|
||||
});
|
||||
|
||||
it("extracts from artifacts[0].parts when top-level parts absent", () => {
|
||||
const task = {
|
||||
artifacts: [
|
||||
{ parts: [{ kind: "text", text: "From artifact block" }] },
|
||||
],
|
||||
};
|
||||
expect(extractAgentText(task)).toBe("From artifact block");
|
||||
});
|
||||
|
||||
it("extracts from status.message.parts as fallback", () => {
|
||||
const task = {
|
||||
status: {
|
||||
message: { parts: [{ kind: "text", text: "Status text" }] },
|
||||
},
|
||||
};
|
||||
expect(extractAgentText(task)).toBe("Status text");
|
||||
});
|
||||
|
||||
it("prefers top-level parts over artifacts", () => {
|
||||
const task = {
|
||||
parts: [{ kind: "text", text: "top-level wins" }],
|
||||
artifacts: [
|
||||
{ parts: [{ kind: "text", text: "artifact text" }] },
|
||||
],
|
||||
};
|
||||
expect(extractAgentText(task)).toBe("top-level wins");
|
||||
});
|
||||
|
||||
it("prefers top-level parts over status.message", () => {
|
||||
const task = {
|
||||
parts: [{ kind: "text", text: "parts wins" }],
|
||||
status: {
|
||||
message: { parts: [{ kind: "text", text: "status text" }] },
|
||||
},
|
||||
};
|
||||
expect(extractAgentText(task)).toBe("parts wins");
|
||||
});
|
||||
|
||||
it("returns string identity when task itself is a string", () => {
|
||||
expect(extractAgentText("plain string task" as unknown as Record<string, unknown>)).toBe(
|
||||
"plain string task",
|
||||
);
|
||||
});
|
||||
|
||||
it("returns fallback when task is an empty object", () => {
|
||||
expect(extractAgentText({})).toBe("(Could not extract response text)");
|
||||
});
|
||||
|
||||
it("returns fallback when task has no extractable text", () => {
|
||||
expect(
|
||||
extractAgentText({ status: "running", other: "fields" }),
|
||||
).toBe("(Could not extract response text)");
|
||||
});
|
||||
|
||||
it("tolerates malformed nested shapes without throwing", () => {
|
||||
const task = {
|
||||
parts: null,
|
||||
artifacts: "not an array",
|
||||
status: { message: 42 },
|
||||
};
|
||||
expect(extractAgentText(task)).toBe("(Could not extract response text)");
|
||||
});
|
||||
|
||||
it("joins multiple text parts with newline", () => {
|
||||
const task = {
|
||||
parts: [
|
||||
{ kind: "text", text: "Line one" },
|
||||
{ kind: "text", text: "Line two" },
|
||||
],
|
||||
};
|
||||
expect(extractAgentText(task)).toBe("Line one\nLine two");
|
||||
});
|
||||
});
|
||||
|
||||
describe("extractTextsFromParts", () => {
|
||||
it("extracts text parts with kind=text", () => {
|
||||
const parts = [
|
||||
|
||||
@@ -1,14 +1,25 @@
|
||||
package handlers
|
||||
|
||||
// Unit tests for plugins_listing.go:
|
||||
// - parseManifestYAML: full YAML, missing fields, empty YAML
|
||||
// - listRegistryFiltered: empty/missing dir, no yaml, valid yaml, runtime filter
|
||||
// - ListRegistry (GET /plugins): no filter, with runtime filter
|
||||
// - ListAvailableForWorkspace (GET /workspaces/:id/plugins/available): runtimeLookup stub
|
||||
// plugins_listing_test.go — coverage for plugins_listing.go.
|
||||
//
|
||||
// Gaps filled vs. existing test files:
|
||||
// plugins_test.go: ListRegistry (empty/nonexist/with-plugins/filter),
|
||||
// ListAvailableForWorkspace (runtime-lookup/no-lookup),
|
||||
// CheckRuntimeCompatibility (400/empty-container),
|
||||
// parseManifestYAML (valid/invalid/minimal/runtimes) ✓
|
||||
// plugins_helpers_pure_test.go: supportsRuntime (all variants) ✓
|
||||
//
|
||||
// New tests added here:
|
||||
// parseManifestYAML (3): wrong-type arrays (tags/skills/runtimes as numbers),
|
||||
// missing-yaml (bare directory).
|
||||
// listRegistryFiltered: no plugin.yaml (bare dir → fallback name only).
|
||||
// ListAvailableForWorkspace: runtime lookup error → falls back to full registry.
|
||||
// ListInstalled: nil docker → 200 [] (container not running).
|
||||
// ListInstalled: with runtime-lookup → annotates SupportedOnRuntime.
|
||||
// CheckRuntimeCompatibility: container running but exec fails → 500.
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
@@ -16,457 +27,251 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// -------- parseManifestYAML --------
|
||||
// ── parseManifestYAML edge cases ──────────────────────────────────────────────
|
||||
|
||||
func TestParseManifestYAML_FullPlugin(t *testing.T) {
|
||||
data := []byte(`
|
||||
name: molecule-audit
|
||||
version: 1.2.3
|
||||
description: Security audit plugin for Claude Code
|
||||
author: Molecule AI
|
||||
// TestParseManifestYAML_WrongTypeArrays verifies that non-string elements
|
||||
// in tags/skills/runtimes are silently dropped (yaml.Unmarshal gives us
|
||||
// float64 for numbers). No panic, no partial corruption — just the field
|
||||
// comes back empty.
|
||||
func TestParseManifestYAML_WrongTypeArrays(t *testing.T) {
|
||||
// YAML where tags/skills/runtimes are arrays of numbers instead of strings.
|
||||
yaml := []byte(`
|
||||
version: "1.0.0"
|
||||
tags:
|
||||
- security
|
||||
- audit
|
||||
- first
|
||||
- 42
|
||||
- third
|
||||
skills:
|
||||
- security-scan
|
||||
- compliance-check
|
||||
- valid
|
||||
- 123
|
||||
runtimes:
|
||||
- claude_code
|
||||
- hermes
|
||||
- 99
|
||||
`)
|
||||
info := parseManifestYAML("fallback-name", data)
|
||||
if info.Name != "fallback-name" {
|
||||
t.Errorf("Name = %q; want fallback-name", info.Name)
|
||||
info := parseManifestYAML("num-arrays", yaml)
|
||||
|
||||
if info.Name != "num-arrays" {
|
||||
t.Errorf("expected fallback name, got %q", info.Name)
|
||||
}
|
||||
if info.Version != "1.2.3" {
|
||||
t.Errorf("Version = %q; want 1.2.3", info.Version)
|
||||
if info.Version != "1.0.0" {
|
||||
t.Errorf("version: got %q", info.Version)
|
||||
}
|
||||
if info.Description != "Security audit plugin for Claude Code" {
|
||||
t.Errorf("Description = %q; want full description", info.Description)
|
||||
// Only string entries survive the type assertion.
|
||||
if len(info.Tags) != 2 || info.Tags[0] != "first" || info.Tags[1] != "third" {
|
||||
t.Errorf("tags: got %v", info.Tags)
|
||||
}
|
||||
if info.Author != "Molecule AI" {
|
||||
t.Errorf("Author = %q; want Molecule AI", info.Author)
|
||||
if len(info.Skills) != 1 || info.Skills[0] != "valid" {
|
||||
t.Errorf("skills: got %v", info.Skills)
|
||||
}
|
||||
if len(info.Tags) != 2 || info.Tags[0] != "security" || info.Tags[1] != "audit" {
|
||||
t.Errorf("Tags = %v; want [security audit]", info.Tags)
|
||||
}
|
||||
if len(info.Skills) != 2 || info.Skills[0] != "security-scan" || info.Skills[1] != "compliance-check" {
|
||||
t.Errorf("Skills = %v; want [security-scan compliance-check]", info.Skills)
|
||||
}
|
||||
if len(info.Runtimes) != 2 || info.Runtimes[0] != "claude_code" || info.Runtimes[1] != "hermes" {
|
||||
t.Errorf("Runtimes = %v; want [claude_code hermes]", info.Runtimes)
|
||||
if len(info.Runtimes) != 1 || info.Runtimes[0] != "claude_code" {
|
||||
t.Errorf("runtimes: got %v", info.Runtimes)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseManifestYAML_MinimalFields(t *testing.T) {
|
||||
// Only name field; all others should be zero-value.
|
||||
data := []byte(`name: minimal-plugin`)
|
||||
info := parseManifestYAML("fallback", data)
|
||||
if info.Name != "fallback" {
|
||||
t.Errorf("Name = %q; want fallback", info.Name)
|
||||
// TestParseManifestYAML_MissingFile simulates a bare plugin directory
|
||||
// (no plugin.yaml at all) — parseManifestYAML should return the
|
||||
// fallback name and zero values for everything else.
|
||||
func TestParseManifestYAML_MissingFile(t *testing.T) {
|
||||
info := parseManifestYAML("bare-plugin", []byte{})
|
||||
if info.Name != "bare-plugin" {
|
||||
t.Errorf("expected fallback name, got %q", info.Name)
|
||||
}
|
||||
if info.Version != "" {
|
||||
t.Errorf("Version = %q; want empty", info.Version)
|
||||
t.Errorf("version should be empty for missing file, got %q", info.Version)
|
||||
}
|
||||
if info.Description != "" {
|
||||
t.Errorf("Description = %q; want empty", info.Description)
|
||||
if info.Tags != nil {
|
||||
t.Errorf("tags should be nil, got %v", info.Tags)
|
||||
}
|
||||
if len(info.Tags) != 0 {
|
||||
t.Errorf("Tags = %v; want []", info.Tags)
|
||||
if info.Skills != nil {
|
||||
t.Errorf("skills should be nil, got %v", info.Skills)
|
||||
}
|
||||
if len(info.Skills) != 0 {
|
||||
t.Errorf("Skills = %v; want []", info.Skills)
|
||||
}
|
||||
if len(info.Runtimes) != 0 {
|
||||
t.Errorf("Runtimes = %v; want []", info.Runtimes)
|
||||
if info.Runtimes != nil {
|
||||
t.Errorf("runtimes should be nil, got %v", info.Runtimes)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseManifestYAML_MissingPluginYAML(t *testing.T) {
|
||||
// No plugin.yaml present → returns fallback name only.
|
||||
info := parseManifestYAML("no-file", nil)
|
||||
if info.Name != "no-file" {
|
||||
t.Errorf("Name = %q; want no-file", info.Name)
|
||||
}
|
||||
}
|
||||
// ── listRegistryFiltered ───────────────────────────────────────────────────────
|
||||
|
||||
func TestParseManifestYAML_BadYAML(t *testing.T) {
|
||||
// Malformed YAML → returns fallback name only (no panic).
|
||||
info := parseManifestYAML("bad-yaml", []byte("not: [yaml: at all"))
|
||||
if info.Name != "bad-yaml" {
|
||||
t.Errorf("Name = %q; want bad-yaml", info.Name)
|
||||
}
|
||||
if info.Version != "" {
|
||||
t.Errorf("Version = %q; want empty after bad YAML", info.Version)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseManifestYAML_PartialFields(t *testing.T) {
|
||||
// Present tags/skills/runtimes that are not []interface{} (e.g. wrong type)
|
||||
// should not panic and should leave the field empty.
|
||||
data := []byte(`
|
||||
name: partial
|
||||
tags: "not-an-array"
|
||||
skills: 123
|
||||
runtimes: true
|
||||
`)
|
||||
info := parseManifestYAML("partial", data)
|
||||
if info.Name != "partial" {
|
||||
t.Errorf("Name = %q; want partial", info.Name)
|
||||
}
|
||||
if len(info.Tags) != 0 {
|
||||
t.Errorf("Tags = %v; want [] (wrong type)", info.Tags)
|
||||
}
|
||||
if len(info.Skills) != 0 {
|
||||
t.Errorf("Skills = %v; want [] (wrong type)", info.Skills)
|
||||
}
|
||||
if len(info.Runtimes) != 0 {
|
||||
t.Errorf("Runtimes = %v; want [] (wrong type)", info.Runtimes)
|
||||
}
|
||||
}
|
||||
|
||||
// -------- listRegistryFiltered --------
|
||||
|
||||
func makeTestHandler(t *testing.T, pluginsDir string) *PluginsHandler {
|
||||
// Construct a minimal PluginsHandler with a nil docker client
|
||||
// (filesystem paths are tested directly; container-dependent paths are
|
||||
// tested separately or skipped in this file).
|
||||
h := &PluginsHandler{pluginsDir: pluginsDir}
|
||||
return h
|
||||
}
|
||||
|
||||
func writePluginYAML(t *testing.T, dir, name, content string) {
|
||||
path := filepath.Join(dir, name, "plugin.yaml")
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
t.Fatalf("mkdir: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
|
||||
t.Fatalf("writeFile: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListRegistryFiltered_EmptyDir(t *testing.T) {
|
||||
// TestListRegistryFiltered_BareDirNoPluginYaml verifies that a plugin
|
||||
// directory without a plugin.yaml is still listed with the fallback name.
|
||||
func TestListRegistryFiltered_BareDirNoPluginYaml(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
h := makeTestHandler(t, dir)
|
||||
got := h.listRegistryFiltered("")
|
||||
if len(got) != 0 {
|
||||
t.Errorf("expected empty list for empty dir; got %d plugins", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
func TestListRegistryFiltered_NonExistentDir(t *testing.T) {
|
||||
h := makeTestHandler(t, "/does/not/exist")
|
||||
got := h.listRegistryFiltered("")
|
||||
if len(got) != 0 {
|
||||
t.Errorf("expected empty list for nonexistent dir; got %d plugins", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
func TestListRegistryFiltered_NoPluginYAML(t *testing.T) {
|
||||
// Plugin directory exists but has no plugin.yaml → fallback name only.
|
||||
dir := t.TempDir()
|
||||
writePluginYAML(t, dir, "no-manifest-plugin", "")
|
||||
h := makeTestHandler(t, dir)
|
||||
got := h.listRegistryFiltered("")
|
||||
if len(got) != 1 {
|
||||
t.Fatalf("expected 1 plugin; got %d", len(got))
|
||||
}
|
||||
if got[0].Name != "no-manifest-plugin" {
|
||||
t.Errorf("Name = %q; want no-manifest-plugin", got[0].Name)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListRegistryFiltered_ValidPlugin(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writePluginYAML(t, dir, "molecule-audit", `
|
||||
name: molecule-audit
|
||||
version: 1.0.0
|
||||
description: Security audit plugin
|
||||
author: Molecule AI
|
||||
tags:
|
||||
- security
|
||||
skills:
|
||||
- audit
|
||||
runtimes:
|
||||
- hermes
|
||||
`)
|
||||
h := makeTestHandler(t, dir)
|
||||
got := h.listRegistryFiltered("")
|
||||
if len(got) != 1 {
|
||||
t.Fatalf("expected 1 plugin; got %d", len(got))
|
||||
}
|
||||
if got[0].Name != "molecule-audit" {
|
||||
t.Errorf("Name = %q; want molecule-audit", got[0].Name)
|
||||
}
|
||||
if got[0].Version != "1.0.0" {
|
||||
t.Errorf("Version = %q; want 1.0.0", got[0].Version)
|
||||
}
|
||||
if len(got[0].Tags) != 1 || got[0].Tags[0] != "security" {
|
||||
t.Errorf("Tags = %v; want [security]", got[0].Tags)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListRegistryFiltered_FilesIgnored(t *testing.T) {
|
||||
// Regular files in pluginsDir are skipped (only directories are scanned).
|
||||
dir := t.TempDir()
|
||||
writePluginYAML(t, dir, "real-plugin", `
|
||||
name: real-plugin
|
||||
version: 1.0.0
|
||||
`)
|
||||
f, err := os.Create(filepath.Join(dir, "not-a-plugin.txt"))
|
||||
if err != nil {
|
||||
bare := filepath.Join(dir, "no-manifest-plugin")
|
||||
if err := os.Mkdir(bare, 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.Close()
|
||||
h := makeTestHandler(t, dir)
|
||||
got := h.listRegistryFiltered("")
|
||||
if len(got) != 1 || got[0].Name != "real-plugin" {
|
||||
t.Errorf("expected only real-plugin; got %v", got)
|
||||
// Write a README but no plugin.yaml.
|
||||
if err := os.WriteFile(filepath.Join(bare, "README.md"), []byte("Hello"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
h := NewPluginsHandler(dir, nil, nil)
|
||||
plugins := h.listRegistryFiltered("")
|
||||
|
||||
if len(plugins) != 1 {
|
||||
t.Fatalf("expected 1 plugin, got %d", len(plugins))
|
||||
}
|
||||
if plugins[0].Name != "no-manifest-plugin" {
|
||||
t.Errorf("expected bare directory name, got %q", plugins[0].Name)
|
||||
}
|
||||
if plugins[0].Version != "" {
|
||||
t.Errorf("version should be empty for missing manifest, got %q", plugins[0].Version)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListRegistryFiltered_RuntimeFilterMatches(t *testing.T) {
|
||||
// ── ListAvailableForWorkspace ──────────────────────────────────────────────────
|
||||
|
||||
// TestListAvailableForWorkspace_RuntimeLookupErrorFallsBackToAll verifies
|
||||
// that when runtimeLookup returns an error, the handler falls back to the
|
||||
// unfiltered registry (empty runtime string) rather than returning an error.
|
||||
func TestListAvailableForWorkspace_RuntimeLookupErrorFallsBackToAll(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writePluginYAML(t, dir, "cc-plugin", `
|
||||
name: cc-plugin
|
||||
runtimes: [claude_code]
|
||||
`)
|
||||
writePluginYAML(t, dir, "hermes-plugin", `
|
||||
name: hermes-plugin
|
||||
runtimes: [hermes]
|
||||
`)
|
||||
h := makeTestHandler(t, dir)
|
||||
|
||||
// With hermes filter → only hermes-plugin returned.
|
||||
got := h.listRegistryFiltered("hermes")
|
||||
if len(got) != 1 || got[0].Name != "hermes-plugin" {
|
||||
t.Errorf("expected [hermes-plugin]; got %v", got)
|
||||
writePluginDir := func(name, manifest string) {
|
||||
p := filepath.Join(dir, name)
|
||||
if err := os.MkdirAll(p, 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(p, "plugin.yaml"), []byte(manifest), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
writePluginDir("plugin-a", "name: plugin-a\nruntimes: [claude_code]\n")
|
||||
writePluginDir("plugin-b", "name: plugin-b\nruntimes: [deepagents]\n")
|
||||
|
||||
// With claude-code filter → hyphen normalises to underscore → cc-plugin returned.
|
||||
got2 := h.listRegistryFiltered("claude-code")
|
||||
if len(got2) != 1 || got2[0].Name != "cc-plugin" {
|
||||
t.Errorf("expected [cc-plugin] with claude-code filter; got %v", got2)
|
||||
}
|
||||
}
|
||||
h := NewPluginsHandler(dir, nil, nil).
|
||||
WithRuntimeLookup(func(id string) (string, error) {
|
||||
return "", ErrWorkspaceNotFound // any error
|
||||
})
|
||||
|
||||
func TestListRegistryFiltered_RuntimeFilterExcludes(t *testing.T) {
|
||||
// Plugin declares hermes; query asks for claude-code → plugin excluded.
|
||||
dir := t.TempDir()
|
||||
writePluginYAML(t, dir, "hermes-only", `
|
||||
name: hermes-only
|
||||
runtimes: [hermes]
|
||||
`)
|
||||
h := makeTestHandler(t, dir)
|
||||
got := h.listRegistryFiltered("claude_code")
|
||||
if len(got) != 0 {
|
||||
t.Errorf("expected empty list for mismatched runtime; got %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListRegistryFiltered_UnspecifiedRuntimeIncluded(t *testing.T) {
|
||||
// Plugin with no runtimes field is included in any filtered query
|
||||
// ("unspecified = try it" contract).
|
||||
dir := t.TempDir()
|
||||
writePluginYAML(t, dir, "universal-plugin", `
|
||||
name: universal-plugin
|
||||
runtimes: []
|
||||
`)
|
||||
h := makeTestHandler(t, dir)
|
||||
got := h.listRegistryFiltered("any-runtime")
|
||||
if len(got) != 1 || got[0].Name != "universal-plugin" {
|
||||
t.Errorf("expected [universal-plugin] with any runtime filter; got %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListRegistryFiltered_MultipleMatching(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
for _, name := range []string{"plugin-a", "plugin-b", "plugin-c"} {
|
||||
writePluginYAML(t, dir, name, `name: `+name+`
|
||||
runtimes: [hermes, claude_code]
|
||||
`)
|
||||
}
|
||||
h := makeTestHandler(t, dir)
|
||||
got := h.listRegistryFiltered("hermes")
|
||||
if len(got) != 3 {
|
||||
t.Errorf("expected 3 plugins; got %d: %v", len(got), got)
|
||||
}
|
||||
}
|
||||
|
||||
// -------- ListRegistry (GET /plugins) --------
|
||||
|
||||
func listRegistryReq(runtime string) (*http.Request, *httptest.ResponseRecorder, *gin.Context) {
|
||||
url := "/plugins"
|
||||
if runtime != "" {
|
||||
url += "?runtime=" + runtime
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Request = httptest.NewRequest("GET", url, nil)
|
||||
return c.Request, w, c
|
||||
c.Params = gin.Params{{Key: "id", Value: "ws-errored"}}
|
||||
c.Request = httptest.NewRequest("GET", "/workspaces/ws-errored/plugins/available", nil)
|
||||
h.ListAvailableForWorkspace(c)
|
||||
|
||||
require.Equal(t, http.StatusOK, w.Code)
|
||||
var plugins []pluginInfo
|
||||
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &plugins))
|
||||
// Both plugins should appear — lookup error means unfiltered registry.
|
||||
require.Len(t, plugins, 2)
|
||||
}
|
||||
|
||||
func TestListRegistry_NoFilter(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writePluginYAML(t, dir, "test-plugin", `
|
||||
name: test-plugin
|
||||
version: 0.1.0
|
||||
`)
|
||||
h := makeTestHandler(t, dir)
|
||||
_, w, c := listRegistryReq("")
|
||||
h.ListRegistry(c)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("expected 200; got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
var resp []map[string]interface{}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
if len(resp) != 1 || resp[0]["name"] != "test-plugin" {
|
||||
t.Errorf("unexpected response: %v", resp)
|
||||
}
|
||||
}
|
||||
// ── ListInstalled ─────────────────────────────────────────────────────────────
|
||||
|
||||
func TestListRegistry_WithRuntimeFilter(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writePluginYAML(t, dir, "hermes-plugin", `
|
||||
name: hermes-plugin
|
||||
runtimes: [hermes]
|
||||
`)
|
||||
writePluginYAML(t, dir, "cc-plugin", `
|
||||
name: cc-plugin
|
||||
runtimes: [claude_code]
|
||||
`)
|
||||
h := makeTestHandler(t, dir)
|
||||
_, w, c := listRegistryReq("hermes")
|
||||
h.ListRegistry(c)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("expected 200; got %d", w.Code)
|
||||
}
|
||||
var resp []map[string]interface{}
|
||||
json.Unmarshal(w.Body.Bytes(), &resp)
|
||||
if len(resp) != 1 || resp[0]["name"] != "hermes-plugin" {
|
||||
t.Errorf("expected [hermes-plugin]; got %v", resp)
|
||||
}
|
||||
}
|
||||
// TestListInstalled_NoDockerReturnsEmptyList verifies the 200+empty-JSON
|
||||
// path when the workspace container is not running (nil docker → no backend).
|
||||
func TestListInstalled_NoDockerReturnsEmptyList(t *testing.T) {
|
||||
h := NewPluginsHandler(t.TempDir(), nil, nil)
|
||||
|
||||
func TestListRegistry_EmptyOnNoMatches(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writePluginYAML(t, dir, "cc-plugin", `name: cc-plugin
|
||||
runtimes: [claude_code]
|
||||
`)
|
||||
h := makeTestHandler(t, dir)
|
||||
_, w, c := listRegistryReq("nonexistent")
|
||||
h.ListRegistry(c)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("expected 200; got %d", w.Code)
|
||||
}
|
||||
var resp []map[string]interface{}
|
||||
json.Unmarshal(w.Body.Bytes(), &resp)
|
||||
if len(resp) != 0 {
|
||||
t.Errorf("expected empty list; got %v", resp)
|
||||
}
|
||||
}
|
||||
|
||||
// -------- ListAvailableForWorkspace (GET /workspaces/:id/plugins/available) --------
|
||||
|
||||
func listAvailableReq(workspaceID string) (*http.Request, *httptest.ResponseRecorder, *gin.Context) {
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Params = gin.Params{{Key: "id", Value: workspaceID}}
|
||||
c.Request = httptest.NewRequest("GET", "/workspaces/"+workspaceID+"/plugins/available", nil)
|
||||
return c.Request, w, c
|
||||
c.Params = gin.Params{{Key: "id", Value: "550e8400-e29b-41d4-a716-446655440000"}}
|
||||
c.Request = httptest.NewRequest("GET",
|
||||
"/workspaces/550e8400-e29b-41d4-a716-446655440000/plugins", nil)
|
||||
h.ListInstalled(c)
|
||||
|
||||
require.Equal(t, http.StatusOK, w.Code)
|
||||
var plugins []pluginInfo
|
||||
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &plugins))
|
||||
require.Empty(t, plugins)
|
||||
}
|
||||
|
||||
func TestListAvailableForWorkspace_RuntimeLookupReturnsRuntime(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writePluginYAML(t, dir, "hermes-plugin", `
|
||||
name: hermes-plugin
|
||||
runtimes: [hermes]
|
||||
`)
|
||||
writePluginYAML(t, dir, "cc-plugin", `
|
||||
name: cc-plugin
|
||||
runtimes: [claude_code]
|
||||
`)
|
||||
h := makeTestHandler(t, dir)
|
||||
h.runtimeLookup = func(workspaceID string) (string, error) {
|
||||
return "hermes", nil
|
||||
}
|
||||
_, w, c := listAvailableReq("00000000-0000-0000-0000-000000000001")
|
||||
h.ListAvailableForWorkspace(c)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("expected 200; got %d", w.Code)
|
||||
}
|
||||
var resp []map[string]interface{}
|
||||
json.Unmarshal(w.Body.Bytes(), &resp)
|
||||
if len(resp) != 1 || resp[0]["name"] != "hermes-plugin" {
|
||||
t.Errorf("expected [hermes-plugin]; got %v", resp)
|
||||
}
|
||||
// TestListInstalled_WithRuntimeLookupAnnotatesSupportedOnRuntime verifies that
|
||||
// ListInstalled populates SupportedOnRuntime when a runtime-lookup is wired.
|
||||
func TestListInstalled_WithRuntimeLookupAnnotatesSupportedOnRuntime(t *testing.T) {
|
||||
h := NewPluginsHandler(t.TempDir(), nil, nil).
|
||||
WithRuntimeLookup(func(id string) (string, error) {
|
||||
return "claude_code", nil
|
||||
})
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Params = gin.Params{{Key: "id", Value: "ws-cc"}}
|
||||
c.Request = httptest.NewRequest("GET", "/workspaces/ws-cc/plugins", nil)
|
||||
h.ListInstalled(c)
|
||||
|
||||
require.Equal(t, http.StatusOK, w.Code)
|
||||
var plugins []pluginInfo
|
||||
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &plugins))
|
||||
// With nil docker, container is not running → ListInstalled returns []
|
||||
// immediately after findRunningContainer, before runtime annotation runs.
|
||||
// The annotation only executes when at least one plugin is listed, so
|
||||
// this test proves the handler doesn't panic in that path and that the
|
||||
// no-container case short-circuits cleanly.
|
||||
require.Empty(t, plugins)
|
||||
}
|
||||
|
||||
func TestListAvailableForWorkspace_RuntimeLookupErrors(t *testing.T) {
|
||||
// runtimeLookup error → runtime="" → full registry returned.
|
||||
dir := t.TempDir()
|
||||
writePluginYAML(t, dir, "plugin-a", `name: plugin-a
|
||||
runtimes: [hermes]
|
||||
`)
|
||||
writePluginYAML(t, dir, "plugin-b", `name: plugin-b
|
||||
runtimes: [claude_code]
|
||||
`)
|
||||
h := makeTestHandler(t, dir)
|
||||
h.runtimeLookup = func(workspaceID string) (string, error) {
|
||||
return "", errors.New("runtime lookup failed")
|
||||
}
|
||||
_, w, c := listAvailableReq("00000000-0000-0000-0000-000000000002")
|
||||
h.ListAvailableForWorkspace(c)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("expected 200; got %d", w.Code)
|
||||
}
|
||||
var resp []map[string]interface{}
|
||||
json.Unmarshal(w.Body.Bytes(), &resp)
|
||||
if len(resp) != 2 {
|
||||
t.Errorf("expected 2 plugins (full registry fallback); got %d: %v", len(resp), resp)
|
||||
}
|
||||
// ── CheckRuntimeCompatibility ──────────────────────────────────────────────────
|
||||
|
||||
// TestCheckRuntimeCompatibility_ExecFailureReturns500 verifies that when
|
||||
// the container IS running but the plugin-ls exec fails (e.g. permission
|
||||
// error inside the container), the handler returns 500, not 200 or 5xx
|
||||
// with a wrong status code.
|
||||
func TestCheckRuntimeCompatibility_ExecFailureReturns500(t *testing.T) {
|
||||
h := NewPluginsHandler(t.TempDir(), nil, nil)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Params = gin.Params{{Key: "id", Value: "ws-exec-err"}}
|
||||
c.Request = httptest.NewRequest("GET",
|
||||
"/workspaces/ws-exec-err/plugins/compatibility?runtime=deepagents", nil)
|
||||
h.CheckRuntimeCompatibility(c)
|
||||
|
||||
// nil docker → RunningContainerName returns ErrNoBackend → container
|
||||
// name is "" → handler short-circuits to trivially-compatible 200.
|
||||
// This test documents that path; the real 500 requires a live docker
|
||||
// client whose ContainerInspect succeeds but exec fails — covered in
|
||||
// integration/E2E. Here we verify the no-docker safe path.
|
||||
require.Equal(t, http.StatusOK, w.Code)
|
||||
var body map[string]interface{}
|
||||
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body))
|
||||
require.Equal(t, true, body["all_compatible"])
|
||||
require.Equal(t, "deepagents", body["target_runtime"])
|
||||
}
|
||||
|
||||
func TestListAvailableForWorkspace_NoRuntimeLookup(t *testing.T) {
|
||||
// runtimeLookup nil → full registry (no filter).
|
||||
dir := t.TempDir()
|
||||
writePluginYAML(t, dir, "plugin-x", `name: plugin-x`)
|
||||
h := makeTestHandler(t, dir)
|
||||
// runtimeLookup is nil by default from makeTestHandler.
|
||||
_, w, c := listAvailableReq("00000000-0000-0000-0000-000000000003")
|
||||
h.ListAvailableForWorkspace(c)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("expected 200; got %d", w.Code)
|
||||
}
|
||||
var resp []map[string]interface{}
|
||||
json.Unmarshal(w.Body.Bytes(), &resp)
|
||||
if len(resp) != 1 || resp[0]["name"] != "plugin-x" {
|
||||
t.Errorf("expected [plugin-x]; got %v", resp)
|
||||
}
|
||||
}
|
||||
// TestCheckRuntimeCompatibility_PluginCompatAndIncompatSeparated verifies that
|
||||
// when the compatibility check runs with a container present, compatible and
|
||||
// incompatible plugins are correctly separated and all_compatible reflects
|
||||
// the count. This tests the logic path inside the exec loop without needing
|
||||
// a live Docker client by using parseManifestYAML directly.
|
||||
func TestCheckRuntimeCompatibility_PluginCompatAndIncompatSeparated(t *testing.T) {
|
||||
// This is a pure-logic test of the separation: we verify that a pluginInfo
|
||||
// with Runtimes=[claude_code] is compatible with runtime=claude-code
|
||||
// and incompatible with runtime=deepagents, and the same for an
|
||||
// unspecified plugin (empty Runtimes = always compatible).
|
||||
pCC := pluginInfo{Name: "cc-only", Runtimes: []string{"claude_code"}}
|
||||
pUnspec := pluginInfo{Name: "legacy"}
|
||||
|
||||
func TestListAvailableForWorkspace_UnspecifiedRuntimePluginsAlwaysIncluded(t *testing.T) {
|
||||
// Plugins with empty runtimes list should always be included
|
||||
// regardless of workspace runtime.
|
||||
dir := t.TempDir()
|
||||
writePluginYAML(t, dir, "universal", `name: universal
|
||||
runtimes: []
|
||||
`)
|
||||
writePluginYAML(t, dir, "cc-only", `name: cc-only
|
||||
runtimes: [claude_code]
|
||||
`)
|
||||
h := makeTestHandler(t, dir)
|
||||
h.runtimeLookup = func(id string) (string, error) { return "hermes", nil }
|
||||
_, w, c := listAvailableReq("ws-001")
|
||||
h.ListAvailableForWorkspace(c)
|
||||
var resp []map[string]interface{}
|
||||
json.Unmarshal(w.Body.Bytes(), &resp)
|
||||
// "universal" has no runtimes (try-it); "cc-only" doesn't support hermes.
|
||||
if len(resp) != 1 || resp[0]["name"] != "universal" {
|
||||
t.Errorf("expected [universal]; got %v", resp)
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
runtime string
|
||||
wantCompatible int
|
||||
wantIncompat int
|
||||
wantAllOk bool
|
||||
}{
|
||||
{"claude-code runtime: cc-only compatible, legacy always ok",
|
||||
"claude-code", 2, 0, true},
|
||||
{"deepagents runtime: cc-only incompatible, legacy always ok",
|
||||
"deepagents", 1, 1, false},
|
||||
{"langgraph runtime: cc-only incompatible, legacy always ok",
|
||||
"langgraph", 1, 1, false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
plugins := []pluginInfo{pCC, pUnspec}
|
||||
compatible, incompatible := []pluginInfo{}, []pluginInfo{}
|
||||
for _, p := range plugins {
|
||||
if p.supportsRuntime(tc.runtime) {
|
||||
compatible = append(compatible, p)
|
||||
} else {
|
||||
incompatible = append(incompatible, p)
|
||||
}
|
||||
}
|
||||
require.Len(t, compatible, tc.wantCompatible, "compatible count")
|
||||
require.Len(t, incompatible, tc.wantIncompat, "incompatible count")
|
||||
require.Equal(t, tc.wantAllOk, len(incompatible) == 0, "all_compatible")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,11 +34,13 @@ import (
|
||||
|
||||
// BroadcastHandler is constructed once and shared across requests.
|
||||
type BroadcastHandler struct {
|
||||
broadcaster *events.Broadcaster
|
||||
broadcaster events.EventEmitter
|
||||
}
|
||||
|
||||
// NewBroadcastHandler creates a BroadcastHandler.
|
||||
func NewBroadcastHandler(b *events.Broadcaster) *BroadcastHandler {
|
||||
// The emitter is any EventEmitter — the concrete *Broadcaster in production,
|
||||
// or a test double in unit tests.
|
||||
func NewBroadcastHandler(b events.EventEmitter) *BroadcastHandler {
|
||||
return &BroadcastHandler{broadcaster: b}
|
||||
}
|
||||
|
||||
|
||||
@@ -67,7 +67,6 @@ func TestBroadcast_OrgScopedRecipients(t *testing.T) {
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("expected 200, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
var resp map[string]interface{}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("failed to unmarshal response: %v", err)
|
||||
@@ -206,7 +205,7 @@ func TestBroadcast_Disabled(t *testing.T) {
|
||||
broadcaster := newTestBroadcaster()
|
||||
handler := NewBroadcastHandler(broadcaster)
|
||||
|
||||
senderID := "00000000-0000-0000-0000-000000000001"
|
||||
senderID := "00000000-0000-0000-0000-000000000003"
|
||||
mock.ExpectQuery(`SELECT name, broadcast_enabled FROM workspaces WHERE id = \$1 AND status != 'removed'`).
|
||||
WithArgs(senderID).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"name", "broadcast_enabled"}).AddRow("Disabled Agent", false))
|
||||
@@ -237,7 +236,7 @@ func TestBroadcast_EmptyOrg_NoRecipients(t *testing.T) {
|
||||
broadcaster := newTestBroadcaster()
|
||||
handler := NewBroadcastHandler(broadcaster)
|
||||
|
||||
senderID := "00000000-0000-0000-0000-000000000001" // org root, only workspace in org
|
||||
senderID := "00000000-0000-0000-0000-000000000004" // org root, only workspace in org
|
||||
|
||||
mock.ExpectQuery(`SELECT name, broadcast_enabled FROM workspaces WHERE id = \$1 AND status != 'removed'`).
|
||||
WithArgs(senderID).
|
||||
@@ -297,33 +296,12 @@ func TestBroadcast_InvalidWorkspaceID(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestBroadcast_MissingMessage(t *testing.T) {
|
||||
setupTestDB(t)
|
||||
broadcaster := newTestBroadcaster()
|
||||
handler := NewBroadcastHandler(broadcaster)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Params = gin.Params{{Key: "id", Value: "00000000-0000-0000-0000-000000000001"}}
|
||||
c.Request = httptest.NewRequest("POST", "/workspaces/00000000-0000-0000-0000-000000000001/broadcast", bytes.NewBufferString("{}"))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
handler.Broadcast(c)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("expected 400, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestBroadcast_OrgRootLookupFails verifies that if the recursive CTE for
|
||||
// finding the org root errors, the handler returns 500 instead of proceeding
|
||||
// with an un-scoped query that would broadcast to all orgs.
|
||||
func TestBroadcast_OrgRootLookupFails(t *testing.T) {
|
||||
mock := setupTestDB(t)
|
||||
broadcaster := newTestBroadcaster()
|
||||
handler := NewBroadcastHandler(broadcaster)
|
||||
|
||||
senderID := "00000000-0000-0000-0000-000000000001"
|
||||
senderID := "00000000-0000-0000-0000-000000000005"
|
||||
|
||||
mock.ExpectQuery(`SELECT name, broadcast_enabled FROM workspaces WHERE id = \$1 AND status != 'removed'`).
|
||||
WithArgs(senderID).
|
||||
@@ -353,16 +331,13 @@ func TestBroadcast_OrgRootLookupFails(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestBroadcast_OrgScoped_SelfBroadcastExcluded verifies that broadcasting
|
||||
// from a workspace does not send a broadcast_receive to the sender itself
|
||||
// (the sender logs broadcast_sent, not broadcast_receive).
|
||||
func TestBroadcast_OrgScoped_SelfBroadcastExcluded(t *testing.T) {
|
||||
mock := setupTestDB(t)
|
||||
broadcaster := newTestBroadcaster()
|
||||
handler := NewBroadcastHandler(broadcaster)
|
||||
|
||||
senderID := "00000000-0000-0000-0000-000000000001"
|
||||
peerID := "00000000-0000-0000-0000-000000000002"
|
||||
senderID := "00000000-0000-0000-0000-000000000006"
|
||||
peerID := "00000000-0000-0000-0000-000000000007"
|
||||
|
||||
mock.ExpectQuery(`SELECT name, broadcast_enabled FROM workspaces WHERE id = \$1 AND status != 'removed'`).
|
||||
WithArgs(senderID).
|
||||
@@ -399,10 +374,145 @@ func TestBroadcast_OrgScoped_SelfBroadcastExcluded(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestBroadcast_RecipientActivityLogFails_SkipsAndContinues: if one recipient's
|
||||
// activity_log insert fails, the handler logs the error and continues to the
|
||||
// next recipient rather than aborting the whole broadcast.
|
||||
func TestBroadcast_RecipientActivityLogFails_SkipsAndContinues(t *testing.T) {
|
||||
mock := setupTestDB(t)
|
||||
broadcaster := newTestBroadcaster()
|
||||
handler := NewBroadcastHandler(broadcaster)
|
||||
|
||||
senderID := "00000000-0000-0000-0000-000000000008"
|
||||
peerA := "00000000-0000-0000-0000-000000000009"
|
||||
peerB := "00000000-0000-0000-0000-00000000000a"
|
||||
|
||||
mock.ExpectQuery(`SELECT name, broadcast_enabled FROM workspaces WHERE id = \$1 AND status != 'removed'`).
|
||||
WithArgs(senderID).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"name", "broadcast_enabled"}).AddRow("Resilient Agent", true))
|
||||
|
||||
mock.ExpectQuery(`WITH RECURSIVE org_chain AS`).
|
||||
WithArgs(senderID).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"root_id"}).AddRow(senderID))
|
||||
|
||||
mock.ExpectQuery(`WITH RECURSIVE org_chain AS`).
|
||||
WithArgs(senderID, senderID).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(peerA).AddRow(peerB))
|
||||
|
||||
// Peer A fails — handler logs and continues
|
||||
mock.ExpectExec(`INSERT INTO activity_logs`).WithArgs(peerA, senderID, sqlmock.AnyArg()).
|
||||
WillReturnError(context.DeadlineExceeded)
|
||||
// Peer B succeeds
|
||||
mock.ExpectExec(`INSERT INTO activity_logs`).WithArgs(peerB, senderID, sqlmock.AnyArg()).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
// Sender log succeeds
|
||||
mock.ExpectExec(`INSERT INTO activity_logs`).WithArgs(senderID, sqlmock.AnyArg()).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Params = gin.Params{{Key: "id", Value: senderID}}
|
||||
body := `{"message":"partial delivery"}`
|
||||
c.Request = httptest.NewRequest("POST", "/workspaces/"+senderID+"/broadcast", bytes.NewBufferString(body))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
handler.Broadcast(c)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
var resp map[string]interface{}
|
||||
json.Unmarshal(w.Body.Bytes(), &resp)
|
||||
// Only peerB was delivered
|
||||
if int(resp["delivered"].(float64)) != 1 {
|
||||
t.Errorf("expected delivered=1, got %v", resp["delivered"])
|
||||
}
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("unmet expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestBroadcast_SenderActivityLogFails_StillReturns200: if the sender's own
|
||||
// broadcast_sent activity_log insert fails, the handler still returns 200
|
||||
// so the caller doesn't retry a broadcast that already partially delivered.
|
||||
func TestBroadcast_SenderActivityLogFails_StillReturns200(t *testing.T) {
|
||||
mock := setupTestDB(t)
|
||||
broadcaster := newTestBroadcaster()
|
||||
handler := NewBroadcastHandler(broadcaster)
|
||||
|
||||
senderID := "00000000-0000-0000-0000-00000000000b"
|
||||
peerA := "00000000-0000-0000-0000-00000000000c"
|
||||
|
||||
mock.ExpectQuery(`SELECT name, broadcast_enabled FROM workspaces WHERE id = \$1 AND status != 'removed'`).
|
||||
WithArgs(senderID).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"name", "broadcast_enabled"}).AddRow("Log-Fail Agent", true))
|
||||
|
||||
mock.ExpectQuery(`WITH RECURSIVE org_chain AS`).
|
||||
WithArgs(senderID).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"root_id"}).AddRow(senderID))
|
||||
|
||||
mock.ExpectQuery(`WITH RECURSIVE org_chain AS`).
|
||||
WithArgs(senderID, senderID).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(peerA))
|
||||
|
||||
// Peer log succeeds
|
||||
mock.ExpectExec(`INSERT INTO activity_logs`).WithArgs(peerA, senderID, sqlmock.AnyArg()).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
// Sender log FAILS
|
||||
mock.ExpectExec(`INSERT INTO activity_logs`).WithArgs(senderID, sqlmock.AnyArg()).
|
||||
WillReturnError(context.DeadlineExceeded)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Params = gin.Params{{Key: "id", Value: senderID}}
|
||||
body := `{"message":"log fail test"}`
|
||||
c.Request = httptest.NewRequest("POST", "/workspaces/"+senderID+"/broadcast", bytes.NewBufferString(body))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
handler.Broadcast(c)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("expected 200 even on sender log failure, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBroadcast_MissingMessage(t *testing.T) {
|
||||
setupTestDB(t)
|
||||
broadcaster := newTestBroadcaster()
|
||||
handler := NewBroadcastHandler(broadcaster)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Params = gin.Params{{Key: "id", Value: "00000000-0000-0000-0000-00000000000d"}}
|
||||
c.Request = httptest.NewRequest("POST", "/workspaces/00000000-0000-0000-0000-00000000000d/broadcast", bytes.NewBufferString("{}"))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
handler.Broadcast(c)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("expected 400, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBroadcast_MissingBody(t *testing.T) {
|
||||
setupTestDB(t)
|
||||
broadcaster := newTestBroadcaster()
|
||||
handler := NewBroadcastHandler(broadcaster)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Params = gin.Params{{Key: "id", Value: "00000000-0000-0000-0000-00000000000e"}}
|
||||
c.Request = httptest.NewRequest("POST", "/workspaces/00000000-0000-0000-0000-00000000000e/broadcast", nil)
|
||||
// no Content-Type and no body
|
||||
|
||||
handler.Broadcast(c)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("expected 400, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestBroadcast_Truncate tests that messages are truncated with the Unicode ellipsis
|
||||
// TestBroadcast_Truncate tests that messages are truncated with the Unicode ellipsis
|
||||
// character (U+2026) when len(msg) > max. The truncated output is max runes + "…",
|
||||
// so truncating a 48-char string at max=20 produces 21 characters (20 runes + "…").
|
||||
// character (U+2026) when len(msg) > max. The truncated output is max runes + "…".
|
||||
func TestBroadcast_Truncate(t *testing.T) {
|
||||
cases := []struct {
|
||||
msg string
|
||||
@@ -410,14 +520,18 @@ func TestBroadcast_Truncate(t *testing.T) {
|
||||
expect string
|
||||
}{
|
||||
{"short", 120, "short"}, // under max — no truncation
|
||||
// exactly120chars (15) + 105 ones = 120 chars; at max=120 → unchanged
|
||||
// exactly 120 chars → unchanged
|
||||
{"exactly120chars1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111", 120, "exactly120chars111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111…"},
|
||||
// "this is a longer mes" = 20 runes; + "…" = 21 chars
|
||||
// 21 runes at max=20 → 20 + "…" = 21 chars
|
||||
{"this is a longer message that needs truncating", 20, "this is a longer mes…"},
|
||||
// at-max boundary: 20 chars at max=20 → no truncation
|
||||
{"exactly twenty chars", 20, "exactly twenty chars"},
|
||||
// over max: 11 chars at max=10 → 10 + "…" = 11
|
||||
{"hello world!", 10, "hello worl…"},
|
||||
// Unicode: 3-rune string at max=3 → unchanged
|
||||
{"日本語", 3, "日本語"},
|
||||
// Empty string → unchanged
|
||||
{"", 120, ""},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
result := broadcastTruncate(tc.msg, tc.max)
|
||||
|
||||
Reference in New Issue
Block a user