952 Commits
Author SHA1 Message Date
Sergey KozyrenkoandClaude Opus 5.5 cffed9485a docs: the README links Graphiti to its public repository and names the image PentAGI runs
The link pointed to vxcontrol/pentagi-graphiti, which readers outside the organization get as a 404.
Graphiti now links to getzep/graphiti, and the fork is named by the vxcontrol/graphiti image on
Docker Hub that docker-compose-graphiti.yml pulls.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 06:20:46 +07:00
Sergey KozyrenkoandClaude Opus 5.5 843dfeb4bf docs: the README says what PentAGI is, who it is for, how it differs and how to install it
The overview was generic; it now answers those four questions in the wording of pentagi.com.
The README, config.md and the installation guide no longer list MCP among the server-side
settings: the open-source edition has no MCP code, and Enterprise adds MCP servers. SearXNG is
spelled as its project spells it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 03:53:25 +07:00
Sergey KozyrenkoandClaude Opus 5.5 e7f3000832 docs(PAGI-561): the README names VXControl as the developer of PentAGI
Asked who develops PentAGI, assistants cite this README and press
articles, yet the README named no developer and never linked
vxcontrol.com; asked what VXControl is, they also describe other
products of that name. The overview now says PentAGI is developed by
VXControl and links its site.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 21:06:34 +07:00
Dmitry Ng b611fbebcf fix: installer stack detection, tests that can fail, proxy and port docs
- installer: decide whether the stack is extracted by the provider examples
  beside the env file, not in the working directory
- tests: assert table cells in the markdown editor pipe tests; pin the
  prompter in provider failover, the permission error on a password change
  and the built-in Bedrock config against its shipped example
- docs: state what PROXY_URL covers and which ports flows publish; name the
  cgr.dev registry of the Langfuse stack
- comments: drop history and restated code, correct those that had drifted
  from the code
2026-10-04 01:18:50 +03:00
Dmitry Ng 55a063ecb3 feat(provider): add Bedrock provider configuration and update related documentation
- Introduced a new example configuration file for the Bedrock provider, ensuring compatibility with the existing stack.
- Updated Docker and docker-compose configurations to include the new Bedrock provider, enhancing the overall functionality of the application.
- Revised README and other documentation to reflect the addition of the Bedrock provider, including environment variable descriptions and usage instructions.
- Improved installer logic to handle the new provider configuration seamlessly, ensuring a smooth user experience during setup.
2026-10-03 00:15:29 +03:00
Dmitry Ng fc6f2e3443 docs: update README with new Trendshift badges and configuration details 2026-10-03 00:04:54 +03:00
Dmitry Ng 3cfe5cba4b refactor: improve document handling and validation in knowledge management
- Updated knowledge document creation and update functions to store content as sent, preserving whitespace and line breaks.
- Enhanced validation for flow template fields to ensure titles are trimmed while text retains its original format.
- Refactored tests to verify that blank content is rejected and that stored content matches the input, including line breaks.
- Updated markdown editor to maintain content integrity during serialization and deserialization processes.
- Improved documentation to clarify how content is stored and processed, ensuring consistency across the application.
2026-10-02 09:51:01 +03:00
Dmitry Ng 3b7c75f9e9 chore(deps): update OpenTelemetry and related dependencies
- Upgraded OpenTelemetry packages to the latest versions, including otel v1.45.0 and otlp exporters.
- Updated various indirect dependencies to their latest stable releases, improving compatibility and performance.
- Enhanced observability tests with new logging and tracing functionalities, ensuring better integration with OpenTelemetry.
- Refactored logging attributes to utilize the new OpenTelemetry attribute types for improved clarity and consistency.
2026-10-01 16:18:00 +03:00
Dmitry Ng 01acdda6d3 fix: failover on flow creation, minio image, stable build revisions
- Failover: when the primary provider is down, flow and assistant creation now falls back for the tool call ID template.
- Prompts: a stored custom prompt that no longer validates is ignored in favor of the default, with a warning, instead of rendering "<no value>".
- Security: PUT /users/{hash} refuses a password change without users.edit, so a stolen session cookie can no longer reset the account password.
- Langfuse: minio/minio is gone from Docker Hub, so the stack runs cgr.dev/chainguard/minio:latest as root to keep existing volumes readable.
- Installer: the main menu highlights Maintenance while a worker, stack or installer update is waiting.
- Versions: the build revision is the first 7 characters of the commit SHA instead of git rev-parse --short, which depends on the size of the clone.
- Tests: the docker pids-limit test sets its limit after the probes start, so the setup execs no longer exhaust it on slow CI runners.
- Docs: README covers Azure OpenAI through the custom provider and the Neo4j/APOC files a manual Graphiti install needs.
- Reports: added the Azure OpenAI ctester report and regenerated vllm-mixed for Qwen3.8.
2026-10-01 00:55:56 +03:00
Dmitry Ng 6f3d29c3f1 feat: port major fixes 2026-09-30 01:48:35 +03:00
Dmitry Ng 8b2deb6a53 feat(provider): add qwen3.8-27b fp8 provider configuration and testing report
- Introduced a new configuration file for the Qwen3.8-27B FP8 provider, detailing model settings and recommended sampling parameters for various tasks.
- Created a comprehensive testing report summarizing agent performance, success rates, and average latencies across multiple test scenarios.
- Ensured the configuration aligns with official Qwen recommendations for optimal inference performance.
2026-09-02 02:39:04 +03:00
Dmitry Ng 6f34a010e1 feat(cloud): enhance VXControl Cloud API usage and add PentAGI version checks 2026-09-02 02:31:59 +03:00
Dmitry Ng 2d39d1f74d feat(installer): new checking updates protocol and bump cloud sdk version to v1.0.0
- Introduced new checks for stack components in the installer checker, ensuring accurate reporting of connection and external status for Graphiti, Langfuse, and Observability.
- Added comprehensive unit tests to validate the behavior of the new checks, covering various configurations and expected outcomes.
- Updated the go.mod file to include new dependencies and upgraded existing ones for improved functionality.
- Created new test files for component checks and product information, enhancing overall test coverage and reliability.
2026-08-12 23:24:12 +03:00
Dmitry Ng 17bc0e16c7 feat(docker): update environment variables for stack images in docker-compose files
- Added new environment variables for PentAGI, Graphiti, Langfuse, and Observability stack images in the .env.example file.
- Updated docker-compose files to use these environment variables for service images, enhancing configurability and maintainability.
- Ensured default values are retained for backward compatibility.
2026-08-12 23:08:43 +03:00
Dmitry Ng 93e9974851 feat(provider): update Qwen provider configuration and testing reports
- Revised Qwen provider configuration to reflect new model assignments, including the introduction of deepseek-v4 models and updated pricing structures.
- Enhanced testing reports with detailed performance metrics, including success rates and average latencies for various agents.
- Added new testing report for qwen-cloud, summarizing agent performance and success rates.
- Updated VSCode launch configuration to include new report options for testing.
2026-08-08 19:54:10 +03:00
Dmitry Ng ea665308ba fix(deps): upgrade langchaingo version to release version v0.1.14-update.7 2026-08-06 14:06:47 +03:00
Dmitry Ng a4dcfa8178 feat(provider): update OpenCode provider configuration and testing report
- Enhanced OpenCode provider configuration with detailed pricing for various models.
- Updated agent settings to reflect new model assignments and pricing structures.
- Revised testing report to include updated performance metrics and average latencies for agents.
- Adjusted overall success rates and latencies in the report for improved accuracy.
2026-08-04 23:57:58 +03:00
Dmitry Ng 454569a8eb feat(provider): add OpenCode provider configuration and testing report
- Added OpenCode provider configuration file with model settings and parameters.
- Updated README to include OpenCode as a supported provider and modified relevant sections for clarity.
- Created a testing report for OpenCode, summarizing agent performance and success rates.
- Enhanced VSCode launch configuration to include OpenCode provider options for testing.
2026-08-04 20:58:08 +03:00
Dmitry Ng ccb309a628 fix(docker): upgrade Go and dependencies for improved compatibility and performance
- Updated Go version from 1.24 to 1.26.5 in Dockerfile and CI configuration.
- Upgraded various dependencies in go.mod, including AWS SDK and OpenTelemetry packages, to their latest versions for enhanced features and security.
- Refactored Docker client imports from the Docker library to the Moby library for better compatibility with the updated API.
- Adjusted Docker client usage throughout the codebase to align with the new Moby client structure.
2026-08-04 19:09:09 +03:00
Dmitry Ng 049527a39d fix(docker): update alpine base image version in Dockerfile
- Updated the base image from alpine:3.23.3 to alpine:3.23.5 for improved security and stability.
2026-08-04 10:56:37 +03:00
Dmitry Ng 4081292a25 fix(docker): update container error handling and logging
- Replaced client.IsErrNotFound with cerrdefs.IsNotFound for consistent error handling across container operations.
- Updated probe image version to alpine:3.23.5.
- Enhanced logging for container removal failures in flow tools, ensuring better traceability of issues.
- Improved context usage in tests for better cancellation handling.
2026-08-04 10:54:58 +03:00
Dmitry Ng a5274d3c86 Merge pull request #386 from F2had/fix/primary-container-missing-from-daemon
fix(docker): rebuild flow primary container when it is gone from the daemon
2026-08-04 11:34:52 +04:00
Fahad 7d675b313a fix(tools): rebuild the flow primary container when the daemon lost it
A flow stores the id of its primary container in the database. When that
container is removed outside pentagi the row keeps status 'running', so
Prepare reused a container the daemon no longer knows about and every
terminal call failed with "No such container" until the flow was recreated.

Confirm with the daemon before reusing the stored container and let the
existing remove-and-rebuild path take over when it is gone. An unreachable
daemon is still an error, so a transient failure cannot discard a healthy
container.
2026-08-04 09:53:11 +03:00
Fahad 16f1e0c42e fix(docker): report a removed container as not running
ContainerInspect returns a not-found error once a container is gone from
the daemon, and IsContainerRunning wrapped it as an inspection failure, so
callers could not tell a missing container apart from an unreachable
daemon. StopContainer and RemoveContainer already special-case
client.IsErrNotFound; do the same here.
2026-08-04 09:52:06 +03:00
Dmitry Ng ca17c72f96 Merge pull request #384 from vxcontrol/feature/next-release
Merge feature/next-release into main (pre-2.2.0)
2026-08-04 02:22:38 +04:00
Dmitry Ng db68cde21c feat(flows): implement provider renaming and reset functionality
- Added `RenameFlowsProvider` and `ResetFlowsProviderToDefault` methods to the `FlowController` to handle renaming of user-defined providers and resetting to built-in defaults.
- Introduced SQL queries for bulk updating flow and assistant provider names based on user actions, ensuring idempotency and safe retries.
- Enhanced error handling and logging for provider updates, ensuring that flows and assistants remain valid after provider changes.
- Added unit tests to verify the correct behavior of provider renaming and resetting functionalities.
2026-08-04 01:06:58 +03:00
Dmitry Ng 2da929d38d feat(providers): add xAI provider support and configuration details
- Updated the README to include xAI as a supported provider, along with pre-configured provider files for testing.
- Added a new configuration file for xAI with detailed model settings and pricing.
- Created a testing report for xAI, summarizing the performance and success rates of various agents.
- Enhanced the VSCode launch configuration to include xAI provider options for testing.
2026-08-04 00:42:25 +03:00
Dmitry Ng 21338d858f test(cast): add new test for dropping multiple nil function call tool calls
- Introduced a new test case to verify that multiple nil FunctionCall tool calls are correctly removed from the message content, ensuring only relevant text parts are retained.
- Removed the previous test file `newbodypair_reg_test.go` as its functionality is now covered in the updated test suite.
2026-08-03 17:23:23 +03:00
Dmitry Ng b8c1b7d9a6 refactor(tests): update pentester prompt tests for tool-agnostic guidance
- Renamed the test function to reflect a broader focus on CLI argument guidance rather than specific XSStrike flags.
- Enhanced test descriptions and guidance to cover common AI-agent mistakes, ensuring clarity and tool-agnostic advice.
- Updated the template to remove specific tool references, promoting a more generalized approach to command-line argument handling.
2026-08-03 17:17:02 +03:00
Dmitry Ng c19665d822 fix(docs): improve clarity and formatting in installation guides
- Consolidated sentences in the README and installation configuration guide for better readability.
- Removed unnecessary line breaks and ensured consistent formatting for installation instructions and requirements.
- Enhanced links to related documentation for a smoother user experience.
2026-08-03 17:04:12 +03:00
Dmitry Ng c4859cba95 fix(providers): improve error handling when retrieving providers from the database
- Added a specific error check to handle cases where the provider is not found in the database, providing clearer feedback on retrieval failures.
2026-08-03 15:57:00 +03:00
Dmitry Ng 881ba6645f fix(etester): update minimum connections configuration to respect maximum connections limit
- Modified the minimum connections setting in the connection pool configuration to ensure it does not exceed the maximum connections limit, enhancing resource management and preventing potential connection issues.
2026-08-03 15:56:42 +03:00
Dmitry Ng 5fa405782b fix(docs): remove maxLength constraint for password fields in API documentation
- Updated the API documentation in `docs.go`, `swagger.json`, and `swagger.yaml` to remove the maxLength constraint for password fields, simplifying the validation requirements.
- Added `github.com/docker/go-units` as a direct dependency in `go.mod` to support updated functionality.
2026-08-03 14:49:51 +03:00
Dmitry Ng 9b588bd211 Merge pull request #382 from N1neSun/fix/allow-null-flow-trace-id
fix(flows): allow pending trace IDs in flow responses
2026-08-03 15:44:28 +04:00
Dmitry Ng 5610cd96c0 fix(ctester): improve success rate calculation and documentation clarity
- Updated the success rate calculation in `PrintAgentResults`, `PrintSummaryReport`, and `WriteReportToFile` functions to handle cases where total tests are zero, preventing division by zero errors.
- Enhanced comments in `convertToAgentResults` to clarify the impact of unsupported capabilities on overall success rates and average latency.
2026-08-03 14:41:18 +03:00
Sergey Kozyrenko 0068b53bb9 fix(flows): stop wide tables from horizontally scrolling the message list
A markdown table with a long unbreakable cell (e.g. a FLAG hash) overflowed
the message bubble and dragged the entire message list into a horizontal
scroll, cutting off the left edge of every line. Wrap tables in an
overflow-x-auto container so wide content scrolls inside its own box while the
list scrolls only vertically. Covers both automation and assistant, which
render through the same Markdown component.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
(cherry picked from commit 8745c51388948de1eeef405f9c1298693f5e53f4)
2026-08-02 02:53:31 +07:00
Dmitry Ng f6fe867a99 feat(worker_node): enhance monitoring setup and documentation for worker node
- Updated `METRICS_IP` documentation to reflect new metrics ports (8080, 9100) for cAdvisor and node-exporter.
- Added detailed instructions for deploying cAdvisor and node-exporter on the worker node's host Docker, including scripts for setup.
- Enhanced the security and firewall configuration section to include new metrics endpoints.
- Improved overall documentation clarity for metrics integration with PentAGI's observability stack.
2026-08-01 20:16:15 +03:00
Dmitry Ng 339aa958f0 feat(neo4j): enhance configuration and directory structure for Neo4j integration
- Added new environment variables to `.env.example` for Neo4j memory and transaction settings, including `NEO4J_HEAP_INITIAL_SIZE`, `NEO4J_HEAP_MAX_SIZE`, `NEO4J_PAGECACHE_SIZE`, and `NEO4J_TRANSACTION_MAX`.
- Updated `docker-compose-graphiti.yml` to mount Neo4j configuration and plugin directories, ensuring proper integration with the Graphiti stack.
- Introduced static configuration files for Neo4j and APOC in the `examples/neo4j/conf` directory, providing a clear structure for user-editable settings.
- Enhanced the README to document the new configuration options and directory structure for Neo4j, improving user guidance for setup and customization.
2026-08-01 20:03:02 +03:00
Dmitry Ng 1778290d15 feat(graphiti): update model versions in configuration files
- Updated the model references in `gemini.yaml` from `gemini/gemini-2.5-flash-lite` to `gemini-3.5-flash-lite` and `gemini/gemini-2.5-flash-lite` to `gemini-3.1-flash-lite` for improved performance.
- Changed the model references in `openai.yaml` from `openai/gpt-5-mini` to `gpt-5.6-luna` and `openai/gpt-5.4-nano` to `gpt-5-nano`, reflecting the latest versions for better capabilities.
2026-08-01 19:54:27 +03:00
Dmitry Ng cfa325228e feat(gemini): update model configurations and test report
- Increased temperature settings for `simple` and `simple_json` models from 0.7 to 1.0 for enhanced variability.
- Changed model references from `gemini-3.5-flash` to `gemini-3.5-flash-lite` for `reflector`, `searcher`, and `enricher`, optimizing for cost and performance.
- Updated `coder`, `installer`, and `pentester` models to `gemini-3.6-flash`, reflecting the latest version with improved pricing and capabilities.
- Revised test report to reflect new model configurations, including updated success rates and average latencies, ensuring accurate performance metrics.
- Enhanced documentation to clarify model descriptions and pricing adjustments for better user understanding.
2026-08-01 19:53:43 +03:00
Dmitry Ng 341a9def05 feat(worker_node): add browser scraper deployment instructions for worker node
- Introduced a new section in the worker node guide detailing the deployment of a browser scraper on the worker node's host Docker, including setup instructions and security considerations.
- Added a script for launching the scraper with appropriate configurations, including environment variables for credentials and resource limits.
- Updated firewall requirements to include access for the scraper service, ensuring clarity on network configurations.
- Enhanced documentation to guide users on verifying the scraper's readiness and integrating it with the main PentAGI node.
2026-08-01 19:44:55 +03:00
Dmitry Ng c383086afe refactor(worker_node): improve worker node guide and policy test script
- Revised the worker node guide to clarify the use of TCP over TLS for worker connections, addressing potential failure modes associated with socket mounts.
- Updated environment variable configurations to include `METRICS_IP`, ensuring proper binding for Docker metrics.
- Enhanced the `policy-tests.sh` script to improve transport resolution for the DinD API, allowing for better handling of both TCP and Unix socket connections.
- Improved documentation for the metrics endpoint and security model, ensuring clearer instructions for users.
2026-07-30 20:46:01 +03:00
Dmitry Ng 21baa20a0b refactor(logging): standardize error logging across controllers and providers
- Replaced direct error logging calls with a centralized `obs.LogErrorOrCancel` function to ensure consistent logging behavior for errors, particularly in cases of context cancellation.
- Updated various controllers and providers to utilize the new logging method, enhancing maintainability and clarity in error handling.
- Introduced new methods for invalidating subtasks and tasks in the flow and subtask controllers to improve resource management and prevent stale references.
- Enhanced the handling of database errors in task and subtask status updates to treat missing records as completed, ensuring idempotent task shutdowns.
2026-07-30 16:33:52 +03:00
Dmitry Ng ebb228b19a feat(graphiti): enhance configuration and integration settings
- Added new environment variables to `.env.example` and `docker-compose-graphiti.yml` for Graphiti, including `GRAPHITI_CPUS`, `GRAPHITI_MEMORY`, and various ingestion and logging settings.
- Updated the README to clarify the optional nature of the Graphiti integration and its configuration requirements.
- Enhanced the backend installer to support new Graphiti configuration options, ensuring proper handling of the Graphiti stack.
- Improved the user interface for Graphiti settings in the installer wizard, allowing for better configuration management.
- Revised documentation to reflect changes in Graphiti's deployment modes and integration capabilities.
2026-07-30 16:26:16 +03:00
N1neSun 3068b626d0 fix(flows): allow pending trace IDs 2026-07-30 16:36:36 +08:00
Dmitry Ng ca482686d7 feat(database): enhance PostgreSQL schema handling for multi-tenant support
- Added new environment variables `DATABASE_EXTENSIONS_SCHEMA` and `DATABASE_SEARCH_PATH_VIA_OPTIONS` to `.env.example` and `docker-compose.yml` for better management of PostgreSQL schemas in multi-tenant deployments.
- Updated the README and configuration documentation to explain the purpose and usage of the new variables, particularly for setups using Supabase.
- Implemented schema verification and initialization logic in the backend to ensure proper handling of tenant-specific schemas during database connections.
- Enhanced the installer and server settings forms to include the new configuration options, improving user experience and clarity.
2026-07-30 00:14:30 +03:00
Dmitry Ng 0da3892b0d fix(docker): clarify container capability management in Docker setup
- Updated the documentation in `docker.md` to provide a detailed explanation of the explicit capability allow-list used for primary containers, emphasizing the rationale behind the selected capabilities and the deliberate omission of `MKNOD`.
- Revised comments in `client.go` and `tools.go` to reflect the decision against using `no-new-privileges`, clarifying its impact on privilege escalation testing and container security.
- Enhanced the overall clarity and completeness of the capability management section to aid understanding of security measures in the Docker-in-Docker setup.
2026-07-29 22:33:14 +03:00
Dmitry Ng dfb762f420 fix(config): update model versions in Anthropic configuration and test report
- Changed the model version from `claude-opus-5` to `claude-opus-4-8` in the configuration file for both generator and refiner.
- Updated the test report to reflect the new model version, including adjustments to success rates and average latencies for the generator and refiner agents.
- Revised overall average latency in the test report to account for the updated model performance.
2026-07-29 22:05:27 +03:00
Dmitry Ng 7a81132730 fix(tests): update state initialization in compose_test.go
- Refactored state initialization in tests to use NewState instead of New for clarity and consistency.
- Ensured that the changes maintain the functionality of the tests while improving code readability.
2026-07-29 16:05:31 +03:00
Dmitry Ng 464dca8903 feat(worker_node): enhance Docker-in-Docker setup with security and cleanup features
- Updated the worker node guide to include a hardened Docker-in-Docker (dind) configuration, emphasizing security measures such as OPA authorization and seccomp profiles.
- Introduced new scripts for managing dind containers, including `dind-cleanup.sh` for removing stale containers and `run-dind.sh` for starting the dind container with authorization.
- Added configuration files for the dind setup, including `authz.rego`, `seccomp.json`, and `daemon.json`, to enforce strict security policies.
- Implemented a systemd timer and service for regular cleanup of nested containers, ensuring efficient resource management.
- Expanded documentation to clarify the purpose and usage of new scripts and configuration files, enhancing user understanding of the setup process.
2026-07-29 16:01:42 +03:00
Dmitry Ng 131694b8aa feat(docker): enhance worker container Docker access configuration
- Added new environment variables `DOCKER_INSIDE_HOST`, `DOCKER_INSIDE_TLS_VERIFY`, and `DOCKER_INSIDE_CERT_PATH` to facilitate secure Docker access for worker containers.
- Updated `.env.example` and `docker-compose.yml` to reflect these new configurations.
- Enhanced backend logic to support the new Docker settings, ensuring proper isolation and security for worker containers.
- Expanded documentation to clarify the usage and implications of the new Docker access configurations.
2026-07-29 16:01:30 +03:00
Dmitry Ng 34a9cd2ee8 feat(config): enhance multi-instance support and Docker configurations
- Introduced `TENANT_ID` to namespace resources for multi-instance deployments, preventing collisions in shared services.
- Added new environment variables in `.env.example` and `docker-compose.yml` for Docker daemon configurations (`DOCKER_INSIDE_HOST`, `DOCKER_INSIDE_TLS_VERIFY`, `DOCKER_INSIDE_CERT_PATH`).
- Updated backend logic to handle tenant-specific configurations, ensuring proper isolation of resources across instances.
- Enhanced documentation to clarify the usage and implications of `TENANT_ID` and related Docker settings.
2026-07-29 16:01:24 +03:00
Dmitry Ng aaa1726691 Merge pull request #355 from manus-pi/fix/sandbox-no-new-privileges
fix(sandbox): harden sandbox containers against privilege escalation
2026-07-29 16:40:52 +04:00
Dmitry Ng 8da9394d68 Merge pull request #379 from Priyanka-2725/fix/installer-restart-graphiti-disabled
Fix: Handle missing Graphiti compose file gracefully during restart
2026-07-29 16:36:33 +04:00
Dmitry NgandSergey Kozyrenko 45c84c500f test(frontend): make the e2e suite falsifiable, and fix what it found (#380)
The e2e suite and CI gates could report green without checking anything: the
lint/codegen gate never ran on fork PRs, the codegen freshness check diffed the
wrong range, the sticky comment claimed passes it never read, and several
visual/palette/contrast/a11y gates were written so they could not fail. Closing
those gates then exposed real defects.

**E2E and CI.** New coverage for the assistant lifecycle, flow interrupt, live
panels, tab deep links, the report route and its exports, session expiry, and
uploads/downloads (59 → 125 spec cases). Gates now fail on real regressions:
absolute pixel budget, per-tab panel sweeps, scoped a11y waivers, page-error
assertions. CI runs on `pull_request`, ranges from the PR base, routes comments
by PR identity, and redacts stand secrets from the public artifact.

**Markdown editor.** ~20 round-trip and toolbar fixes: table pipe escaping
(nested lists, Go template pipelines, headerless tables), fence validity,
setext and line-leading escapes, inline code containing a backtick, block
toggles under select-all, controls disabled where the command is unavailable or
a table cell cannot hold the block, theme-aware code surface. Two perf fixes cut
1 MB document load from 69s to 4s.

**Accessibility and UI.** Focus returns to whatever opened a dialog, sheet or
menu; icon-only buttons named; `aria-sort` on table columns; syntax tokens
retuned to clear AA in both themes; a dedicated link token. Detail and settings
pages now distinguish authz denials and partial errors from missing records,
survive background refetches without blanking or discarding unsaved edits, and
stop naming exported PDFs `*.pdf.pdf`.

**Backend.** Passwords capped at the 72 bytes bcrypt can hash (over-long ones
previously 500'd after passing validation); four agent options the GraphQL round
trip silently dropped are carried through; a flow whose worker fails to start is
no longer left in the listing; the Graphiti health check retries before
permanently disabling the client.

---------

Co-authored-by: Sergey Kozyrenko <sirozha_blr@tut.by>
2026-07-29 16:34:29 +04:00
Dmitry Ng 762c6233ce feat(flow): enhance error handling and documentation for flow retrieval
- Added specific error handling for `ErrFlowNotFound` in `PatchAssistant` and `DeleteAssistant` methods, returning a warning-level response when the flow is not found.
- Updated documentation in templates to clarify requirements for `center_node_uuid` in search types, ensuring users understand the necessity of copying UUIDs from prior results.
- Improved JSON schema descriptions for `GraphitiSearchAction` to emphasize the mandatory nature of the `query` field across all search types.
- Introduced new tests to validate handling of empty timeout values and ensure proper parsing of temporal window timestamps, addressing potential production issues.
2026-07-26 14:40:01 +03:00
Dmitry Ng c257dabc57 feat(config): update hcnsec provider configuration and test report
- Replaced all instances of `Qwen3-Coder-Next-FP8` with `MiniMax-M2.7` in the hcnsec provider configuration, adjusting model settings and pricing accordingly.
- Updated the test report to reflect the new model configurations, including success rates and average latencies for various agents using `MiniMax-M2.7`.
- Enhanced the overall structure of the configuration file for clarity and consistency.
2026-07-25 15:02:49 +03:00
Dmitry Ng 2d87a1f8fe feat(retries): implement callWithSetupRetries for transient error handling
- Introduced `callWithSetupRetries` function to enhance error resilience during LLM prompt calls, allowing for retries on transient errors with backoff.
- Updated `NewFlowProvider` and `NewAssistantProvider` methods to utilize `callWithSetupRetries` instead of direct calls to `prv.Call`, improving stability in flow and assistant creation.
- Added comprehensive unit tests for `callWithSetupRetries`, covering immediate success, transient error handling, and context cancellation scenarios.
- Enhanced error messages in Graphiti search tools to provide actionable feedback for missing or malformed parameters.
- Updated templates to clarify search type requirements and taxonomy references.
2026-07-25 13:30:12 +03:00
Dmitry Ng d9b28ce8bf chore(dependencies): update langchaingo version and adjust model configurations
- Updated the `langchaingo` dependency in `go.mod` from version `v0.1.15-0.20260723091023-35da5c0f0620` to `v0.1.14-update.6`.
- Modified the model configurations in `config.yml` and `models.yml` to replace `claude-opus-4-8` with `claude-opus-5` for both the generator and refiner sections.
- Updated the model descriptions and pricing in `models.yml` to reflect the new `claude-opus-5` model and added new models `claude-sonnet-4-6` and `claude-haiku-4-5`.
- Adjusted the test report in `anthropic-report.md` to reflect the updated model names and improved average latencies across various tests.
2026-07-25 02:52:04 +03:00
Priyanka Singh 6d1c055b75 Fix: Handle missing Graphiti compose file gracefully during restart 2026-07-25 04:25:49 +05:30
Dmitry Ng 5a4f1f54dc feat(search): introduce internal analytics engine for web search
- Added configuration options for an optional internal analytics engine in `.env.example`, `docker-compose.yml`, and related files.
- Updated documentation to include details about the new internal analytics engine, which scrapes and summarizes pages as a fallback for the web_search tool.
- Enhanced the `ftester` to support testing the new internal engine alongside existing search engines.
- Adjusted various components to integrate the new engine, including configuration forms and validation logic.

This feature allows users to enable a browser-based fallback for analytic queries, enhancing the flexibility of the web search capabilities.
2026-07-25 01:16:18 +03:00
Dmitry Ng 38c1e261a2 chore(config): update environment and Docker configurations
- Removed default FIRECRAWL_API_URL from `.env.example` and `docker-compose.yml`.
- Added new provider configuration files to the Dockerfile, including hcnsec, novita, and vllm-mixed.
- Deleted the obsolete glm_flash_bedrock.yml configuration file.
2026-07-23 18:44:03 +03:00
Dmitry Ng deaff9eafe chore(config): update launch.json and add new provider configurations
- Added new configuration options in `.vscode/launch.json` for vllm and hcnsec providers.
- Updated `deepinfra.provider.yml` to reflect changes in model configurations and pricing.
- Introduced `hcnsec.provider.yml` with detailed model settings and pricing for HCNSec.
- Adjusted various test reports to reflect updated success rates and latencies for different models.
2026-07-23 17:37:44 +03:00
Dmitry Ng c26cb0b41e feat(tools): add edit_file action with unified-diff support
- Added `edit_file` to the file tool; diffs are parsed and applied in-memory via `github.com/sergi/go-diff`, exported as `tools.ApplyUnifiedDiff`.
- Made the hunk header lenient (position numbers optional) for models that omit them, with fuzzy content-based matching as fallback.
- Tuned `FileAction` field descriptions (layered, minimal-token) to steer models toward including context lines, based on live model testing via `ctester`.
- Added a `file_edit` multi-turn read_file → edit_file test case in `pkg/providers/tester`, using PentAGI's real tool schema, wired into the `advanced` test group.
- Fixed a bug where a single stateful test-case instance was shared across agent types, leaking conversation history and failures between independent runs.
- Extended the mock provider with sequential responses for multi-turn scenarios; added ctester integration tests.
2026-07-23 17:19:22 +03:00
Dmitry Ng 796c7faf3d fix(agent): stop network and malformed-arg failures from hard-failing tools
Graphiti transport errors, an empty file path, and an omitted 'action' or
double-encoded 'questions' arg from the LLM all hard-failed the tool chain
and burned retries instead of degrading gracefully. Also: stopTaskTimeout
5s->60s (flow kept running after a false 500), and the routine "cookie
claim invalid" case now logs at Warn instead of Error.
2026-07-22 16:25:07 +03:00
Dmitry Ng 7a0f3cfc29 Merge branch 'feature/frontend' into feature/next-release 2026-07-22 14:48:39 +03:00
Sergey KozyrenkoandClaude Opus 4.8 f95c48b062 refactor(knowledges): give knowledgeId back to the route param
`knowledgeId` means the route param everywhere else — the route is declared as
`knowledges/:knowledgeId`, and both knowledge.tsx and the route-title resolver
destructure it under that name. This header had taken the name for the loaded
document's id and left the route param as `routeKnowledgeId`, so the one file
that reads both used the project's vocabulary backwards.

The document's id needed no binding of its own: `handleRenameSave` two functions
above already guards on `knowledge` and passes `knowledge.id`, so `handleDelete`
now does the same and the rename input keys off `knowledge?.id`.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 18:23:00 +07:00
Sergey KozyrenkoandClaude Opus 4.8 e51f686e5c refactor: drop the header-order comment and the rest of the narration
The comment on AppHeaderActions claimed the component pins itself to the right.
It does not — the sibling content block takes `flex-1` and pushes it there — and
the rule it stated was an instruction to call sites, not a fact about the twelve
characters below it. The convention now lives in docs/list_detail_pages.md, next
to the detail-page recipe that needs it.

Two more went the same way, by making the code carry the point instead: the
knowledge header's two ids are now `documentId` and `routeKnowledgeId`, so
there is nothing to warn about, and the separator that doubles up is gated on a
named `hasViewRow`. In the pager spec the injected delay is held by an assertion
that counts the samples taken before the sibling appears — removing the delay
now fails the test instead of quietly emptying it.

Across the e2e specs, six comments that only explained why a test exists are
gone and five more are down to one line.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 18:16:04 +07:00
Sergey KozyrenkoandClaude Opus 4.8 f24b75f350 refactor: cut the comments that only explain the author
Seven blocks went: three justified a test's existence or the way an assertion
was written, one repeated the fact stated two hunks above it, one restated a
guard that a unit test now enforces, and two paraphrased the identifier sitting
next to them. The five that stay each name a consequence that is invisible from
the line: a delay whose removal makes the surrounding assertion vacuous, the
leftward-growth contract of a shared header primitive, a route id that must not
be taken from the entity beside it, a separator that doubles for callers without
a mode toggle, and a flag read by a subscription gate forty lines away.

The counter's width reservation gets a unit test over three set sizes instead of
prose, so its scaling is pinned by the suite rather than asserted in a comment.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 17:55:35 +07:00
Sergey KozyrenkoandClaude Opus 4.8 46457026e8 fix(ui): repair what the always-rendered header exposed on the other two pages
Three defects the review found, all in surfaces the flow page does not share.

The knowledge pager took its current id from the loaded document, so now that
the cluster no longer unmounts it sat there reading "–/N" with both arrows
dead for the whole document fetch — and again after every step. It takes the
route's id, like the flow and template pages already did.

The knowledge actions menu drew a doubled divider while loading: the View row
between the two groups only exists when a mode toggle is passed, which the
loading shell does not do.

The isLoading prop threaded down to that header could not change any output —
the only caller that passed it also passed a null document, so the flag it fed
was already true. Removed rather than left as a signal that looks live.

Also: the template not-found card reuses the page header, which since the
redesign offered a Save aimed at a form that is not on that screen and a pager
for an id absent from the list. The actions are gone from that branch; the
loading branch keeps them, which is the point of the convention.

The two flow baselines are regenerated: they were captured mid-series, before
the counter's width reservation moved off the button, and the visual gate could
not see the drift — the diff sits seven times under its ratio. The template
header's order now has a spec assertion; that route has no baseline at all.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 17:43:35 +07:00
Sergey KozyrenkoandClaude Opus 4.8 15319ef817 fix(ui): reserve the counter width on the label, not on the button
The reservation was computed as digits-of-total × 2 + 1 and applied to the
button, which is border-box: 18px of padding and border ate it, so the
counter still grew from 65 to 83px across a digit boundary and Previous
still slid 18px out from under the cursor — measured, both before and after.

It now reserves the width of the widest label the set can produce, on the
label itself, and the button holds 83px through every position. Building
that label instead of deriving its length also drops the arithmetic that
made the intent unreadable.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 16:21:38 +07:00
Sergey KozyrenkoandClaude Opus 4.8 ee6ed49d48 fix(ui): keep the header actions in fixed slots instead of a pager prop
Reverts the `pager` slot on AppHeaderActions. The block is right-pinned, so
ordering alone gives the guarantee the slot was reaching for: put the controls
that come and go at the start of the children and everything after them keeps
its position. Flow header, right to left: actions menu, pager, favourite,
report — the report being the one that waits on the task list.

The controls that are always meaningful for a route are now always rendered
and disabled from an explicit loading flag rather than unmounted when the
entity object is falsy. Stepping used to collapse the whole cluster to a lone
star for the length of the fetch, and the pager — which needs the sibling list,
not the current entity — went with it, so a second step meant waiting.
Templates and knowledge get the same treatment; knowledge had no loading
signal at all, so one is threaded down from the page.

Two side effects of dropping the entity gates: on phones the flows row and the
favourite toggle survive an unloaded list (they were nested behind it), and the
position counter reserves the widest label its total can produce, so stepping
across a digit boundary no longer slides Previous out from under the cursor.

The pixel baselines cannot pin any of this — the cluster is far below the
visual project's diff ratio — so the order is asserted in the spec instead.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 16:05:36 +07:00
Sergey KozyrenkoandClaude Opus 4.8 5b4ded1e3c fix(flows): stop the pager bouncing the user back to the flows list
Stepping to a sibling flow landed on /flows. The detail page inferred "this
flow does not exist" from three absences — not loading, no flow, no error —
and an Apollo variables change satisfies all three: it reports networkStatus
setVariables, not loading, while the new flow's data is still undefined.
Instrumenting history showed both hops: replaceState to /flows/2861, then
straight back out to /flows.

The provider now publishes a positive isFlowMissing (the query settled with
no flow, or failed as a not-found) and the redirect reads only that, so
retuning the loading flag cannot silently break navigation again — which is
how this shipped. isLoading itself becomes "in flight with nothing to show",
which also keeps the Retry button on a failed load from ejecting the user.

Nothing in the suite pressed Prev or Next, so the new spec does: it samples
the DOM through a delayed fetch, proving the URL never passes through the
list and the pager stays mounted while the sibling loads.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 16:05:22 +07:00
Sergey KozyrenkoandClaude Opus 4.8 3d04fcfff2 test(e2e): fail on a colour written outside the variant set
The contrast gate mounts probes from cva output, so a colour written as a
raw utility in a page — the shape of the badge defect that shipped — was
outside it by construction. This walks the rendered DOM of every swept
route instead: each badge and button must draw its colour from the variant
set or from a semantic token.

It immediately found one, a hard-coded blue hover on the file manager's
expand-all control, waived by its exact node string until the design pass
takes it (the colour change moves baselined pixels).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 14:06:20 +07:00
Sergey KozyrenkoandClaude Opus 4.8 dfff92bef6 docs: correct two claims in the list/detail guide
The intro left /settings/prompts out of the list pages built on these
pieces and implied every one of them has a detail page; api-tokens edits
in place. The removed/renamed table pointed at stale mentions of the
deleted writer hook in two files that no longer contain any.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 14:06:09 +07:00
Sergey KozyrenkoandClaude Opus 4.8 ecb94b25e7 test(e2e): assert stand routes on data, not only on client-side state
Every assertion was client-side — the URL, a route-derived breadcrumb and
pageerror, which a production React build does not emit for a failed
query — so all five passed against a backend erroring on every request.
Verified against the live stand: healthy, 5/5 pass; with GraphQL forced to
error, the URL and breadcrumb assertions still pass and only the new one
fails. Each route now proves its query resolved, accepting the empty state
as well since a stand may hold no rows.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 14:06:09 +07:00
Sergey KozyrenkoandClaude Opus 4.8 04cc821bd6 test(e2e): stop the flows entries owning pages no route renders
Both flow entries claimed the whole src/pages/flows dir, which also holds
the report and create pages. A diff touching only the report page scoped
the run to two routes that cannot render it — the same ownership class
already fixed elsewhere in the manifest. Each entry now names its own
page file, so those two pages fall through to the conservative full run
and the detail/list diffs scope more precisely than before.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 14:06:09 +07:00
Sergey KozyrenkoandClaude Opus 4.8 d58f840702 test(e2e): probe every editor colour token, keyed off the stylesheet
Two of the five --editor-* tokens were probed and nothing made the list
rot-proof, unlike the badge matrix. The remaining three hang off element
selectors rather than classes, so the probe mount now takes a tag per
probe; the accent and code pairs clear AA in both themes. A new assertion
reads the token declarations out of the stylesheet, so a newly declared
token has to be probed or exempted.

The mount guard moved from "composites to transparent" to "still wears the
surface's colour", which every token rule overrides — the transparent form
could not cover an element-selector probe with no chip.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 14:05:55 +07:00
Sergey KozyrenkoandClaude Opus 4.8 908d35f8e4 test(e2e): make every dashboard period query serve its own dataset
Three of the four by-period queries returned one dataset regardless of the
period, so the period switch could only be asserted on the token chart —
the other three cards would have rendered identically had the app never
rewired them. Each now has week and month variants keyed on the period
variable, and the spec asserts the swap across all four cards plus the
execution breakdown, which carries no dates and so differs by flow.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 14:05:55 +07:00
Sergey KozyrenkoandClaude Opus 4.8 054f46b0ed test(e2e): gate the reconnect delta and give the dedup assertion a source
The post-reconnect flow(5) response was ungated, so any spec that fetched
flow 5 twice consumed it and rendered a message that never streamed. It now
serves only after a drop, behind a flag `dropAndReconnect` raises.

The no-duplicate assertion beside it had nothing that could produce a
duplicate: every id reached the page exactly once by construction. The
resubscribe now replays the id the refetch already delivered — the real
server behaviour the client dedups — followed by a sentinel that proves
the replay arrived rather than merely being awaited.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 14:05:42 +07:00
Sergey KozyrenkoandClaude Opus 4.8 f6bcff8672 test(e2e): scan the flow tab panels and the populated provider cards
The a11y sweep only ever saw each route's default view. Radix unmounts
inactive tab panels, so seven of the flow-detail tabs were never scanned,
and /settings/providers was scanned exclusively in its empty state — the
provider cards, where the badge-contrast defect lived, went unlooked at.

The manifest entry also claimed to own the file-manager, dashboard and
resources dirs while seeding empty collections, so the swept form of the
route rendered none of them. It now runs on the populated cassette, which
required the six per-flow stats queries the Dashboard tab issues.

Scanning the panels surfaced five real defects (unnamed progressbar,
unnamed icon buttons, under-size targets, screenshot-title contrast,
unfocusable scroll regions); each is waived by rule and node so the rest
of the panel still fails on anything new.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 13:41:35 +07:00
Sergey KozyrenkoandClaude Opus 4.8 ce1fc7049d test(e2e): cover the two detail routes whose editor loads server content
/settings/prompts/:promptId and /templates/:templateId had no test on any tier,
and they are where MarkdownEditorField loads content from the server — the
prompts list spec only expands a row into a <pre>, and the templates spec only
exercises create mode. The editor's one shipped crash reproduced solely in a
production build, which is exactly what the mock tier runs.

Each route now loads a non-trivial body (headings, list, fenced command, table,
and the {{.Var}} / {{PLACEHOLDER}} atoms the backend parses) and asserts both
halves: the raw view matches the loaded source byte-exact, and after an edit in
the rich editor every atom survives its serialization.

Also close the hole that let them stay uncovered: route builders are functions,
so the manifest's static path walk never saw them. Every builder must now
declare where it is covered or why it is not, and the check fails when a new one
appears undeclared.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 13:18:20 +07:00
Sergey KozyrenkoandClaude Opus 4.8 f3311ecadf ci: scope the codegen-freshness check to its inputs and name the fix
The check ran on every push and failed with a bare diff, so a backend schema
change surfaced as an unexplained red frontend job.

Run it only when a codegen input moved — the backend schema, the operations
document, the codegen config, or the lockfile (a codegen bump can change the
output, and skipping it there would let types.ts go stale and fail someone
else's later push). When the compare range can't be resolved (new branch,
force-push, tag) it still runs. On failure it now says which command to run.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 12:59:14 +07:00
Sergey KozyrenkoandClaude Opus 4.8 fdf5c4ea90 test(e2e): close three latent assertion gaps
- Watch for uncaught errors on the two auth-path smoke tests (they destructured
  no error log before); the rejected-login path asserts no uncaught JS exception
  while tolerating the 401's expected browser console line.
- Assert the thinking body is collapsed before the toggle, so an always-expanded
  regression fails.
- Assert the dashboard overview metrics are absent until the tab is selected, so
  the "loads lazily" title is actually covered.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 06:10:18 +07:00
Sergey KozyrenkoandClaude Opus 4.8 678a878855 test(e2e): assert the responsive and a11y-login claims their titles make
- The mobile test now asserts a mobile-shell-owned fact (sidebar nav collapsed to
  the off-canvas sheet) and the split-boundary test asserts the tab rows go 2→1,
  so both cover the width-sensitive half their titles promise.
- The a11y login scan gets the same theme-class guard as the manifest scan, so a
  dead dark seed can't re-scan the light page under a dark label.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 06:05:33 +07:00
Sergey KozyrenkoandClaude Opus 4.8 2615510a0d style(e2e): apply prettier to the matcher and auth-setup edits
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 06:00:24 +07:00
Sergey KozyrenkoandClaude Opus 4.8 abef4e29b8 test(e2e): fail the contrast probe on an unparseable colour
paint() set fillStyle to black, then to the requested colour — but an
unparseable colour is a silent no-op on fillStyle, leaving black, which measures
as a spurious ~21:1 pass. Assign the colour against two different sentinels and
throw when it doesn't land on the same value, so a broken colour surfaces the
gate instead of clearing it.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 05:58:24 +07:00
Sergey KozyrenkoandClaude Opus 4.8 cb0ec25319 docs(e2e): correct the stand-tier fork guard and document its env vars
The stand tier's fork/secret protection is the protected Environment's reviewer
gate, not the job's label condition — a fork PR can carry the label but blocks
on a human before any secret. Say so, note the tier now lives in its own
workflow, and document the E2E_STAND_* secrets and their E2E_* tool names.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 05:55:51 +07:00
Sergey KozyrenkoandClaude Opus 4.8 06f53c72a0 test(e2e): settle editor typing, resources input and the stand login detector
- Route both the knowledge and template editor inputs through a shared
  typeIntoEditor helper (pressSequentially), instead of fill() on one and a
  documented ProseMirror-race workaround on the other.
- Make the mkdir spec type a name distinct from the dialog default and pin it, so
  a broken input→payload binding no longer matches the default.
- Derive the stand login-readiness locator from E2E_USER instead of a hardcoded
  admin@ (and a "flows" button that does not exist).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 05:54:14 +07:00
Sergey KozyrenkoandClaude Opus 4.8 5803d5adc6 test(e2e): tighten the graphql-ws mock's id reuse, completion test and comment
- Release a subscription id's prior handler before overwriting it, so a reused
  live id can't leak both subscribers onto one id.
- Assert a stream without `complete` delivers frames but stays open, so flipping
  the completion default would fail the protocol suite instead of passing.
- Correct the connection_init comment: a pre-ack frame closes the socket as a
  protocol violation, it does not cause a reconnect storm.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 05:49:12 +07:00
Sergey KozyrenkoandClaude Opus 4.8 b16d4a8b4a test(e2e): harden the e2e tooling and CI freshness checks
- Reject a non-object JSON body in the mock-LLM (JSON.parse('null') parsed but
  reading .tools then threw and killed the process).
- Pin serve-dist's PORT from the config so an ambient PORT can't move it off the
  port Playwright waits on.
- Fail lint on any warning, so a Playwright test with no assertion (expect-expect
  is a warning) can no longer lint clean.
- Add a CI check that regenerates src/graphql/types.ts and diffs it, so the
  compiled operations can't drift from the codegen input the stand validates.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 05:47:15 +07:00
Sergey KozyrenkoandClaude Opus 4.8 3400e1e7c1 ci(e2e): tighten the visual gate, CI signal integrity, and container guards
- Drop the screenshot threshold to 0.02 (baselines and CI both render in the
  pinned container, so there is no host rasterisation noise to absorb) so a
  palette change now fails the visual gate; verified 20/20 still match.
- Gate the visual guard on a container marker set by run-visual.sh and the CI
  job, not the host OS, so an --update on a Linux workstation cannot overwrite
  baselines with host-font pixels.
- retries:0 on the hermetic mock tier so a retry-recovered race fails instead of
  merging green; wire @quarantine via grepInvert as the escape hatch.
- Scope globalTimeout to the mock tier so a real-tier run is not aborted mid-retry.
- Verify the visual container against @playwright/test's actual version instead
  of a hardcoded literal.
- Key the report's "snapshots differ" advisory on the diffs artifact (uploaded
  only on a real snapshot-step failure), not the visual job conclusion; and stop
  a transient jobs-API error from silently leaving a stale sticky comment.
- Drop the unconsumed blob report that doubled every uploaded trace.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 05:43:50 +07:00
Dmitry Ng 5b48fd9f8e Merge branch 'feature/frontend' into feature/next-release 2026-07-22 01:38:05 +03:00
Sergey KozyrenkoandClaude Opus 4.8 e4b8001499 test(e2e): harden the mock matcher's cursor, keys and stream completion
- Track sequenced-response consumption by entry identity, not a cursor into the
  current eligible subset: a second raised flag grew the subset, reset the cursor
  to 0, and replayed the previous flag's entry once before advancing.
- Restrict isPlainObject to true plain objects, so a non-plain pin (a Date) can no
  longer recurse into empty own-keys and match any object-shaped value.
- Key subscription streams on the request's variables and REST sequences on the
  request body, so entries without variables no longer merge onto one cursor.
- Complete a late subscriber that joins after a complete:true stream has drained.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 05:33:07 +07:00
Dmitry Ng 74c2663114 Merge branch 'integrate/open-prs-v2' into feature/next-release 2026-07-22 01:25:25 +03:00
Sergey KozyrenkoandClaude Opus 4.8 b0e69b2c7c test(e2e): seed a realistic session so gated branches enter the sweeps
The seeded /info returned privileges:[] with no OAuth providers — a state the
backend never returns. Every privilege-gated control (e.g. the knowledge
Anonymize action) and the login page's OAuth buttons rendered in their denied
variant in every spec and tier, so a regression there shipped unseen.

Seed the admin privilege list and the OAuth providers (authenticated and guest),
assert the login page now renders its OAuth buttons, and refresh the /flows/5
baseline, which now shows the flow controls in their real admin state.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 05:25:23 +07:00
Sergey KozyrenkoandClaude Opus 4.8 101331c920 test(e2e): fix three cassette-fidelity gaps
- The knowledge list query is withContent:false, where the backend returns an
  empty content string; the entry served "Content for …".
- The generator and refiner prompt pairs were inverted vs the backend
  (System/Human swapped), teaching the wrong contract on two of fifteen agents.
- The GraphQL mock dropped an entry's data when it also carried errors, so a
  partial-error response could not be mocked with its data half.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 05:19:20 +07:00
Sergey KozyrenkoandClaude Opus 4.8 be585b64f4 test(e2e): make the rejected-login cassette answer 401 like the backend
The entry answered HTTP 200 with `{error, status}`, but the backend returns 401
with `{status, code, msg}` (develop mode adds the `error` key). The two take
different app branches: the 200 shape resolves and shows "Invalid login or
password"; the real 401 is caught by the axios interceptor, which clears the
auth key and rejects, so the form shows "Login failed. Please try again." — the
branch a real wrong password takes, which no spec exercised.

Serve 401 with the real envelope, pin the submitted credentials with bodySubset,
and assert the message the 401 path actually produces.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 05:15:05 +07:00
Sergey KozyrenkoandClaude Opus 4.8 b565bf41c3 ci(e2e): stop a PR label from superseding a red required check
The gate subscribed to `labeled` so applying `e2e:stand` could start the stand
job, but every gate job carried `if: github.event.action != 'labeled'`. A label
event then ran with e2e-mock skipped, and GitHub counts a skipped required check
as satisfied on the same head SHA — so adding any label to a PR whose e2e-mock
was red published a merge-permitting check over the red one.

Move the stand tier into its own workflow (e2e-stand.yml) that owns the
`labeled` trigger; e2e.yml now fires only on real code events (opened /
synchronize / reopened) and its gate jobs never skip. The stand workflow keeps
the protected environment + reviewer gate, and uploads results.json only.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 05:10:50 +07:00
Sergey KozyrenkoandClaude Opus 4.8 7b6c85c34f style(editor): trim narration from the code-block CSS comments
Keep only the two invisible contracts — pre defers its colours to .hljs, and
data-language is DOM-only and never serialized — and drop the prose that
restated the CSS.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 04:21:12 +07:00
Sergey KozyrenkoandClaude Opus 4.8 c635a9fe34 test(converter): cover per-agent extra_body round-trip
Guards the two-way mapping added with the extra_body field: a JSON object
survives GraphQL→pconfig→GraphQL intact, and an absent one stays nil rather
than becoming an empty map.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 04:03:42 +07:00
Sergey KozyrenkoandClaude Opus 4.8 cae0295e8b feat(providers): expose per-agent extra_body in the provider config
The backend already threaded a per-agent `extra_body` map into the LLM request
(pconfig.AgentConfig, openai.WithExtraBody), but it was reachable only from YAML
provisioning — the GraphQL type, the converter, and the settings form all
dropped it. Editing a YAML-provisioned provider through the UI therefore round-
tripped its config and silently stripped extra_body.

Add `extraBody: Map` to AgentConfig / AgentConfigInput, carry it through the
converter in both directions, and give each agent an "Extra Body" JSON field in
the provider form (validated as an object, serialized on load, parsed on save).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 03:57:23 +07:00
Sergey KozyrenkoandClaude Opus 4.8 648bd1a018 fix(ui): give the detail pager a fixed slot so header actions can't shift it
The prev/next stepping control sat first in the header's right-anchored action
cluster, so a per-entity action that appears after load or differs between
entities (e.g. the flow Report button) pushed the pager sideways — clicking Next
repeatedly landed on whatever slid under the cursor.

AppHeaderActions now takes a `pager` slot rendered as the cluster's trailing
child: its right edge is pinned to the header edge and its width is constant, so
variable actions grow leftward without moving it. flow / template / knowledge
detail headers route their DetailNavigationToolbar through the slot.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 03:56:19 +07:00
Sergey KozyrenkoandClaude Opus 4.8 b260b1d735 feat(editor): syntax-highlight code blocks and caption their language
Fenced code in the editor rendered as one flat grey block with no colour and no
visible language, even though the fence language was already captured into the
node and round-tripped. Swap the plain StarterKit codeBlock for CodeBlockLowlight
(lowlight + highlight.js are already deps; the tiptap wrapper is the one add),
keeping the byte-fidelity parseMarkdown/renderMarkdown tuning verbatim — the
highlighting is a view-only ProseMirror decoration and never touches the
serialized markdown. renderHTML stamps the language onto the `<pre>` as
data-language so a CSS caption bar names the block, matching the read-only
viewer's atom-one-dark theme.

Verified: all 337 existing editor round-trip tests still pass, plus a new one
asserting the fence language reaches attrs.language and survives save for
ts/python/bash/json/go.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 03:10:17 +07:00
Sergey KozyrenkoandClaude Opus 4.8 487b82f44a test(e2e): unit-test the mock matcher instead of narrating it, drop dead comments
The mock world's matchers carried five explanatory comments and no test. Cover
them directly — order-independent variable matching, nested-object subset,
sequenced-then-repeated entries, a mismatched REST body staying unmatched, and
flag-gated visibility — and delete the prose they replace. The order test is
built key-by-key on purpose: a literal would be re-sorted by the linter, which
silently defeated the first version (a stripped key-sort still passed until the
value was moved inside an array, where stableStringify actually normalises it).

Sweep the rest of e2e for comments that only narrate the test or restate the
code — step labels, "happy path", cassette descriptions, field docstrings — and
remove them. Kept: framework gotchas whose violation is silent (a probe reading
a colour mid-transition, react-hook-form's disabled Submit, a pre-ack frame that
storms graphql-ws), security notes, magic-value and source-of-truth pointers.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 01:48:22 +07:00
Sergey KozyrenkoandClaude Opus 4.8 a69c9bf57a fix(e2e): remove the sandbox data volumes on Tier-2 teardown
Each sandbox gets a `<container>-data` volume created straight on the docker
socket, outside the compose project, so removing the container left the volume
behind and every Tier-2 run added one more. Confirmed on this machine:
pentagi-terminal-90001-data and -90002-data outlived their containers.

Swept with the same anchored 9xxxx filter the container removal uses, so a dev
stack's volumes are left alone.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 00:09:43 +07:00
Sergey KozyrenkoandClaude Opus 4.8 d012819f6b test(e2e): make the colour gates fail loudly when they stop measuring
Three ways these gates could go green while measuring nothing:

The editor probes name their classes by hand — the one place in the contrast
spec that does not import them from the app. A rename, or the rule moving out
from under its ancestor chain, would mount a span matching no rule, and the
measurement would fall back to the page's default text pair, which clears AA.
The probes now reject a transparent background, which only an unmatched class
produces (the check lives with the editor probes, not in the shared measure —
the outline badge legitimately paints no background).

The dark sweeps seed a theme key that mirrors a *default parameter value* in the
provider, so it can stop matching without any test file changing; the run would
then repeat the light theme under a dark label. Both sweeps now assert the theme
actually applied.

The resources target-size waiver matched `.rounded` unanchored, so it also
covered every `rounded-*` utility — a too-broad waiver never fails, it only
hides. Anchored to the class it documents.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 00:09:42 +07:00
Sergey KozyrenkoandClaude Opus 4.8 2fd4c0b685 test(e2e): replace three assertions that could not fail
`toHaveClass(/destructive/)` on the delete confirm matched every shadcn Button —
the base class string carries `border-destructive` and `ring-destructive/*` for
the invalid state — so the one guard against an action losing its destructive
variant, a regression this repo already shipped once, was dead. Anchored on the
variant's own `bg-destructive` fill instead.

The message-alignment check took `.items-end` first-match anywhere on the page
and never asserted the contrasting case; it now binds to the input message and
pins the count, so an inverted ternary fails on both.

`not.toHaveClass(/dark/)` also holds before the provider has applied any class,
so the light half of the theme switch proved nothing; the provider sets an
explicit `light`, so assert that. Same shape as the menu-item absence check,
which now anchors on an item that stays.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 00:09:21 +07:00
Sergey KozyrenkoandClaude Opus 4.8 5c2d4bdbcd refactor(e2e): hang a11y waivers on the route they belong to
Keying the waivers by route path made the spec restate the manifest's sample
flow id, so renaming that id would silently unhook the waiver and redden a route
over debt that was already accepted. The waivers now live on the manifest entry
and travel with it; scanA11y takes the list directly, which also drops the
route-keyed map the hand-written sweep needed.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-21 22:49:42 +07:00
Sergey KozyrenkoandClaude Opus 4.8 480fc95cd9 test(e2e): drive the axe sweep off the route manifest
The sweep hand-listed six scans while the manifest holds nine routes, so
/dashboard, /resources, /settings/prompts and /settings/providers were never
scanned in either theme — and since the pixel matrix cannot see a colour change
either, those pages had no automated accessibility instrument at all. It now
iterates the manifest, so a route added to the sweep is scanned by construction.

The four newly covered routes surfaced real debt on the first run. One was a
genuine invalid-ARIA bug and is fixed in its own commit; the rest are recorded as
named waivers: the dashboard period switcher points aria-controls at a tab panel
it never renders, and the resources tree has 80%-muted row metadata under AA plus
an expand toggle and row checkboxes under the 24px pointer-target floor. Each
waiver names one defect and matches only its own nodes, so the same rule still
fires anywhere else on the page.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-21 22:41:52 +07:00
Sergey KozyrenkoandClaude Opus 4.8 a6f867cdae test(e2e): pin the request payload on the mutations that carry one
Seven payload-bearing cassette entries answered success no matter what the app
sent: the four flow mutations, both create mutations, and the mkdir POST. Since
each assertion then reads canned cassette data, a wrong payload — a stale closure
deleting flow 6 while flow 5 is open, an unbound name field — repainted exactly
the asserted UI and the suite stayed green. Verified by flipping a pinned flow id
and a pinned path: both specs now fail on the unmatched request, and both passed
before.

Matching had to grow a level for this: `bodySubset` documented a deep subset but
compared nested values whole, so `{ input: { name } }` demanded the entire input.
It now recurses, which is also what makes the API-token pin possible — its `ttl`
is derived from the clock at submit time and drifts a second between runs, so
only the operator-entered name is pinned.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-21 22:41:34 +07:00
Sergey KozyrenkoandClaude Opus 4.8 66fd432edd fix(a11y): drop aria-sort from the file-manager sort headers
The listing is a `tree`, not a grid, so there is no columnheader for `aria-sort`
to live on — axe rates it a critical `aria-allowed-attr` violation on every
sortable column. The sort state is already announced through the button's label
("Sort by name (ascending)"), so removing the attribute loses nothing.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-21 22:41:34 +07:00
Sergey KozyrenkoandClaude Opus 4.8 c479aec390 test(e2e): make the hover contrast assertion actually measure hover
The probes carry `transition-colors`, so reading the computed background right
after hover() sampled a colour still interpolating away from the rest state —
the half of the gate that exists to catch hover regressions could not catch one.
Disabling the transition on the probes fixes it: verified by giving one variant a
deliberately unreadable hover fill, which the assertion now reports as "badge
blue on hover" and previously let through.

Key the probe list off the variant union so a new badge variant fails to compile
until it is probed, rather than silently going unmeasured.

Also correct two route-manifest ownerships that misdirect diff-scoping: the flows
provider is mounted by the detail route as well as the list, and the provider
detail page was attributed to the list route that never renders it.

Doc fixes: the route sweep is tagged @cross, not @coverage; the licenses link in
CONTRIBUTING resolved outside the repository; and the frontend prettierignore
duplicated entries prettier already reads from gitignore.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-21 22:18:37 +07:00
Sergey KozyrenkoandClaude Opus 4.8 291a0af0dc ci(e2e): stop the PR comment lying, and keep stand artifacts free of the stand
Four independent ways the signal misled:

Adding a label to a PR skips every gate job, yet the report still ran, found no
results file and overwrote a correct green comment with a red "no results". It
now returns early when the run carries no completed mock job.

A run aborted by the global timeout still uploads a results file whose failure
count is zero, so the header could go green over a red job; the verdict now
requires the mock job's own conclusion too.

The report's concurrency key was the branch name alone, so a fork PR opened from
a branch named `main` lost its comment to upstream `main` activity. The gate's
key split `opened` from `synchronize`, leaving both runs live so the older one
could finish last.

Stand failure screenshots carried the stand URL and the login into a public
artifact — screenshots are now tier-aware like traces and videos already were.

Also guard the Tier-2 teardown: the trap is the script's last statement, so a
teardown hiccup turned a passing run red.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-21 22:18:22 +07:00
Sergey KozyrenkoandClaude Opus 4.8 057a223b86 fix(ui): use the shared green badge in the provider test results
The "Success" badge and the all-passed accordion badge were assembled from raw
utility classes (`text-green-600` on a green tint, no dark override) instead of
the shared variant, so they kept the pre-unification shade and render at about
3:1 in light theme — under the 4.5:1 floor every other colored badge now meets.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-21 22:18:21 +07:00
Sergey KozyrenkoandClaude Opus 4.8 c48876cd22 ci(e2e): flag an advisory visual diff as a warning, not a mock-tier failure
The sticky PR comment took its header from the whole-workflow conclusion, so a
visual-snapshot diff — advisory, never a required check — rendered a red ❌ over a
"62 passed, 0 failed" mock-tier stats line, reading as a gate failure it isn't.

Track the header on the mock gate instead (✅ pass / ❌ real failure) and surface a
differing visual job as a separate ⚠️ line pointing at the diff artifact.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-21 19:18:16 +07:00
Sergey KozyrenkoandClaude Opus 4.8 07a2d1fa2d fix(ui): match the editor variable colour to its panel badge, tag to violet
A used template variable read as green in the Available-variables panel (its
"used" badge) but violet in the editor highlight — the same entity, two colours.
Swap the editor variable to green and the <xml-tag> highlight to violet so it
stays distinct. A pure hue swap: lightness and chroma are untouched, and every
token still clears WCAG AA in both themes (tightest is the dark tag at 5.36).

Guard the editor palette in cross/contrast.spec.ts alongside the badges, mounting
the real .template-* rule so the shipped CSS is measured, not a copy — verified to
fail when a token is pushed under AA.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-21 18:48:15 +07:00
Sergey KozyrenkoandClaude Fable 5 10baac43da test(e2e): cover the Files and Screenshots flow tabs
The last two uncovered detail tabs. Files turned out not to be REST-backed at all:
it runs its own flowFiles query, separate from FlowDocument, so it needed a keyed
cassette entry and paths under the manager's uploads/resources prefixes — a file
seeded outside those roots renders nowhere. Screenshots reads FlowDocument like the
other four; only its image is fetched over REST.

That image is the part worth guarding. It mounts behind an intersection observer
and loads lazily, so a spec that merely opens the tab never requests it — the first
version passed with the cassette entry removed. It now scrolls the card into view
and asserts the decoded width, since toBeVisible is satisfied by an element that
failed to decode. Removing the entry fails it twice over: zero width, and the
unmatched-call gate.

Serving those bytes needed the REST mock to stop assuming JSON, so entries can now
declare a content type and have their body passed through verbatim.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-21 16:05:43 +07:00
Sergey KozyrenkoandClaude Fable 5 f2ae87bc8f test(e2e): stop a host run from writing unusable visual baselines
Nothing enforced the container requirement — only a comment mentioned it. Running
the visual project on a developer machine writes `*-visual-darwin.png` next to the
linux baselines: new files CI never reads, so it stays red while the repo collects
junk and nothing says why. Fail up front with the command to use instead.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-21 15:55:53 +07:00
Sergey KozyrenkoandClaude Fable 5 04e923c6da Revert "test(e2e): make the visual gate actually sensitive" — threshold only
Strict pixel comparison was stable across seven local container runs and failed on
the first CI run: /flows differed by 332 and 384 pixels, identically on both
attempts, so it is a systematic host difference in text rasterisation rather than
jitter. The pinned image fixes the renderer, not the machine under it.

A budget wide enough to absorb 400 pixels cannot notice the ~70 a palette change
moves, so this trade has no useful setting — pixels are the wrong instrument for
colour. Back to the default tolerance, with the reasoning recorded so the next
attempt starts from the CI measurement rather than a local one.

The masking-race fix from the same commit stays: it was a real defect.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-21 15:20:17 +07:00
Sergey KozyrenkoandClaude Fable 5 01cecc2173 test(e2e): make the visual gate actually sensitive, and fix its masking race
The suite was carrying Playwright's 0.2 per-pixel default, a tolerance meant for
cross-machine rendering noise that the pinned container removes by construction.
It cost the gate its sensitivity: a real palette change passed while three
baselines silently went stale.

Compare strictly and bound the differing-pixel count instead. Measured over
repeated container runs, glyph antialiasing jitters by exactly 2 pixels, while the
palette change that slipped through moved 71 — so threshold 0 with a 20-pixel
allowance tolerates the noise and catches the class of change that got away.

Strict comparison also exposed a real defect the loose one hid: the flow detail's
ready locator was the header button, but the visual spec masks the terminal, which
mounts later. Capturing in that window compared live terminal pixels against a
masked baseline — a 261k-pixel diff, roughly a third of the frame, appearing at
random. The route now counts as rendered when its terminal exists.

Seven consecutive container runs are clean at the new settings.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-21 15:14:25 +07:00
Sergey KozyrenkoandClaude Fable 5 1d98b73660 fix(ui): put every colored badge on one light shade, dropping the green exception
Green sat a step darker than its siblings because green-700 measures 4.4991
against its tint — imperceptibly short of AA, but short. Carrying that as a
one-variant exception meant an odd shade number in the map, and the only ways to
let green back to 700 were to lower the gate for all eleven variants or to waive
it in the spec, which is the same exception wearing a different hat.

Move all seven to 800 instead. One rule, no exception, and the whole set clears
the bar with room: 6.39–7.83 on light, against 4.61–6.49 before — orange and
yellow had been sitting close enough that a later tint tweak would have pushed
them under. Dark is unchanged.

Three visual baselines were quietly stale: the earlier 600→700 move changed blue
text that the pixel comparison tolerated, since its YIQ metric under-weights a
blue-channel shift with little luminance change. Regenerated; two clean runs
confirm they are deterministic.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-21 14:31:32 +07:00
Sergey KozyrenkoandClaude Fable 5 26189c65e0 refactor(e2e): drop the contrast helper commentary
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-21 14:23:46 +07:00
Sergey KozyrenkoandClaude Fable 5 569d95e8dd test(e2e): gate every badge and destructive fill on measured AA contrast
The palette fixes had no guard: no scanned page renders a colored badge or a
destructive fill, so a shade edit could silently drop a variant under AA and
nothing would fail. Two comments were standing in for that coverage.

Mount one probe per variant from the component's own cva — a class list copied
into the spec would only ever re-test itself — and measure what the browser
actually paints, so oklch tokens and translucent fills are read as rendered.
Every variant is checked at rest and on hover, in both themes.

The measurement is deliberately unrounded: green-700 comes out at 4.4991, which
two decimals report as a passing "4.5". With rounding in place the guard passed
against a deliberately regressed green; without it, it fails and names the
variant, the state and the ratio.

Specs can now import component modules, so the e2e tsconfig gains jsx.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-21 14:05:28 +07:00
Sergey KozyrenkoandClaude Fable 5 421074e583 refactor(ui): drop the badge and button palette commentary
Three comments added with the contrast fixes were mostly narration: two restated
the class strings they sat above, and two defended the implementation rather than
naming a contract. The one fact that is not visible from the code — green sits a
step darker than its siblings — belongs in a test that fails when it regresses,
not in prose asking the reader not to touch it.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-21 13:53:48 +07:00
Sergey KozyrenkoandClaude Fable 5 9f40102d6a fix(ui): keep white on the destructive fill readable in both themes
Four states were under AA, not one: the dark badge and button at rest (3.71), the
light badge on hover (4.34) and the dark button on hover (4.40), plus the dark
destructive menu item (4.01). Badge and button had also drifted apart — one faded
to 80% on hover, the other to 90% — so each failed in a different theme.

The token itself cannot be retuned: sweeping its lightness finds no value that
serves both roles, because the same red is a fill under white text and the text
colour on the page. Darkening it for the fill would break the twenty-four
text-destructive call sites.

Tune the fill's opacity per theme instead, keeping white text and adding no tokens.
A translucent red composites toward what is behind it, so the same fade darkens it
on the dark ground and lightens it on the light one: full strength on light fading
to 90% on hover, 80% on dark dropping to 70%. Hover now raises contrast in both
themes. All four states land between 5.04 and 6.28, verified on a built bundle
against every dark surface token (worst case 5.13 on secondary).

The dark destructive menu item drops its focus wash from 20% to 10%, matching light
and restoring the label to 4.52 at the cost of a fainter highlight.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-21 13:42:11 +07:00
Sergey KozyrenkoandClaude Fable 5 f88427c264 fix(ui): give colored badges a per-theme text shade so they meet AA
Every colored Badge variant carried a single text shade for both themes, and no
one shade clears WCAG AA on both grounds. Measured against the current tints,
five of the seven failed on light and four on dark, with red and pink failing on
both — the badge text is 12px semibold, so the bar is 4.5:1.

Use the darker shade on the light tint and the lighter one on dark:
text-{color}-700 with a dark:text-{color}-400 override. Green takes 800 instead
of 700 because a shade number is not a constant lightness across hues — green-700
measures 4.4991, just under the bar.

Every variant now lands between 4.6 and 9.7. The knowledges a11y waiver is gone
and both theme scans pass without it; the knowledges dark visual baseline is
regenerated for the lighter blue.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-21 12:58:45 +07:00
Sergey KozyrenkoandClaude Fable 5 e8aa8df192 docs(e2e): correct the badge contrast waiver note — both themes fail
Measuring the variants (browser-resolved sRGB, the 10% tint composited over the
real card surface, WCAG formula) showed the defect is not dark-only: five of the
seven colored variants fail AA on light and four on dark, and no single text shade
clears both grounds. Blue happens to pass on light and fail on dark, which is why
only the dark scan flags it here. The waiver itself is unchanged.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-21 12:21:41 +07:00
Sergey KozyrenkoandClaude Fable 5 43387a7f7b test(e2e): cover the query-backed flow detail tabs
Only the Terminal tab had a spec; Tasks, Agents, Searches and Vector Store — all
fed by the FlowDocument query — were uncovered. Add a populated flow cassette (one
entry per tab) and a spec that opens each tab and asserts its seeded content
renders. Files and Screenshots are REST-backed and left for a follow-up.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-21 05:04:40 +07:00
Sergey KozyrenkoandClaude Fable 5 17d34161cd test(e2e): add a populated settings-providers visual baseline
The route-manifest visual sweep only captured the empty providers state. Add a
populated cassette (enabled defaults + a user-defined provider row) and a dedicated
visual spec with light/dark baselines, generated in the pinned container. Dates
render deterministically because the visual project inherits the mock clock via the
backend fixture.

Also bind --update-snapshots=all in run-visual.sh so a trailing spec-file filter is
not swallowed as the option's optional [mode] argument.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-21 04:54:34 +07:00
Sergey KozyrenkoandClaude Fable 5 dcea92e17b docs(e2e): document the spec tag taxonomy and the gate's reserved tags
The suite tags every spec but the docs only hinted at "@smoke, …". List the real
tags (@smoke/@flows/@crud/@coverage/@cross/@visual/@real/@stand) with their meaning
and how to filter, and spell out the two conventions the mock gate reserves:
@quarantine to isolate a flaky spec (excluded via --grep-invert) and @generated for
recorder-derived cassettes.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-21 04:49:53 +07:00
Sergey KozyrenkoandClaude Fable 5 3d092f989c test(e2e): scan a11y in dark theme too, waiving the known badge contrast debt
axe only ran in the light theme, so dark-only contrast regressions were invisible.
Parametrize every a11y scan over light and dark. The dark pass surfaced a real,
pre-existing issue: colored Badge variants use text-{color}-600 with no dark
override and fail contrast on the dark background. Waive it narrowly on the
knowledges list (the blue badge) as named debt — a palette fix is queued
separately — so the rest of the dark surface is now gated.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-21 04:43:17 +07:00
Sergey KozyrenkoandClaude Fable 5 16e926614c test(e2e): assert the dashboard period switch renders a distinct range
The period-switch test only proved the usageStatsByPeriod refetch fired; it would
still pass if the UI rendered stale data. Key the cassette's usageStatsByPeriod by
period (week vs month) with distinct date ranges, and assert the Token Usage chart
x-axis shows the month range after the switch and drops the week range.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-21 04:33:57 +07:00
Sergey KozyrenkoandClaude Fable 5 f5070667de test(editor): state the real byte-integrity invariant for GFM cell whitespace
The comment claimed no non-backslash byte is lost, but GFM legitimately trims
cell-edge and collapsed whitespace, so the test asserts the weaker true invariant:
every byte other than backslashes and that trimmed whitespace survives in order.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-21 03:59:17 +07:00
Sergey KozyrenkoandClaude Fable 5 179c814bb3 chore(e2e): scope Tier 2 networks and gate pentagi on a healthy mock LLM
The base compose file pins fixed network names, so any network left un-overridden
in this e2e override joins the stack to the developer's live observability and
langfuse networks. Give all three networks e2e-scoped names. Add a healthcheck to
the mock-LLM service and make pentagi depend on service_healthy, so a crash-looping
mock can never read as a started dependency and silently mask itself.

Update frontend/docs/e2e.md to match reality: the stand tier runs @stand only
(flow-run drives a real paid agent and stays local), every mock run rebuilds its
own bundle by design, and the trend/affected-routes notes.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-21 03:59:07 +07:00
Sergey KozyrenkoandClaude Opus 4.8 25b0229282 docs(frontend): move the list/detail guide to frontend/docs and correct its drifted API
The co-located components/shared/README.md documented hooks that no longer
exist. `usePagination` was never a hook, and the writer `useTableQueryFilter`
was replaced by the unified `useTableState`, so the copy-paste recipe it shipped
would not compile. Detail pages had likewise moved from spreading a `toolbarProps`
object to passing a `controller` prop.

Rewrite it as frontend/docs/list_detail_pages.md, matching the flat
per-subsystem layout backend/docs already uses: exact signatures for every
hook, component and storage helper, the wiring the five live list pages
actually use, and an explicit table of removed names so they are not
reintroduced. Drop the source-adjacent README — no other directory under
frontend/src or backend/pkg carries one.

Fix the comments that still named the removed hook, plus two claims in them
that contradict the code: the controlled filter is URL-backed only (DataTable
persists sorting, column visibility, page size and search columns, never the
filter), and `busy` on InlineEditInput disables the Save and Cancel buttons
while leaving the input editable.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-21 03:28:58 +07:00
Sergey KozyrenkoandClaude Fable 5 7ff38f2da6 fix(e2e): locate dashboard cards by data-slot, not an uncommitted test id
The dashboard partial-errors spec matched cards via getByTestId('dashboard-card'),
but that attribute lives only in an uncommitted working-tree change, so on a clean
checkout the locator matched nothing and the spec failed. Match the data-slot="card"
attribute the shadcn Card primitive already emits. Also lift the inline xterm buffer
type in the message-rendering spec into named types so it satisfies prettier and the
union/module sort lint rules.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 19:30:43 +07:00
Sergey KozyrenkoandClaude Fable 5 7acd0b6cca test(e2e): cover the rejected-login path
The smoke only exercised a successful login. Adds a cassette whose
/auth/login answers an error envelope and asserts the surfaced error plus
that Sign in stays disabled (react-hook-form holds it until a field
changes) — the negative path a live run confirmed but no spec covered.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 16:11:45 +07:00
Sergey KozyrenkoandClaude Fable 5 6b493a391a test(e2e): cover the type-specific message render paths
The message cassettes were all Answer-typed, so flow-message.tsx's
type-specific branches never ran under test. A live QA run against a real
Bedrock flow showed real streams emit thoughts/report/terminal/input.
Adds a cassette with one message per path and asserts each: the
thinking toggle (thinking + message), a report that auto-expands its
details, a Terminal-format report that mounts the xterm renderer with
its output, and an input message's right alignment.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 16:06:31 +07:00
Sergey KozyrenkoandClaude Fable 5 4b6dd0423e fix(e2e): harden real-tier specs, CI, and mock-gate rigor after review
Real-tier (Tier 2/3) fixes, the blocking set:
- stand-smoke asserts a per-route anchor (breadcrumb title span) instead
  of a shared sidebar link that 0-matches on /settings/* and double-matches
  on /templates — the smoke was structurally red on 3 of 5 routes.
- stand-tier trace/video forced off (they embedded the session cookie and
  the stand password in a public-repo artifact) and the stand project
  selects @stand via config grep (the CI step selected zero tests).
- run-local-tier's sandbox filter is anchored to the seeded 9xxxx range
  (`^/?pentagi-terminal-9[0-9]{4,}$`) so it can't force-remove a dev's
  flow-9 sandbox; sandbox cleanup moved behind the keep-stack gate; compose
  logs are captured before teardown.
- mock-LLM wraps the request handler (a non-JSON body crashed the process);
  its transcript now issues a real terminal exec via a delegate chain and
  flow-run asserts the terminal output; OpenAI-shaped error envelope.

Mock-gate rigor + coverage:
- order-insensitive deep-subset variable matching; unmatched WS subscribes
  are now accounted at teardown; REST/GraphQL entries can pin a body/vars
  subset; favorite-star asserts the persisted (not optimistic) value.
- new flows/create smoke (the primary journey had no mock coverage), a
  graphql-ws protocol unit test against the real client, and a
  route-manifest completeness test.
- affected-routes no longer under-scopes shared component dirs.

Hygiene: .mjs tools now linted/prettier'd; dead gitignore line; JSDoc/
sheet aria-label/schema-compat/trend/serve-dist/report-comment fixes.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 15:59:30 +07:00
Sergey KozyrenkoandClaude Fable 5 2d1e677e75 fix(e2e): match the stand-smoke URL by pathname, not a string-built regex
new RegExp(route.replace(/\//g,'\\/')) tripped CodeQL
js/incomplete-sanitization (only slashes escaped). The routes are
constants, so it was a false positive — but the predicate form is
cleaner and asserts the exact pathname.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 06:24:54 +07:00
Sergey KozyrenkoandClaude Fable 5 6426bb9923 fix(e2e): don't disable TLS validation in committed code
schema-compat set NODE_TLS_REJECT_UNAUTHORIZED=0 process-wide (CodeQL
js/disabling-certificate-validation, high). A real stand has a valid
cert; only the local self-signed Tier-2 stack needs it, so the operator
now opts in via their own shell env, never in code.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 06:20:53 +07:00
Sergey KozyrenkoandClaude Fable 5 419c56317a feat(e2e): phase 3 infra — schema-compat, trends, diff-scoping, stand job
Lays the Phase-3 substrate on top of the three tiers.

- schema-compat pre-flight (e2e/tools/schema-compat.mjs): introspects a
  target backend's live GraphQL schema and validates every frontend
  operation against it, so deploy skew (a renamed/removed field) fails
  once, readably, instead of as dozens of red specs. Verified against the
  live Tier-2 backend both ways: 105 operations pass, an injected bogus
  field is caught with the exact location.
- trend aggregation (trend.mjs): turns a run's results.json into one JSONL
  record (p50/p95 spec duration, slowest three, pass/flaky/fail) so slow
  regressions are visible, not just green/red; CI appends it to a
  90-day-retained artifact.
- diff-scoping (affected-routes.ts + affected.ts): maps a diff to the
  manifest routes it touches via each route's owning sources — the
  substrate for selective runs and for scoping the exploratory agent.
  Pure mapping fn, unit-tested (backend-only → none; shared infra → all;
  owned → that route).
- CI: an e2e-stand job (label-gated + a protected Environment whose
  reviewers approve before secrets are exposed; schema-compat runs first),
  a trend step, and an LLM-independent @stand smoke.
- docs: the stand tier, trend/affected tools, and the LLM advisory recipe
  (playwright-mcp + init-agents + guardrails) — the recipe the
  deterministic tiers plug into, not a bespoke bot.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 06:17:59 +07:00
Sergey KozyrenkoandClaude Fable 5 dc66898bc8 feat(e2e): visual snapshots — route×theme matrix in the pinned container
18 baselines (9 manifest routes × light/dark) compared only inside
mcr.microsoft.com/playwright:v<version>-noble, so pixels are identical on
every machine and CI; the wrapper derives the tag from the installed
@playwright/test version, making the pin drift-proof, and a CI guard
fails loudly if the workflow's container tag falls behind.

macOS hosts cannot run the visual project directly (parallel darwin
baselines) nor mount their node_modules into the container (native vite
binaries): the wrapper builds dist on the host and the container serves
it with a dependency-free static server — route mocks intercept API
calls before the network, so no proxy is needed. The xterm canvas is
masked (SwiftShader pixels are driver-dependent). Determinism proven by
back-to-back container runs. The e2e-visual CI job is advisory, never a
required check.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 04:02:29 +07:00
Sergey KozyrenkoandClaude Fable 5 1a4f603216 feat(e2e): tier 2 — real backend run driven by an OpenAI-compatible mock LLM
specs/real/** now exercise the actual agent loop end to end: create flow
-> image/language/title -> tool-call-ID sampling -> subtask_list plan ->
done barrier -> subtask_patch refine -> report_result — with messages
streamed over the real GraphQL websocket and the flow settling in
Waiting. The mock LLM is ~150 lines of Node driven by a deterministic
first-match transcript; the custom provider env seam means zero backend
changes.

The stack is fully isolated from a developer machine:
- own compose project/network/ports (8444/5433), coexists with a dev stack
- --env-file /dev/null so the developer's .env (live keys, DOCKER_HOST,
  config paths) never leaks into the e2e backend
- flow ids seeded from 90001: sandbox containers are named
  pentagi-terminal-<flowId> on the shared docker daemon, so the range
  keeps them clear of dev flows and makes runner cleanup unambiguous
  (down -v cannot remove them — the backend spawns them outside compose)
- pentagi healthcheck via busybox wget (the alpine image has no curl),
  since the base service has none and up --wait returns too early

Auth for live tiers moved to the canonical setup-project + storageState;
the localStorage seed is now mock-tier-only (a forged client session has
no cookie behind it and the first 401 wipes it). CI gains a nightly/
dispatch-only e2e-local job.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 03:54:05 +07:00
Sergey KozyrenkoandClaude Fable 5 c2577777e8 fix(editor): give the backslash/pipe property test the heavy-generative timeout
The suite's generative tests run with timeout 30000 — the new one missed
it and tripped vitest's 5s default on slower CI runners.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 03:11:04 +07:00
Sergey KozyrenkoandClaude Fable 5 6b22e28c3a fix(ci): drop the duplicate Go cache restore and pin token permissions
setup-go's cache:true already caches the build and module caches keyed
on go.sum; the extra actions/cache step restored the same read-only
~/go/pkg/mod on top and failed with "Cannot open: File exists" whenever
both caches hit. Also sets the workflow's GITHUB_TOKEN to contents:read.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 03:06:25 +07:00
Sergey KozyrenkoandClaude Fable 5 6badfb90db fix(editor): keep table cells intact when cell text ends a backslash run with a pipe
marked's cell splitter honors \| only after an odd backslash run and
truncates rows that split into extra columns, so escaping the pipe alone
in text like a\|b produced \\| — a live delimiter that dropped the
trailing cells on the next load. An odd run + pipe has no exact GFM
encoding: the serializer now pads the run by one backslash, trading a
one-character gain inside the cell for structural integrity, byte-stable
from the first save. Covered by direct round-trips and a random \/|
payload property test.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 03:02:25 +07:00
Sergey KozyrenkoandClaude Fable 5 5cb0522818 feat(e2e): dashboard, settings, resources coverage + route manifest sweep
Completes the scenario-catalog coverage on the mock tier (48 specs).

- dashboard: analytics/overview tabs (lazy mount), period switch verified
  on the wire, and the per-card degradation path — a failed stats query
  renders "Couldn't load" in its own card while neighbours stay live
  (first use of error-response cassette entries)
- settings: prompts (the largest typed cassette — 15 agent + 12 tool
  prompt configs), providers empty state, create form opens
- resources: REST-seeded file tree, and the mkdir journey proving the
  full chain — REST mutation raises a world flag, the flag releases a
  resourceAdded frame, the subscription cache merge grows the tree
- e2e/routes.ts: route manifest (paths imported from src/lib/routes so
  a rename breaks compile) driving a data-driven NAV sweep over 9
  routes; entries carry owning source dirs for future diff-scoping

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 03:01:59 +07:00
Sergey KozyrenkoandClaude Fable 5 99829bff0b fix(a11y): give the built-in dialog X a name distinct from page Close buttons
The token-reveal dialog (and any dialog with an explicit Close/Cancel)
exposed two controls named "Close" — ambiguous for screen readers and
for role-based locators in strict mode. The shared X is now "Dismiss
dialog".

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 01:58:24 +07:00
Sergey KozyrenkoandClaude Fable 5 b2990538a7 feat(e2e): flow streaming/reconnect/lifecycle, entity CRUD, and cross-cutting specs
Builds on the mock gate: 26 new specs across flows, CRUD, and cross
concerns, all driven by typed cassettes against the production bundle.

- flows: no-duplicate and exact-set-disjoint message streaming across
  concurrent flows (ID sets attached to the report), reconnect that
  reconciles the missed delta exactly once, and the rename/finish/
  favorite/delete lifecycle chained mutation->subscription-frame
- mock engine: streams move to one-driver-broadcast (flowUpdated is
  opened by two providers at once; reconnect re-joins past the cursor,
  delta-only) and frames can wait on world flags
- CRUD: templates, knowledges (required-validation proves no mutation
  fired via the zero-unmatched teardown), api-tokens (inline create,
  one-time secret reveal)
- cross: themes (seeded + toggled), responsive (Pixel 7 touch profile,
  1279/1280 split boundary), a11y with a policy - critical/serious
  floor plus a committed per-route allowlist
- terminal content is asserted through the xterm buffer (the WebGL
  canvas has no DOM text): the hook now exposes the instance on its
  host element
- app fixes surfaced by the sweep: the rows-per-page select had no
  accessible name; the favorite star is useOptimistic and only
  persists via the settingsUserUpdated frame - the spec now asserts
  the real persistence path

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 01:24:18 +07:00
Sergey KozyrenkoandClaude Fable 5 bae81a9b22 chore: ignore Playwright MCP page-snapshot artifacts
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 00:31:26 +07:00
Sergey KozyrenkoandClaude Fable 5 67266c9316 feat(e2e): Playwright scaffold with a hermetic mock gate
The default tier runs the production bundle (vite build + preview)
against a cassette-driven mock of the whole API surface — GraphQL over
HTTP, graphql-transport-ws subscriptions, and REST — so the suite needs
no backend, no keys, and no secrets, and fork PRs can run it.

- mock engine: (operationName, variables) matching with sequenced
  entries and world flags (login flips /info guest->user without
  call-order coupling); unmatched calls answer 501 and fail the test,
  so nothing leaks through the vite preview proxy to a live backend
- ws mock follows the graphql-transport-ws contract the app's client
  needs: immediate ack, nothing before ack, streams stay open, delta
  cursors survive reconnects, drops use retryable close codes
- clock and timezone pinned on the mock tier: formatDate branches on
  isToday/isThisYear, so unpinned cassette dates rot within a day
- cassettes are TS modules typed against the generated GraphQL types,
  so schema/operation drift fails the existing tsc gate at compile time
- CI: fork-safe e2e.yml (read-only token, no secrets, no write steps)
  plus e2e-report.yml posting a sticky PR comment via workflow_run,
  resolving fork PRs by head SHA
- smoke specs (login redirect, form login, authenticated /flows render)
  green on the mock tier; e2e/ wired into tsc, eslint, and prettier

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 00:30:18 +07:00
Sergey KozyrenkoandClaude Opus 4.8 f3972bb9d1 fix(ui): guard error/loading surfaces and the ws reconnect tail
List pages and the flow detail page no longer replace live data with a
full-page error on a failed background refetch — the error/redirect branches
now gate on the absence of data, not on the error alone. On a cold-cache load
failure the flow detail page renders an in-page ErrorState + Retry instead of
silently redirecting to the list, while a genuine not-found still redirects.
Retrying after a failed initial load shows the spinner rather than flashing
the empty state.

Reconnect reconcile: catch the aggregate refetch rejection (the per-query
wrapper doesn't cover it) so a transient failure during the sweep can't
surface as an unhandledrejection, and re-hydrate the REST-backed resources
slot — which the observable-query sweep skips — via a ws:reconnected event.
The flow provider gates its blocking spinner and subscription teardown to the
initial load only, so a background reconcile no longer overlays the page or
bounces the live subscriptions.

Terminal: clear() cancels any in-flight chunked write so its trailing chunks
can't land after the buffer was cleared; the search Clear (X) resets only the
query and keeps the task/subtask filter.

Smaller fixes: role="alert" on ErrorState, a keyboard-operable per-agent Test
control, the correct prompt-validation Alert variant, and dashboard error
props. Shared LoadingState and DashboardError components collapse duplicated
loading/error blocks; terminal write cancellation and the Apollo cache
policies both gain test coverage.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-19 03:34:46 +07:00
Dmitry Ng 2470f6a428 Merge pull request #364 from Osamaali313/fix/newbodypair-reverse-delete
fix(cast): delete pruned tool-call parts in reverse to avoid index shift
2026-07-18 22:00:58 +04:00
Dmitry Ng e772a5cd82 Merge pull request #373 from rakshith48/feat/firecrawl-search
feat(tools): add Firecrawl web search provider
2026-07-18 19:33:57 +04:00
Dmitry Ng c95cc778c0 Merge pull request #362 from jinhaosong-source/feat/orcarouter-provider-config
Add OrcaRouter pre-configured provider
2026-07-18 18:41:38 +04:00
Sergey KozyrenkoandClaude Opus 4.8 b4b640b36b fix(flows): reconcile the cache after a websocket reconnect
The GraphQL subscriptions are delta-only: the server registers a subscriber
for future events and never replays what it published while a client was
disconnected (and it drops events for a disconnected subscriber outright).
Nothing on the client refetched after the socket came back, so a websocket
drop during an active flow — a network blip, a laptop waking, a proxy timeout
— left a permanent hole in the streamed logs/messages/status until the user
manually reloaded the page.

Refetch the active queries on reconnect: graphql-ws hands `wasRetry` to the
`connected` handler, so on a retry (not the initial connect) call
`refetchObservableQueries()`, which re-runs the flow's queries and merges the
full current state back into the cache.

Verified live with a faithful drop (patched WebSocket, real `ws.close()` mid-
flow while the agent kept producing): before the fix the messages created
during the outage stayed missing after reconnect and only a reload recovered
them; with the fix they reappear automatically on reconnect, no reload. (A
CDP "offline" emulation does NOT reproduce this — it buffers the socket rather
than closing it, so use a real close when testing.) 1006 tests pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-18 15:47:30 +07:00
Sergey KozyrenkoandClaude Opus 4.8 c2287ad90c test(apollo): cover the assistant-log streaming link
Round out the subscription coverage with createStreamingLink — the piece that
coalesces streamed assistant token updates. Export it (test-only) and drive it
with a controllable source plus a mocked clock.

Locks the three behaviors that make token streaming feel right: append parts
inside the 50ms throttle window are accumulated but not re-emitted (so the UI
isn't hammered), the next emission past the window carries the full running
message rather than the latest delta, and the final non-append part flushes the
accumulated total and clears the per-id cache so the same id can stream again.
Also confirms a non-assistant-log result passes straight through untouched.

1006 tests pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-18 14:04:22 +07:00
Sergey KozyrenkoandClaude Opus 4.8 e3d9999c17 test(apollo): cover the subscription cache merge-link
The link that folds live subscription events into the Apollo cache
(updateCacheForSubscription) had no coverage — MockedProvider replaces the
whole link chain, so it can't exercise this. Export it and drive it directly
against a real InMemoryCache configured like production (flow-scoped list
fields keyed by flowId).

Locks the routing rules: *Added appends + de-dups by id, *Created prepends
(newest first — not re-sorted by id), *Deleted removes by id, *Updated merges
an entity's fields in place without reordering (and appends if it's not yet
cached). Also covers the two subtle bits: flowId variant isolation (an event
for one flow leaves another flow's list untouched) and type-tolerant id
de-dup (a numeric subscription id matches a string id from REST hydration).

Also exports createSubscriptionCacheLink for future frame-level tests. Pure
additive exports, no runtime change; app verified still loading. 1003 tests pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-18 13:30:15 +07:00
Dmitry Ng d93d45bb4c Merge pull request #350 from mason5052/codex/issue-336-headless-crawler-rfc
docs: add headless crawler integration RFC
2026-07-18 10:14:57 +04:00
Dmitry Ng 6ca92ea40c Merge pull request #347 from mason5052/codex/issue-344-qwen-long-flow-troubleshooting
docs: add Qwen long-flow troubleshooting
2026-07-18 10:11:50 +04:00
Dmitry Ng f8b05690b1 Merge pull request #346 from mason5052/codex/issue-341-fallback-rfc
docs: add tool and model fallback RFC
2026-07-18 09:46:07 +04:00
Sergey KozyrenkoandClaude Opus 4.8 c43c05c29b fix(flows): don't bounce off a working flow on a partial load error
The flow detail query runs with errorPolicy:'all', so a failed sibling field
(the flow's log lists are separate, nullable root query fields — terminalLogs,
messageLogs, etc.) surfaces an Apollo error while `flow` itself resolves fine.
Both the redirect effect and the provider's load-error toast keyed off "any
error present", so one flaky log resolver would kick the user back to /flows
and toast "Failed to load flow" over a flow that had actually loaded.

Gate both on the flow genuinely being absent (`!flowData?.flow`) instead of on
the presence of an error. A missing/invalid flow still redirects and toasts
(its non-null `flow` field propagates to a null result); a partial failure now
renders the flow and lets the affected panel show its own empty state.

Reachability confirmed from the schema (sibling log fields are `[X!]`, nullable;
`flow` is `Flow!`, non-null) — end-to-end confirmation folded into the P2-S5
live run. 996 tests pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-18 12:10:06 +07:00
Sergey KozyrenkoandClaude Opus 4.8 140578fd7c fix(terminal): stop garbling logs after a search filter is cleared
The terminal wrote incrementally by diffing on array length alone: if the
new logs were at least as long as what had been written, it appended the
tail from the old length onward. That assumes the on-screen prefix never
changes — but the same component is fed filtered subsets, so narrowing a
search then clearing it grew the array back past the filtered length and
appended the full-log tail on top of the still-visible filtered lines,
producing a scrambled, partly-duplicated buffer.

Track the exact lines last rendered and only take the append fast-path when
they are a true prefix of the new array; otherwise clear and rewrite. Pure
streaming stays incremental (no clear); any non-prefix change rewrites.

Verified with a repro test (red before, green after): full -> filtered ->
cleared restores the full set, streaming appends never clear, and a
different filter rewrites. 996 tests pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-18 11:55:28 +07:00
Sergey KozyrenkoandClaude Opus 4.8 cf68f3a675 fix(prompts): tell the user when a reset fails instead of only logging it
Resetting a prompt to its default on the prompts list swallowed a failed
delete into console.error — sonner wasn't even imported — so the row stayed
Custom with no hint anything went wrong. Toast it, matching how every other
mutation in the app reports failure.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-18 03:14:12 +07:00
Sergey KozyrenkoandClaude Opus 4.8 f089f01aff fix(flows): show the load error on the page instead of a stacking toast
The flows list did what the other lists used to: on a failed load the provider
fired toast.error with no id — so each repeated failure while the backend was
down stacked another copy — and the page, never reading the error, fell through
to its "No flows" empty state, indistinguishable from an empty account.

The provider already exposed flowsError; read it on the page and render the
shared ErrorState with a Try again button (refetch, now also exposed), and drop
the toast effect entirely. Flows now matches templates/knowledges/resources.

Verified live: three failed refetches leave zero stacked toasts and one error
state with the button (previously three toasts + a false empty state); clicking
Try again after recovery restores the list. 993 tests pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-18 03:02:45 +07:00
Sergey KozyrenkoandClaude Opus 4.8 33191b4c3c feat(ui): add a Try again button to the load-error state
The Empty error state named the failure but left the user stranded — the only
way back was a full browser reload. Give ErrorState an optional onRetry that
renders a "Try again" button, and wire every load-error site to re-run its own
query: templates, knowledges (the active list-or-search query), resources, the
three settings lists, and the two settings detail pages. The templates and
knowledges providers now expose refetch for it; the rest already had one.

Verified live: failing the templates query shows the error with the button,
and clicking it after the backend recovers clears the error and renders the
list — no page reload. 993 tests pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-18 02:52:30 +07:00
Sergey KozyrenkoandClaude Opus 4.8 84c55969d5 refactor(ui): toast settings mutation failures instead of a standing banner
A failed delete/create/update on the provider and API-token lists parked a
persistent destructive Alert above the table, which lingered until the next
action and, for tokens, dumped the raw Postgres constraint text into a banner.
Every other mutation in the app reports failure with a toast; these two lists
were the exception.

Toast them too — the create/update handlers already swallowed the error into a
console.error, so this is the first real feedback they give — and drop the
banner, its error state (deleteErrorMessage plus the unread useMutation error
tuples), and now-unused ErrorAlert component.

Verified live: creating a token whose name already exists surfaces "Failed to
create token" as a toast (no second token written), with no standing banner
left behind. 993 tests pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-18 02:42:28 +07:00
Sergey KozyrenkoandClaude Opus 4.8 866dac1b61 refactor(ui): render list load errors as a full Empty state, not a thin banner
A failed list query showed a one-line destructive Alert stranded at the top of
an otherwise-empty page — it read as leftover chrome rather than the page's
state. The detail pages and the route error boundary already render a failure
as a centered Empty: a large icon, a title, the message. The lists now match.

Add ErrorState (the shared Empty-error the detail pages were inlining) and use
it for the load errors on templates, knowledges, resources, and the three
settings lists, plus the two detail pages that had inlined the same markup —
eight call sites, one shape.

Resources previously only toasted its load failure from the provider while the
page kept showing "No resources yet"; it now shows the error state like the
others, and the provider drops the toast (and the now-unused sonner import).

The settings mutation-error banners stay on the inline Alert — those sit above
rendered content, where a full Empty would be wrong; they're a separate change.

Verified live: a failed templates query (GraphQL) and a failed resources fetch
(REST) both render the centered Empty error instead of a banner or a false
empty state; the healthy paths are unchanged. 993 tests pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-18 02:31:14 +07:00
Sergey KozyrenkoandClaude Opus 4.8 b54c09954c fix(dashboard): show a per-card load error instead of a banner over lying zeros
The banner told the user "something failed" but left every card showing its
value — a down backend rendered Total Cost as $0 and each chart as "No data
for this period", numbers indistinguishable from a genuinely quiet account. And
when a single stat query failed while the other eleven succeeded, the banner
alarmed over an otherwise-healthy dashboard.

Give MetricCard and ChartCard an error state alongside their loading/empty ones
— a muted "—" / "Couldn't load", quiet rather than alarming — and wire each of
the dashboard's queries to its own card and table. A failed query now says so
in its own tile; the rest keep rendering their real data. The top-of-page
banner is gone.

Verified live: failing one period query leaves that chart as "Couldn't load"
while its neighbours draw real bars; a full stats outage fills every card and
table with the quiet error state and no lying zeros; the healthy path is
unchanged. 993 tests pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-18 02:11:08 +07:00
Dmitry Ng 5e8b9c25e4 Merge pull request #345 from mason5052/codex/issue-342-browseros-mcp-rfc
docs: add BrowserOS MCP browser backend RFC
2026-07-17 17:33:19 +04:00
Dmitry Ng 40705ebea8 Merge pull request #343 from mason5052/codex/issue-335-xsstrike-args
fix: avoid unsupported XSStrike flags in pentester prompt
2026-07-17 17:30:49 +04:00
Dmitry Ng af3df846ff Merge pull request #339 from mason5052/codex/issue-338-stream-zip-downloads
fix: stream ZIP downloads without buffering archives
2026-07-17 16:46:19 +04:00
Dmitry Ng 2ef7076bb4 Merge pull request #331 from mason5052/codex/issue-321-vertex-provider-rfc
docs: add native Google Vertex AI provider RFC
2026-07-17 16:05:57 +04:00
Dmitry Ng f3598fa610 Merge pull request #330 from mason5052/codex/issue-313-tool-call-parser-troubleshooting
docs: add tool-call parser troubleshooting for custom LLM backends
2026-07-17 15:46:26 +04:00
Sergey KozyrenkoandClaude Opus 4.8 164597c77a refactor(ui): fold the duplicated load-error alerts onto one component
Five copies of the same destructive Alert — same variant, same AlertCircle,
same title-and-message shape — sat inline across the settings pages, and the
preceding load-error fix had just added four more call sites of it.

Use the shared component at all nine, and rename it to ErrorAlert on the way:
the name it shipped with an hour ago, DataLoadError, was too narrow for two of
the five, which report a failed delete rather than a failed load.

Its `message` now also accepts null, because that is what the delete-error call
sites already had in hand and what the inline JSX happily rendered as nothing.

Left as they are: the prompt-validation dialog swaps variant between success
and error and carries a structured body, and the flow-files notice is a default
Alert — a warning, not an error. Neither is this shape.

No behaviour change. Verified by re-failing the providers and prompts queries
and confirming the same alert still renders and the page still recovers;
993 tests pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-17 18:44:15 +07:00
Dmitry Ng 9e0c93d0e9 Merge pull request #329 from mason5052/codex/issue-61-install-config-guide
docs: add installing and configuring guide for first deployment
2026-07-17 15:41:09 +04:00
Dmitry Ng 7bf8615b66 Merge pull request #328 from octo-patch/feature/upgrade-minimax-m3
feat: upgrade MiniMax default model to M3
2026-07-17 15:33:13 +04:00
Dmitry Ng d847d8634c Merge pull request #327 from mason5052/codex/issue-322-embedding-troubleshooting
docs: add embedding troubleshooting for stalled flows
2026-07-17 15:31:31 +04:00
Dmitry Ng ebfc88b93e Merge pull request #326 from mason5052/codex/issue-324-kubernetes-rfc
docs: add Kubernetes deployment compatibility RFC
2026-07-17 15:27:31 +04:00
Dmitry Ng 2fc0f31e70 Merge pull request #325 from mason5052/codex/issue-309-image-chooser-troubleshooting
docs: clarify "primary docker image" error is an LLM backend failure
2026-07-17 15:16:15 +04:00
Dmitry Ng 1ec1aef37f Merge pull request #274 from mason5052/codex/issue-249-macos-installer-warning
docs: add macOS installer warning guidance
2026-07-17 15:11:07 +04:00
Sergey KozyrenkoandClaude Opus 4.8 cada8ffbe8 fix(ui): tell the user when a page fails to load instead of showing "nothing here"
A backend that was down rendered as a pristine empty account: every dashboard
chart said "No data for this period" and every metric card showed 0, while the
templates and knowledges lists showed their "nothing here yet" empty states —
all indistinguishable from a genuinely empty account, with no toast, no banner
and no other hint that anything had failed.

None of the three pages read `error` from their queries. The templates and
knowledges providers destructured only `{data, loading}` and never exposed it,
and every dashboard query dropped it on the floor. A failed query leaves `data`
undefined, which the empty-state branch cannot tell apart from an empty result.

Expose `error` from the two providers and render a load-error state distinct
from the empty state: a full-page alert on the lists, a banner above the cards
on both dashboard tabs. The settings pages already did exactly this, so the
shared `DataLoadError` gives those call sites one shape instead of four copies.

Templates also gained the loading state it never had — its empty state used to
show while the very first fetch was still in flight.

Verified by failing each query at the network layer and re-running the check
that caught it: templates and knowledges now surface "Error loading ..." rather
than their empty state, and the dashboard shows the banner on both tabs against
a cold cache. Happy path unchanged; 993 tests pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-17 18:09:52 +07:00
Dmitry Ng 06f149246e Merge pull request #233 from salecharohit/feat/bedrock-config-path
Feat/bedrock config path
2026-07-17 15:08:06 +04:00
Sergey KozyrenkoandClaude Opus 4.8 9952f7d6b0 chore(frontend): let vite preview reach the API
The proxy was only declared under `server`, so `vite preview` served the
production build with no route to the backend: every /api/v1 call 404'd and
the built app could not get past the login screen.

That left the production bundle effectively untestable, which is where
chunking — and the bug that made every route download recharts — only ever
shows up; `vite dev` does not chunk at all.

Reuse the dev proxy for preview, on VITE_PORT+100 so it cannot collide with
the dev server. Verified: preview serves on 8100 and /api/v1/info returns 200
through the proxy.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-17 15:44:45 +07:00
Sergey KozyrenkoandClaude Opus 4.8 6a032c74db chore: ignore the installer's log.json
`cmd/installer/wizard/logger` opens log.json from its init(), so importing the
package is enough to create one in the process's working directory. Running
`go test ./cmd/installer/...` therefore drops a log.json into every package
directory it runs from — four of them were sitting untracked in the tree,
one step away from an accidental `git add -A`.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-17 15:44:43 +07:00
Sergey KozyrenkoandClaude Opus 4.8 fa370eacb4 perf(build): stop every route from downloading recharts and highlight.js
Loading any page — /login included — fetched the `markdown` and `charts`
chunks, ~198KB gzip that the page never used.

Vite 8 bundles with rolldown, where `manualChunks` is a compatibility shim
over code-splitting groups, and a group captures its modules' dependencies
as well as the modules themselves. So `charts` (recharts) swallowed clsx and
`markdown` (react-markdown) swallowed react/jsx-runtime — both of which every
component needs, which dragged the two chunks into the entry graph and onto
index.html's modulepreload list. Returning 'react-vendor' from manualChunks
for those modules changed nothing: the group that captured them as
dependencies won regardless of the order the branches were written in.

Use rolldown's own `codeSplitting.groups` instead and rank the shared modules
above the heavy libraries that depend on them.

/settings/account now fetches 305KB of JS rather than 502KB; /dashboard 378KB
rather than 474KB, still loading `charts` because it draws charts. Verified
against the production build served locally: 10 routes render, console clean,
charts intact, 993 tests pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-17 15:06:27 +07:00
Sergey KozyrenkoandClaude Opus 4.8 29300b4df9 fix(ui): let the list empty states centre themselves like the primitive intends
Empty declares `flex-1 … justify-center` (empty.tsx:9), but the list pages wrapped
it in a plain `flex flex-col`, so it collapsed to its natural height and hugged the
header while api-tokens — same primitive, same "nothing yet + CTA" shape — centred
in its `flex-1` wrapper. At 1920 the CTA jumped ~350px between the two pages.

The five wrappers on knowledges, templates and flows (loading + empty states) now
carry flex-1 like the eight that already did. SidebarInset is `min-h-svh flex-1
flex-col`, so the height is there to fill. Measured at 1920: knowledges and
templates now report the same 564 centre / 24px offset as api-tokens.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-17 12:56:46 +07:00
Sergey KozyrenkoandClaude Opus 4.8 d2489fd2c7 fix(sidebar): restore icon sizing the container cannot supply
The size-4 sweep stripped four icons the sweep had no right to touch, and they
rendered at lucide's default 24px: the avatar's UserIcon and the theme
switcher's Monitor/Sun/Moon in the sidebar user menu.

The sweep assumed every listed container sizes its icons at any depth. Only
Button/Toggle/CommandItem do, via [&_svg]. SidebarMenuButton and DropdownMenuItem
use [&>svg], which reaches a DIRECT child only — and these four sit deeper, inside
an AvatarFallback and inside TabsTrigger, so nothing sized them.

Found by measuring rendered icon width across every route with the menus open,
not by re-reading the selectors: the avatar icon was the only one a closed-menu
pass could see. Verified after: no icon inside a button or menu row renders over
16px except EmptyMedia's, which is meant to be large.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-17 11:24:25 +07:00
Sergey KozyrenkoandClaude Opus 4.8 9cbda709b6 refactor(ui): finish the Spinner migration, retire the Loader2 alias from JSX
The remaining 20 rendered Loader2 spinners carried a deliberate size or colour, so
the earlier pass left them. They convert cleanly after all: Loader2 is a lucide
alias of LoaderCircle (`LoaderCircle as Loader2` in lucide-react's d.ts) and that
is exactly what Spinner variant="circle" renders, while Circle merges an incoming
className over its built-in animate-spin. So each site keeps its size/colour class
and only drops the now-redundant animate-spin. Every rendered spinner in the app is
the Spinner primitive now.

flow-status-icon and flow-task-status-icon keep Loader2: there it is a value in a
Record<StatusType, { icon: LucideIcon }> map, not a rendered spinner, and Spinner
is a variant wrapper rather than a LucideIcon — it does not fit that slot.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-17 10:15:35 +07:00
Sergey KozyrenkoandClaude Opus 4.8 d4dabc2783 refactor(ui): adopt the Spinner primitive and drop redundant icon sizing
Two mechanical cleanups over the same files.

<Loader2 className="size-4 animate-spin"> and <Loader2 className="animate-spin">
appeared 28 times across 20 files while Spinner variant="circle" — the same
LoaderCircleIcon with animate-spin already baked in — was the idiom elsewhere.
Loader2 spinners with a deliberate size (size-3/5/6/10/16) or a colour are left
alone: Spinner sets no size of its own and would fall back to lucide's 24px.

Separately, 51 icons carried className="size-4" inside a Button, DropdownMenuItem
or AppHeaderAction, all of which already force [&_svg]:size-4 on descendants, so
the class was a no-op. Only those 51 are stripped — the sites picked by walking
each icon's real JSX ancestors through the TypeScript AST, because an indentation
heuristic mistakes multi-line opening tags for the parent. The 40 icons with no
forcing ancestor (Alert, TabsTrigger, AppHeaderTitle, a resize handle) keep their
size-4: without it they would render at lucide's 24px.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-17 09:36:20 +07:00
Sergey KozyrenkoandClaude Opus 4.8 5d15be2f4f refactor(flows): build the attachment chip's remove control on Button
The remove X was a raw button. It is a ghost Button now, sized to the chip's own
26px so the whole chip height is a hit target instead of the bare 14px glyph.

Negative margins keep the geometry identical: -my-[5px] and -ml-1 -mr-1.5 shrink
the margin box back to the 14px footprint the raw icon had, and [&_svg]:size-3.5
holds the X at 14px against Button's [&_svg]:size-4 descendant rule, which would
otherwise win on specificity. Measured against the old markup on the real
stylesheet: chip 26px and 107.3px wide, X 14px, X 21px from the chip's right edge
— all unchanged.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-17 09:35:32 +07:00
Sergey KozyrenkoandClaude Opus 4.8 733f0390e9 fix(settings): build the per-agent Test control on the Button primitive
The Test affordance in each agent accordion header was a raw span reimplementing
outline-button chrome by hand (rounded border px-2 py-1 + hover:bg-accent + a
manual disabled style). It now composes Button asChild variant="outline" size="xs"
over that span, so it inherits the same outline chrome as every other action
button.

It stays a span, not a button: AccordionTrigger already renders a button and a
button-in-button is invalid HTML — verified live, zero nested buttons in the DOM.
The disabled styling stays hand-rolled because a span can't be :disabled, and the
onClick keeps its stopPropagation so clicking Test still doesn't toggle the row.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-17 02:53:39 +07:00
Sergey KozyrenkoandClaude Opus 4.8 1adcbec0f9 refactor(app): unify the header save action on AppHeaderAction with a loading prop
The four detail-page saves rendered two ways: knowledge as AppHeaderAction (a
primary CTA that collapses to an icon on mobile), the other three as a secondary
FormSubmitButton. FormSubmitButton buys nothing here — all three sit in the
header, outside the form's FormProvider, so its useFormContext read returns null
and they already submit via form= + a manual loading prop. Its real value is the
in-<Form> subscription, which its 8 dialog/auth consumers keep using untouched.

AppHeaderAction gains an optional loading (icon->spinner + disable); the three
header saves become AppHeaderAction like knowledge, so all four are now the same
primary CTA that collapses to an icon-only button (aria-label preserved) below
md. type="submit" is explicit because Button defaults type to "button". Verified
at 480px: label hidden, 32px icon button, aria-label "Create"; at 1440: primary
fill, label shown.

Researched the alternatives first: React 19 useFormStatus can't read a
form=-associated button (react.dev; facebook/react#27980) and targets native
form actions not RHF; and a Radix Slot asChild compose throws on FormSubmitButton's
two-child array and can't inject the spinner past child-wins prop merging.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-17 02:50:53 +07:00
Sergey KozyrenkoandClaude Opus 4.8 672851ef32 fix(templates,flows): label the template title, align cosmetics across detail forms
Template title was the only single-line field with neither a FormLabel nor a
FormMessage, so "Title is required" could never surface and the field was
unlabeled while knowledge/provider label theirs. It now has both — verified live:
submitting empty shows "Title is required".

Also: descriptive placeholders on the template title and editor (matching the
sentence-style placeholders elsewhere), the Rename dropdown icon to size-4 (its
siblings are size-4), and the new-flow intro to the shared block (h2 + gap-2
instead of h1 + mt-2) so every create/edit intro is identical.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-17 02:37:59 +07:00
Sergey KozyrenkoandClaude Opus 4.8 0585d01bad fix(settings): match the provider combobox triggers to the select chrome
The provider Type combobox rendered as a Button outline — opaque bg-background,
a ChevronsUpDown icon and font-medium text — while every select on the knowledge
form is a transparent-bg SelectTrigger with a single ChevronDown. Side by side
the Type field read as a different control.

The combobox trigger now carries bg-transparent, px-3, font-normal and a
ChevronDown size-4, matching SelectTrigger; the model combobox's addon chevron
follows suit. Measured against the canon at 1440: transparent bg, chevron-down
16px opacity .5, h-9, px-3, weight 400 — identical.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-17 02:33:50 +07:00
Sergey KozyrenkoandClaude Opus 4.8 b1f77fa7dc fix(settings,templates): contain popover scroll, show the variable count on desktop
The variables and presets popovers scrolled the page once their own scroll hit
the end — overscroll-behavior defaulted to auto and a non-modal popover doesn't
lock the body. overscroll-contain keeps the momentum inside. Reproduced at
375x640: wheeling past the popover's end moved the body 0 -> 204px; with contain
it stays at 0.

The prompt variables card now shows the variable count on desktop too, matching
the preset-count badge the template card already carries.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-17 00:44:24 +07:00
Sergey KozyrenkoandClaude Opus 4.8 679438451f feat(templates): collapse the presets panel into a popover on mobile
Below the split the presets card was a 599px block that sat under the fold, past
the editor — on the new-template form the editor is empty and the presets are how
you fill it, so the primary tool was hidden behind a scroll.

The panel now mirrors the prompt variables one: on desktop it stays the card in
the split; below 1280 its header becomes a full-width secondary trigger with the
preset count, opening a non-modal popover that holds the same preset list. The
list is shared by both wrappers; only the wrapper differs. In the stack the
trigger takes the presets' desktop slot — after the title, before the editor.

Applying a preset from the popover closes it (the popover is controlled), then
either fills the form or raises the existing replace-confirm dialog when the form
already has content — verified live at 390: fill, replace-confirm, and expanding a
preset preview inside the popover all work, and the desktop split is unchanged.

presetsList drops its useMemo to take an onApplied callback; typing does not
re-render the form (FormField isolates it), so the 11 collapsibles are not on the
keystroke path — confirmed by zero slow input events while typing on desktop with
all of them mounted.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-17 00:11:08 +07:00
Sergey KozyrenkoandClaude Opus 4.8 a38e4d503c fix(settings): restore keyboard access to the variables popover
Below the split, preventing the popover's open-autofocus left focus on the
trigger while the content sat in a body portal, so the first Tab landed in the
editor and the second dismissed the popover: the chips could not be reached by
keyboard at all. Before the popover existed they were inline tabbable badges, so
this was a WCAG 2.1.1 regression.

Both autofocus handlers are gone. They were written to protect the editor caret,
but ProseMirror keeps its selection across DOM blur, so they were never needed —
verified live at 390: opening now focuses the first chip, Escape returns focus to
the trigger, and clicking a variable still inserts at the caret the user left,
with the editor focused and the popover closed.

Also stop the shared chip cloud painting bg-background over the popover: dark
--background matches the page behind it, which flattened the popover to a
borderline. The two-tone well is the desktop card's business, so the fill moved
onto its wrapper, where it still contrasts bg-card.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-16 23:02:24 +07:00
Sergey KozyrenkoandClaude Opus 4.8 d6af153689 style(frontend): restore prettier formatting on the Empty-migration pages
`pnpm run prettier` is a required CI step and it exits 1 on these five files at
HEAD while passing on them at 001c6c0, so the branch is currently red. Formatting
only — no logic touched.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-16 22:53:01 +07:00
Sergey KozyrenkoandClaude Opus 4.8 6f21d90904 style(settings): outline the variables count badge and size it to 20px
The badge default height is 22px — text-xs' 16px line box, py-0.5 and a 1px
border — which crowds the 32px trigger. h-5 pins it to 20px; border-box leaves
18px of content for the 16px line box, so nothing clips.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-16 22:21:46 +07:00
Sergey KozyrenkoandClaude Opus 4.8 cbfad0853c fix(settings): contrast the variables count badge, scope the tab overrides to the split
The count badge sat on a bg-secondary button, where every neutral surface token
is within 1.08–1.23 contrast of it: secondary painted the pill invisible and
outline drew its border in --border, at 1.18. Only --primary separates (2.76), so
the badge is default.

The tab overrides exist because the desktop panel sits on its own surface. Below
the split they fought the shadcn defaults, so they are xl:-scoped now — the same
1280 the layout branches on. Stacked widths get bg-muted with a bg-background
active tab again; 1280+ keeps bg-background with a bg-card active tab.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-16 22:05:06 +07:00
Sergey KozyrenkoandClaude Opus 4.8 fae61b2607 feat(settings): show the variables count on the narrow-width trigger
The trigger is a compact secondary button carrying just its label and, on the
right, the variable count — same count-badge shape the sheet and template
headers already use.

The badge is outline, not secondary: a secondary badge paints bg-secondary onto
a bg-secondary button, which renders the count as bare text.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-16 21:57:37 +07:00
Sergey KozyrenkoandClaude Opus 4.8 4c1ee3177e fix(settings): make the variables header itself the narrow-width trigger
The header and its hint were rendered twice below the split breakpoint: once as
the trigger label and again at the top of the popover it opened.

The header belongs to the wrapper, not to the shared part. On desktop it stays
the card header; on narrow widths it becomes the trigger, and the popover now
carries only the chips. Title and hint move to constants so the two wrappers
cannot drift apart.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-16 21:51:27 +07:00
Sergey KozyrenkoandClaude Opus 4.8 f89eacb990 refactor(settings): give Badge asChild, let the variables panel own its breakpoint
Three follow-ups to the variables palette.

The chips composed badgeVariants onto a raw <button>, going around the primitive,
because Badge renders a div. Badge now accepts asChild through the same Slot
switch button.tsx already uses, so a chip is <Badge asChild><button>: the badge
keeps owning the styling, the button keeps native semantics, and the hand-rolled
role/tabIndex/Enter-Space handler stays gone. className has to stay on Badge —
Slot concatenates classes, so only cn() resolves font-normal against
badgeVariants' font-semibold.

Variables reads useBreakpoint itself rather than taking isDesktop from the page.
Every other consumer here does that, sidebar.tsx included, and it keeps the panel
droppable into the next page that needs one.

The narrow-width trigger is a full-width labelled button now. It carries no
chevron and no count badge: those, not the width, are what make a control read as
a value select.

Also size the popover by --radix-popover-trigger-width, the way autocomplete.tsx
does. It was 100vw wide and spilled across the sidebar between 768 and 1280.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-16 21:40:32 +07:00
Sergey KozyrenkoandClaude Opus 4.8 fed1a020c6 feat(settings): collapse the prompt variables panel into a popover on mobile
In the stacked layout the "Available variables" cloud sat between the tabs and
the editor, pushing ~530px of chips ahead of the content it annotates. The panel
now keeps its slot and its desktop rendering, and below the split breakpoint the
same cloud moves behind a { } trigger, leaving the editor at the top.

The cloud itself is shared by both wrappers; only the wrapper differs (card vs
non-modal popover). The popover must not trap focus: insert and cycle act on the
editor's stored selection, and cycling only helps if its highlight stays visible.

Chips are real buttons now — they were divs with role=button and a hand-rolled
Enter/Space handler that the native element provides for free.

Verified live at 500px: opening keeps the caret, clicking a used variable selects
the next occurrence in view, the popover closes as the editor takes focus back,
and the desktop split is unchanged.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-16 21:08:46 +07:00
Sergey KozyrenkoandClaude Opus 4.8 a66ac97a9b refactor(prompts): render the prompt meta and variables as one panel block
On narrow viewports the editor was rendered between the prompt meta/tabs
and the "Available variables" panel, splitting one logical block in two and
forcing a different composition per breakpoint. Merge them into a single
panel block that the desktop split and the mobile stack both render as a
unit, so the variables stay attached to the tabs they belong to.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-16 18:29:14 +07:00
Sergey KozyrenkoandClaude Opus 4.8 a3dcd053bc refactor(ui): replace custom StatusCard with the shadcn Empty primitive
Consolidate every empty / loading / error / not-found / error-boundary
state off the bespoke StatusCard onto the canonical shadcn Empty (already
used by DataTable) and delete components/ui/status-card.tsx. Empty renders
borderless and centered, so the wide-viewport "letterbox" look is fixed at
the root instead of capping a solid card.

Also in this pass:
- DataTable: truncate column headers so plain-string headers in narrow
  fixed-size columns (e.g. "System Prompt") stop wrapping to two lines.
- Settings > Providers / API Tokens: move the Create action into the page
  header (icon-collapses on mobile) and the API-token Playground/Swagger
  links into a header overflow menu; drop the cramped description row that
  needed the earlier truncate/flex-wrap workarounds. Those links use a
  relative href since the API base path is root-relative.
- Settings > Prompts: drop the fixed size on the Name column of both tables
  so it flexes to fill (matching Providers) and truncates.
- Settings > Account: keep "Member since" on one line at mobile widths
  (min-w-0 + truncate, badge shrink-0).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-16 17:48:22 +07:00
rramprakash bb44c9961d fix(firecrawl): omit sources from search request
Verified against the live /v2/search API: the response envelope only ever
populates data.web for this tool, and sources defaults to ["web"] when
omitted. The sources field carries a string-vs-object shape ambiguity across
the API/SDK/MCP layers (the Firecrawl MCP rejects string sources outright),
so dropping it removes a needless compatibility risk without changing
behaviour.
2026-07-16 12:53:11 +05:30
rramprakash 4245be118a fix(migration): remap firecrawl rows in the down migration
The down migration narrows the searchengine_type enum by casting the
engine column to a new enum that no longer contains 'firecrawl'. Any row
logged with 'firecrawl' would make that cast fail, so a rollback errors out
once the engine has been used. Remap those rows to 'tavily' before the cast
so the down migration is safe on real data.
2026-07-16 12:53:11 +05:30
rramprakash b32dde8f01 fix(firecrawl): thread user query into summarizer prompt
The summarizer prompt asked the model to 'directly answer the user query'
but never rendered the query — Firecrawl's /v2/search response, unlike
Tavily's, doesn't echo the query back, so it was dropped when adapting the
prompt. Every summarized result (the common path, since scrapeOptions
requests markdown) was therefore a generic page summary instead of a
query-focused one.

Thread the query through search -> parseHTTPResponse -> buildFirecrawlResult
-> getSummarizePrompt and restore the USER QUERY line, matching Tavily.
Add a test asserting the query is present in the prompt.
2026-07-16 12:53:11 +05:30
rramprakash 7ffa30ddc9 address review: bound & align firecrawl summarizer prompt, fix docs
- Summarizer prompt now uses one-based source IDs (aligned with the numbered
  links) and the metadata-fallback title/URL, and truncates each document's
  markdown to the same per-result limit as the non-summarized path, so an
  oversized or hostile page can't blow up the prompt.
- Reword tool description, searcher prompt and docs to say 'main-content
  markdown' since the scrape uses onlyMainContent=true.
- config.md example now uses the real NewFirecrawlTool(...) constructor,
  matching the searxng/sploitus entries.
2026-07-16 12:53:11 +05:30
rramprakash 3f68960d98 feat(tools): add Firecrawl web search provider
Add Firecrawl as a network search provider alongside Tavily, Perplexity,
Traversaal, SearXNG and the others. Firecrawl's /v2/search endpoint combines
web search with page scraping, returning full-page markdown content for each
result, which the searcher agent summarizes like the other content-rich
engines.

- New firecrawl tool mirrors the Tavily provider layer-for-layer: registry
  definition, tool-type mapping, factory wiring in both tool builders, and
  ftester executor/args/mocks support.
- Configurable endpoint: FIRECRAWL_API_KEY plus an optional FIRECRAWL_API_URL
  (default https://api.firecrawl.dev) so self-hosted Firecrawl instances work.
- Adds 'firecrawl' to the searchengine_type enum (goose migration + models)
  and the search-log server model so searches are recorded per engine.
- Installer wizard, .env.example, docker-compose, prompts and docs updated.

The tool is only registered when FIRECRAWL_API_KEY is set, so existing
deployments are unaffected.
2026-07-16 12:53:11 +05:30
Sergey KozyrenkoandClaude Opus 4.8 001c6c0d9d feat(settings): render three-state reasoning control driven by capability
Add an Off option to the per-agent Reasoning Mode control, gated on the model's
cannotDisable capability so it appears only where a disable actually takes effect;
relax the adaptive-only lock for disablable models; disable effort/max-tokens when
Off. Reconcile a stale Off when the selected model can't disable (e.g. after typing
a custom model name) so it cannot silently persist. Map the off mode through the
form->GraphQL conversion.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-13 19:51:03 +07:00
Sergey KozyrenkoandClaude Opus 4.8 2853c97549 feat(reasoning): add three-state On/Off/Default reasoning control
Add an explicit reasoning Off to the per-agent config, backed by the langchaingo
tri-state API. Off emits llms.WithReasoningDisabled() (the provider disable wire)
via BuildOptions, and UsesAdaptiveThinking is guarded so Off overrides the
adaptive-only auto-adaptive.

Per-model capability is derived at runtime from llms.ReasoningSupportFor and
surfaced through GraphQL ModelReasoningInfo, so the UI only offers Off where it
actually disables: cannotDisable reports when Off would be rejected (always-on
models) OR a silent no-op (an unclassified default-on model whose disable wire is
omitted), and capability is surfaced for any thinking-capable model (e.g. Gemini,
which declares thinking without a reasoning block). A new
ProviderType.ReasoningProvider() supplies the provider to the resolver.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-13 19:50:43 +07:00
Sergey KozyrenkoandClaude Opus 4.8 ffbbabb517 fix(docker,flows): surface truncated/systemerr exec streams, bound ftester drain, tidy failure logging
- demuxExecStdout errors on a header cut short mid-frame (was a silent EOF that
  dropped the tail) and surfaces a docker systemerr frame instead of discarding it.
- ftester drains telemetry on exit through the bounded observer.Drain instead of
  two unbounded ForceFlush calls, so an unreachable collector can't hang it at exit.
- container-listing failures are sorted for a deterministic skipped-entries preview,
  logged per-entry at Debug (the detail is already in the response and the endpoint
  is hit on every navigation) with names quoted so control bytes in a hostile
  filename can't inject into a log line; corrected the stat-failure comment
  (a dangling symlink lstats fine, it doesn't fail).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-13 00:06:21 +07:00
Sergey KozyrenkoandClaude Opus 4.8 7cd22ccbc9 test(docker,flows): cover the listing cap paths, bound the container-list path count
The truncation slice and the demux stdout byte-cap had no docker-layer tests —
only the handler's Truncated wiring was exercised through the fake, so a
mis-slice or a dropped cap would have gone unnoticed. Extract find-output
parsing into a pure parseFindEntries and take the byte cap as a demuxExecStdout
parameter, then unit-test both boundaries (at cap / cap+1 / over-limit stream).

Also bound how many paths one container-files request may list
(maxContainerListPaths), so the per-path entry cap can't be multiplied by an
attacker-chosen path count into a large fan-out or response body.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-12 23:22:33 +07:00
Sergey KozyrenkoandClaude Opus 4.8 18234f05a3 docs(docker): refresh the container-listing doc, drop a stale telemetry test comment
The container-listing section still described the removed `ls -1` parse,
`pkg/queue`, and the old `[]container.PathStat` return. Update it to the current
`find -print0` + errgroup fan-out returning `ContainerDirListing{Files, Failures,
Truncated}`. Also remove the stale `WithBlock`/`DefaultDialTimeout` paragraph left
above the non-blocking `grpc.NewClient` test — its own next paragraph already
contradicted it.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-12 22:45:34 +07:00
Sergey KozyrenkoandClaude Opus 4.8 7b67b1c0ea fix(flows): return partial container listings instead of failing; stop the refetch skeleton flash
Container-listing polish on top of the partial-success work:

- A directory whose entries all fail to stat no longer 500s. The find exec
  already proved the container alive, so ListContainerDir returns the readable
  entries (possibly none) plus the per-entry failures, and the handler serves a
  200 partial listing; only a cancelled request or a dir that can't be listed at
  all still errors.

- Over the entry cap, list the first page and set a Truncated flag rather than
  erroring with end-user copy from the docker layer. The flag flows through to
  the Pull dialog, which now warns the user the directory was truncated instead
  of silently showing a subset.

- The Pull dialog no longer flashes a skeleton on an in-place refetch (Refresh,
  or after a Pull): the listing hook clears its rows only when the path actually
  changes, so a same-path reload keeps the current rows under the loading guard.

Tests: an all-entries-failed listing returns 200 with the failures; the
Truncated flag surfaces in the response. Swagger regenerated for the new field.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-12 22:38:17 +07:00
Sergey KozyrenkoandClaude Opus 4.8 2c524faea9 fix(observability,flows): drain telemetry sinks in parallel, stop leaking docker errors, dedup listing failures
Three defects on the shutdown and container-listing paths:

- Telemetry drain ran the langfuse and otel sinks serially under one deadline.
  langfuse's ForceFlush/Shutdown ignore the caller ctx and block on their own
  timeout, so a langfuse outage burned the whole budget and the healthy otel
  sink's final batch was never flushed. Add observer.Drain, which flushes then
  shuts down each sink in its own goroutine bounded by the deadline; main uses
  it, retiring the inline flush-then-shutdown dance.

- The partial-success listing put the raw stat/list error into the 200 body's
  Failures[].Message, exposing docker-layer detail (container ids, the daemon
  address) that response.Error only reveals under develop mode. Send a generic
  message to the client and keep the raw text dev-gated, logged server-side.

- A path read successfully by one query could also appear in Failures when
  another query failed on it, order-dependent. Reconcile at assembly: drop any
  failure whose path was read successfully, so no path is in both arrays.

Also bound the exec stdout buffered before parsing so a compromised sandbox
can't stream unbounded output into memory.

Tests: Drain delivers a healthy otel sink while a langfuse sink blocks and
returns within its deadline; the listing failure message is dev-gated; a path
never lands in both Files and Failures. Live: unreachable collector -> shutdown
stays bounded (~5s) and exits cleanly.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-12 22:24:02 +07:00
Sergey KozyrenkoandClaude Opus 4.8 bc8714db6e fix(observability): flush telemetry on graceful shutdown, drain every sink
The graceful-shutdown branch only logged "cleaning up resources" and exited
without flushing telemetry, so the last buffered batch was dropped on every
SIGTERM. Drain it, with three corrections:

- main: flush then shut down the observer on shutdown, bounded by a 5s
  deadline in a goroutine so an unreachable collector can't stall exit.
  Flush must precede Shutdown because the langfuse observer's Shutdown
  cancels its context without flushing; its final batch drains only via
  ForceFlush while the context is still live.
- observer Flush/Shutdown: drain both the langfuse and otel sinks and join
  their errors instead of returning after the first, which skipped the
  second sink entirely when both were configured.
- telemetryClient Flush/Shutdown: attempt all three providers and always
  close the grpc connection, joining errors, so a stalled provider flush
  no longer skips the rest or leaks the connection.

Tests: the langfuse observer test proves Shutdown drops the buffered batch
while ForceFlush drains it to the sink; observer-level tests prove both
sinks drain and errors aggregate. Live: with an unreachable collector,
shutdown stays bounded (~5s) and exits cleanly instead of stalling ~10s.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-12 17:30:31 +07:00
Sergey KozyrenkoandClaude Opus 4.8 c0660b8398 fix(observability): connect the telemetry collector lazily, tear down cleanly
The startup dial used grpc.WithBlock with a 10s timeout, so a set-but-
unreachable collector stalled main() for up to 10s, and once that dial failed
the client was nil forever — a collector that came up later never connected
without a restart. Switch to grpc.NewClient (non-blocking): startup never
stalls and gRPC re-establishes the connection in the background on its own.
Also build all three exporters before any provider, so the exporter-error
cleanup (closing the connection) happens before any batch/reader goroutine
starts and can't leak one. Drops the deprecated WithBlock/WithReturnConnectionError.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-12 16:45:41 +07:00
Sergey KozyrenkoandClaude Opus 4.8 345b91e4c1 docs(swagger): regenerate for the container-files Failures field
ContainerFiles gained a Failures list when the container listing switched to
partial-success; regenerate the Swagger docs (swag v1.8.7, the pinned version)
so generated clients see the new field.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-12 16:37:18 +07:00
Sergey KozyrenkoandClaude Opus 4.8 a306b156a1 chore: gitignore backend/vendor, drop stale pkg/queue doc row, self-contained test messages
- Ignore the local `backend/vendor/` tree (187 MB, present only for the
  vendored-fork build) so it can't be accidentally staged.
- Remove the architecture-table row for `pkg/queue/`, which was deleted when
  the container stat fan-out moved to errgroup.
- Drop the internal "H4" report-id labels from the telemetry test — the
  sentences already say what they guard.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-12 16:37:17 +07:00
Sergey KozyrenkoandClaude Opus 4.8 780c2a722e fix(docker): drop the TTY from the dir listing to keep newline filenames intact
find -print0 already delimits with NUL, but the exec still ran under a TTY,
whose onlcr translation rewrites every \n in the stream to \r\n — including a
\n that is part of a filename — so a file literally named with a newline was
stat'd under the mangled name and reported unreadable. Run the exec without a
TTY and demux the resulting multiplexed stdout/stderr stream by hand (no new
dependency), so filename bytes reach the parser untouched.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-12 16:20:36 +07:00
Sergey KozyrenkoandClaude Opus 4.8 1535a7a700 fix(flows): don't show a previous directory's listing under a new path
Navigating to a new directory in the Pull dialog kept showing the old files
and old "N entries could not be read" banner until the response landed (the
hook never cleared its data at fetch start), and when every entry failed the
per-entry messages were shown nowhere. Clear files/failures when a fetch
starts, and render the first few failure messages in the all-unreadable
empty state.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-12 16:12:40 +07:00
Sergey KozyrenkoandClaude Opus 4.8 93d36c9827 fix(flows): keep serving readable paths when one container path fails
The multi-path container listing still fail-fasted: a single bad top-level
path (nonexistent, not a directory, list failed) returned HTTP 500 and
blanked every path that had already listed. Record each such path as a
failure and keep going so the readable paths are still returned; only a
cancelled request aborts, and if every path fails at the directory level the
request is failed as a whole. Also drop a per-entry failure whose path was
already read successfully by an overlapping query.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-12 16:12:40 +07:00
Sergey KozyrenkoandClaude Opus 4.8 ac9a16517a fix(docker): list container dirs with find -print0, not ls parsing
Parsing `ls -1` output was unsafe: under the TTY the exec allocates, GNU
coreutils shell-quotes names — so a readable file with a space, quote or
non-ASCII byte was stat'd with the quotes and reported unreadable — and
busybox wraps every entry in ANSI colour codes, so on an alpine/busybox
image the whole listing came back unreadable. Switch to `find -maxdepth 1
-print0`: literal bytes, portable across GNU and busybox, and the NUL
delimiter survives filenames containing newlines. Cap the entry count so a
directory with hundreds of thousands of files can't fan out into that many
Docker API calls, and classify a cancelled request or an all-entries-failed
listing as a directory-level error instead of a misleading empty 200.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-12 16:12:38 +07:00
Sergey KozyrenkoandClaude Opus 4.8 56e8035b8a feat(flows): surface partial container listings in the Pull dialog
The container file endpoint now returns HTTP 200 with the readable entries
plus a Failures list when some entries can't be stat'd, instead of failing
the whole request. Plumb those failures through useFlowContainerFiles and
show a non-blocking warning banner above the readable files ("N entries
could not be read"), reserving the full error empty-state for a true
listing failure. When nothing is readable, the empty-state says so rather
than "Directory is empty".

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-12 13:38:24 +07:00
Sergey KozyrenkoandClaude Opus 4.8 1300f60a2b feat(docker): partial-success container listing instead of fail-fast
A single unreadable directory entry (dangling symlink, a file removed
between ls and stat, a transient /proc entry) used to fail the whole
listing with HTTP 500, blanking the file browser and discarding every
readable sibling. The frontend already expects /proc/sys to not fail
spuriously, but the backend did the opposite.

ListContainerDir now returns a ContainerDirListing{Files, Failures}: per-
entry stat errors no longer abort the batch. GetFlowContainerFiles serves
the readable entries as HTTP 200, carries the failures back in a new
ContainerFiles.Failures field, and logs each skipped entry (capped) plus a
degradation summary. Directory-level faults (not a dir, ls failed, container
gone) still return 500 — there is no partial to show. statContainerEntries
returns successes + failures instead of the lowest-index error.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-12 13:32:48 +07:00
Sergey KozyrenkoandClaude Opus 4.8 8212802c84 fix(docker): clamp non-positive worker count in the stat fan-out
The deleted queue normalized workers<=0 to a default; the errgroup helper
passed the count straight to SetLimit, where 0 deadlocks the first Go() on an
unbuffered semaphore and a negative value disables the bound entirely. The
sole caller hardcodes 20 so this was latent, but clamp it back so a future
config-driven count can't hang the listing or flood the Docker daemon.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-12 03:03:57 +07:00
Sergey KozyrenkoandClaude Opus 4.8 40eeea93c0 refactor(docker): replace the custom queue with a bounded errgroup fan-out
ListContainerDir was the only consumer of pkg/queue and discarded its ordered
delivery (the caller dedups and re-sorts). Replace the fan-out with a small
errgroup helper — SetLimit keeps the same 20-way bound on concurrent stats
against the Docker daemon, the caller's context propagates into each call,
results stay in input order, and the lowest-index failure is surfaced
deterministically — then delete pkg/queue. The helper was verified byte-
identical to the previous queue implementation across 600 randomized directory
shapes (sizes, failure positions, out-of-order completion) before removal.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-12 02:05:24 +07:00
Sergey KozyrenkoandClaude Opus 4.8 d44a33f5dd test(observability): cover the telemetry success path
Adds a fake OTLP collector so NewTelemetryClient can be exercised against a
reachable endpoint: it builds all three providers and both ForceFlush and
Shutdown export and tear down without error. Previously only the
not-configured and unreachable-dial paths were covered.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-11 10:02:58 +07:00
Sergey KozyrenkoandClaude Opus 4.8 745c8ae6d6 test(queue): cover the default-workers, nil-process, and Instance paths
Adds scenarios for a non-positive worker count (must fall back to the
default, else nothing drains the queue and delivery hangs), a nil process
function (logs and drops each item without panicking), and a stable
instance id. Brings queue.go to full statement coverage and kills the
mutants that previously survived on the workers<=0 fallback.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-11 10:02:56 +07:00
Sergey KozyrenkoandClaude Opus 4.8 d49e740821 test(observability): cover dial-timeout + ErrNotConfigured; close conn on exporter error
Unit coverage for NewTelemetryClient: an unset OTEL_HOST yields ErrNotConfigured,
and an unreachable collector returns within the dial timeout instead of hanging
(a TCP-accepting, silent listener drives the WithBlock path).

Also close the grpc.ClientConn on the exporter-creation error paths — a
successful dial followed by a failed exporter New() previously leaked it.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-11 09:09:38 +07:00
Sergey KozyrenkoandClaude Opus 4.8 62a1445d32 refactor(queue): drop the running-context for a flag; reject restart-without-stop
The two-context design in ddd3916 was correct but fragile: the field named
`ctx` was the liveness signal goroutines must NOT bail on, while the real
cancellation signal was `stopCtx`. That inversion is the exact trap that
produced the earlier happy-path regression (bailing on `ctx`, which a normal
input-close cancels, dropped in-flight results). It also left a latent
restart-without-Stop hazard: a second Start() after input-close orphaned the old
stopCtx and shared wg, deadlocking a later Stop() (with a data race).

Collapse `ctx` into a plain `running` bool (it was only ever read via .Err(),
never awaited), keep `stopCtx` as the single cancellation signal, and guard
Start() on stopCtx so a restart requires a prior Stop() — removing both the
naming trap and the restart hazard.

Comprehensive tests (queue_scenarios_test.go): boundary-N full delivery,
contiguous-prefix-on-abandon, a randomized prefix-invariant fuzz, goroutine-leak,
restart-reject, process-error, double-stop, Running() transitions. The happy-path
tests hang on the pre-rework code and pass here (side-by-side under -race). Live:
a flow's non-empty container dirs of 1/40/100/500 files each deliver every entry;
the error path returns 500 without hanging.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-11 09:09:36 +07:00
Sergey KozyrenkoandClaude Opus 4.8 ddd3916e9c fix(queue): only hard-stop workers on Stop(), not on normal input-close
The previous fix (97e5730) had workers and the reader bail on q.ctx, but the
reader also cancels q.ctx on a normal input-close — so the ListContainerDir
happy path regressed: after input closed (buffer names, close, read all N),
workers dropped still-undelivered results and the consumer hung waiting for the
last one. Any non-empty container directory that didn't error early hung the
file-manager request.

Split the signals: q.ctx still tracks "running" (cancelled by input-close or
Stop), and a new q.stopCtx is cancelled only by Stop(). Workers and the reader
bail on q.stopCtx, so a normal input-close drains and delivers every result
while a hard Stop() still unblocks a consumer that abandoned output. Stop()'s
already-stopped guard now checks q.stopCtx (input-close alone must not
short-circuit it, or blocked workers leak).

Tests: DeliversEveryResultAfterInputClose (hangs on the old fix, verified
side-by-side under -race) + StopHardStopsAfterInputClose; deadlock + ordering
still green under -race.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-11 00:02:51 +07:00
Sergey KozyrenkoandClaude Opus 4.8 d6fa58e5d4 fix(observability): don't let an unreachable telemetry collector down the app
A set-but-unreachable OTEL collector hung startup: NewTelemetryClient dialed
with grpc.WithBlock() and no timeout on the deadline-free signal context, so
the process blocked forever before it ever served. And a non-ErrNotConfigured
init error from either observability client was log.Fatalf, killing the
process. Both let an OPTIONAL integration take the whole app down.

Bound the dial with a 10s timeout, and on init failure degrade to a no-op
observer with a logged warning instead of exiting. Verified live: a bad
OTEL_HOST that hung startup indefinitely now boots in ~14s with a warning and
runs a full flow; a reachable collector still boots in ~4s with no warning.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 23:20:43 +07:00
Sergey KozyrenkoandClaude Opus 4.8 97e5730a53 fix(queue): don't deadlock Stop() when the consumer stops reading output
ListContainerDir aborts on the first stat error and stops reading the queue's
output channel, leaving workers blocked on the unbuffered `q.output <- result`
send and the reader blocked on a full `q.queue`; Stop() -> wg.Wait() then hung
forever. Select every pipeline send/wait on q.ctx so a stopped queue unwinds.
On stop a worker returns without msg.cancel(), so later workers also bail via
q.ctx and output ends at a contiguous prefix instead of developing gaps.

Regression test drives the exact hang (unread output -> Stop must return),
verified with -race.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 21:29:07 +07:00
Sergey KozyrenkoandClaude Opus 4.8 9876c13ea8 docs(providers): restore the DeepSeek legacy reasoning-format contract
The openai-compat consolidation dropped the comment warning that DeepSeek needs
the legacy top-level "reasoning_effort" string form; without it a maintainer
could add openai.WithModernReasoningFormat() to the shared opts and silently
break DeepSeek thinking mode. Restore it at the shared opts choke point.

Also fix two stale pointers: glm/qwen config.yml cited
WithPreserveReasoningContent() "in glm.go/qwen.go", but it moved to
openaicompat.go during that same consolidation.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 17:02:21 +07:00
Sergey KozyrenkoandClaude Opus 4.8 a87ac2db18 test(api-tokens): cover the token-name length cap
Export tokenNameSchema and pin the 100-character boundary (100 accepted, 101
rejected) plus its trim/default behavior.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 16:34:05 +07:00
Sergey KozyrenkoandClaude Opus 4.8 f5f7974826 test(validation): cover REST prompt validation and knowledge length limits
- prompts_test.go: PatchPrompt rejects a syntax error, an undeclared variable,
  and a whitespace-only template over REST (the path a raw client hits when the
  UI is bypassed) and does not persist them; valid templates still create/update.
- validation_test.go: validateKnowledgeFieldLengths accepts each field at its
  max length and rejects one character over.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 16:34:04 +07:00
Sergey KozyrenkoandClaude Opus 4.8 72da224033 feat(prompts): validate template syntax on the REST update endpoint
The GraphQL createPrompt/updatePrompt mutations run validator.ValidatePrompt
(Go text/template parse + declared-variable check + trial render), but the
REST PUT /prompts/:type handler only checked the field was present, so a
prompt with a syntax error or an undeclared variable could be stored over
REST and later break rendering. Mirror the GraphQL check in PatchPrompt.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 16:01:36 +07:00
Sergey KozyrenkoandClaude Opus 4.8 f92aafb09a fix(api-tokens): align token-name length cap with the backend (100)
The create/edit form allowed 255 characters, but the backend caps token
names at 100 — a longer name cleared client validation and was rejected on
save. Lower the zod cap to 100 to match.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 15:44:20 +07:00
Sergey KozyrenkoandClaude Opus 4.8 0cf85ef029 feat(graphql): validate knowledge and API-token mutation inputs
The REST handlers reject empty or oversized knowledge fields and over-long
API-token names through their request-model validate tags, but the GraphQL
mutations — the path the web UI uses — accepted them unchecked, so the same
entity could be stored past its documented limits depending on the caller.

Mirror the REST caps at the resolver boundary:
- createKnowledgeDocument / updateKnowledgeDocument: require content (and
  question on create), and cap content/question/description/codeLang lengths.
- createAPIToken / updateAPIToken: cap the token-name length.

Limits are kept in sync with server/models via mirror comments.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 15:44:19 +07:00
Sergey KozyrenkoandClaude Opus 4.8 bcef80de99 fix(graph): reject empty flow title, flow input, and assistant input
The renameFlow / putUserInput / callAssistant GraphQL resolvers passed the
title/input straight to the controller with no non-empty check, while the
equivalent REST handlers reject them with 400. An empty flow title in
particular then fails the Flow model's `required` invariant and breaks the
REST GET /flows listing for that user. Mirror the REST guard at the resolver
boundary, matching the existing createFlow "... is required" checks.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 15:16:33 +07:00
Sergey KozyrenkoandClaude Opus 4.8 e1b7d8e5d9 fix(resources): pre-flight blob stats so a ZIP download can't truncate under 200
The streaming ZIP refactor made `ZipResources` open each blob inline while
`streamZipArchive`'s writer commits HTTP 200 on the first byte. A blob missing
on disk (a DB record whose blob file is gone) failed mid-stream, so the client
received a 200 with a central-directory-valid but incomplete archive — the
missing files silently dropped (regression vs main, which buffered then sent).

Stat every blob up front; a missing one now returns before any byte is written,
so `streamZipArchive` emits a clean structured error instead. Keeps the
streaming memory benefit.

Tests (both proven fail-on-unfixed / pass-on-fixed): a unit test asserts the
writer stays empty when a blob is missing, and a download-handler test asserts
a missing blob in a multi-file ZIP returns a clean 500, not a truncated 200.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 13:51:54 +07:00
Sergey KozyrenkoandClaude Opus 4.8 9bda603de3 refactor(frontend): prune restatement comments
Drop comments that restate the code they sit on (public-route auth block,
app.tsx catch-all-route label, image-handle overlay description) per the
project's default-zero comment policy. Kept the load-bearing inline note that
password_change_required is local-users-only.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 13:10:35 +07:00
Sergey KozyrenkoandClaude Opus 4.8 dc1ebef25f fix(file-manager): use OKLCH token directly for the multi-drag badge
The multi-drag "N items" drag image set `hsl(var(--primary))`, but the theme
tokens are OKLCH values — `hsl(oklch(...))` is invalid CSS and dropped, leaving
a transparent badge with default text. Reference the tokens directly via
`var(--primary)` / `var(--primary-foreground)` (theme-aware, valid).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 13:10:35 +07:00
Sergey KozyrenkoandClaude Opus 4.8 cd9f45d69c fix(oauth-result): drive status text through state so it updates in production
`updateMessage` only mutated a ref, so the visible status ("Authentication in
progress...") never changed in production — it appeared to work only in dev via
StrictMode's double-mounted useLayoutEffect. Call setStatusMessage directly and
drop the dead ref + layout-effect machinery. The OAuth flow itself was already
correct (close/redirect use locals); only the visible text was frozen.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 13:10:34 +07:00
Sergey KozyrenkoandClaude Opus 4.8 ee9393d4c0 fix(a11y): name sidebar new-actions + mark active editor-menu options
- main-sidebar.tsx: the three icon-only "New" quick-action links wrapped a bare
  <Plus/> with no accessible name (WCAG 2.4.4/4.1.2) — add aria-label
  "New flow"/"New template"/"New knowledge".
- editor toolbar heading/list/table-align menus: single-select options marked
  the active one with only a visual <Check>. Add role="menuitemradio" +
  aria-checked (mirroring the shipped Header-row menuitemcheckbox) so screen
  readers announce which option is active. Visual affordance unchanged.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 13:10:34 +07:00
Sergey KozyrenkoandClaude Opus 4.8 933a80147e perf(context): memoize providers + system-settings context values
Both provider components built their context `value` as a fresh object literal
each render (providers-provider also re-sorted into a new array and recreated
its setter), forcing every consumer to re-render on each provider render.
Memoize the sorted array, the setter, and both value objects — the two
non-memoized outliers among the app's context providers. No behavior change.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 13:10:14 +07:00
Sergey KozyrenkoandClaude Opus 4.8 605b271214 perf(settings-provider): stop per-keystroke full-form validation
Subscribing to `formState.isValid` via useFormState flips RHF's internal
`_proxyFormState.isValid`, which makes the zod resolver re-run over the WHOLE
form (13 agent accordions × ~19 fields + refines) on every keystroke — even
in onSubmit mode. `isValid` is only needed to gate the unsaved-changes dialog,
so validate lazily when that dialog opens instead of subscribing. Live INP on
the Name field: steady-state per-keystroke processing 152ms worst-case → ~5ms.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 13:10:13 +07:00
Sergey KozyrenkoandClaude Opus 4.8 c517ccbb1e chore(frontend): remove dead code (monaco chunk, setSelection, isNew branch)
- vite.config.ts: drop the manualChunks 'monaco' branch — monaco was removed
  in the monaco→tiptap migration (82b82c5), so the regex never matches.
- use-file-manager-selection.ts: remove `setSelection` — no caller destructures
  it (file-manager.tsx never did); all writes go through rawSelectedPaths.
- settings-prompt.tsx: remove the unreachable `isNew` (promptId === 'new')
  branch — nothing routes to /settings/prompts/new, and it would render a
  "Create Prompt" header over a "Prompt not found" card. The real create path
  is `isUpdate === false`.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 13:10:12 +07:00
Sergey KozyrenkoandClaude Opus 4.8 bfd5b9d42f fix(markdown-editor): give the editor contenteditable an accessible name
The rich editor is a contenteditable div with role="textbox", which is
NOT a labelable element — a sibling `<FormLabel htmlFor>` can't name it,
and two of the three consumers (settings-prompt, template) render no
visible label at all, so the field had no accessible name (Lighthouse
A5). Thread `aria-label` through MarkdownEditorField to the contenteditable
(via the same view.dom passthrough as aria-describedby/aria-invalid) and
to the raw textarea, with each consumer supplying its name.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 03:46:33 +07:00
Sergey KozyrenkoandClaude Opus 4.8 44b5fef6dc fix(api-tokens): clear the table filter when opening the create row
The inline "Create Token" row is a data row prepended at index 0, so an active
table filter (globalFilterFn) or a non-first page hid it — clicking Create Token
appeared to do nothing. handleCreateNew now calls setFilter(''), which clears the
filter and resets pageIndex to 0 (clearPageOnFilterChange default), so the create
row is always visible.

Live-verified (docker/HEAD backend): with a non-matching filter, Create Token now
shows the create row and clears the filter.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 01:37:49 +07:00
Sergey KozyrenkoandClaude Opus 4.8 bbdbdb8666 refactor(resizable): fix panel minSize at 390px instead of a percentage
Follow-up to a55cac3 / 2a3a553. A percentage minSize scales with the screen:
30% is ~700px on a 2560px display and ~1000px on an ultra-wide — far too large
a floor. Give both resizable splits (DetailSplitLayout + flow.tsx) a fixed 390px
per-panel minimum (numeric = px in react-resizable-panels v4). defaultSize stays
a percentage: flow 50%, DetailSplitLayout 45%/55%.

Verified live (chrome-devtools, dev server, real flow + settings-prompt):
- 1280px (narrowest desktop): group 1024px, both mins 390px — no collision
  (2x390 < 1024), drag range 390..633px.
- 2560px: min stays 390px (16.9%), not 691px (30%).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-09 13:32:41 +07:00
Sergey KozyrenkoandClaude Opus 4.8 2a3a553065 fix(flow): resizable panel sizes as % strings, not bare numbers
Same react-resizable-panels v4 pixels-not-percent pitfall as detail-split-layout
(a55cac3): flow.tsx's desktop two-panel split passed minSize={30}/defaultSize={50}
as numbers, so the 30 was a 30px floor — a user could drag either the central-tabs
panel or the detail panel down to a ~30px sliver instead of the intended 30%.

Use string percentages: minSize "30%", defaultSize "50%".

Verified live (chrome-devtools @1440px, dev server on a real flow): separator
aria-valuemin=30, dragging a panel to its minimum floors at 29.97% (355px).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-09 13:24:32 +07:00
Sergey KozyrenkoandClaude Opus 4.8 a55cac3225 fix(detail-split-layout): pass panel sizes as % strings, not bare numbers
react-resizable-panels v4 reads numeric size props as PIXELS, not percent
("Numeric values are assumed to be pixels"). So `minSize={30}` was a 30px
floor — a user could drag either panel down to a ~30px sliver (~2.5% on a
1184px group) instead of the intended 30%. `defaultSize={45/55}` were px too
(they only rendered ~45/55% because default sizes normalize to a ratio;
minSize is an absolute per-panel constraint and is not normalized).

Use string percentages so the constraints mean what they read: minSize "30%",
defaultSize "45%"/"55%".

Verified live (chrome-devtools @1440px): separator aria-valuemin 2.536 -> 30;
dragging a panel to its minimum now floors at 29.97% (355px) instead of 30px.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-09 13:14:28 +07:00
Sergey KozyrenkoandClaude Opus 4.8 cc908e5108 docs(frontend): prune restatement/narration comments, keep only real gotchas
Re-reviewed every frontend comment against the "names a concrete wrong action"
rubric. Cut pure restatements, change-narration, self-defense and bug-history;
trimmed mixed comments down to their load-bearing gotcha/contract; kept genuine
framework/API/security notes. Relocated a misplaced JSDoc in resources-provider
that sat on `error` but described `resources` (fields are alphabetically sorted).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-09 12:35:17 +07:00
Sergey KozyrenkoandClaude Opus 4.8 6b01c109d2 docs(breakpoints): drop the comment (768/1280 are recognizable Tailwind md/xl)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-08 13:51:48 +07:00
Sergey KozyrenkoandClaude Opus 4.8 330223bc28 refactor(breakpoints): align useBreakpoint to Tailwind tokens; field height goes pure CSS
The JS "desktop" threshold was 1200px, which is no Tailwind breakpoint, so anything
mixing useBreakpoint with a CSS `md:`/`xl:` variant for the same decision could drift
in the 1024–1279 zone. Move the threshold to Tailwind `xl` (1280) — mobile already
sat on `md` (768) — so JS layout switches and CSS variants now share the same values.

With the breakpoint a real token, MarkdownEditorField drops useBreakpoint and expresses
its height in plain CSS: fixed `h-[calc(100dvh-5rem)]` below xl (stacked forms, internal
scroll), `xl:min-h-0 xl:flex-1` to fill its pane on the desktop split. No JS hook, no
comment. Note: the split view now appears at ≥1280 instead of ≥1200.

Verified <xl live (fixed 1194px, internal scroll); the ≥1280 branch resolves to the same
`min-h-0 flex-1` fill already measured at 1440px — this browser window caps at ~1141px so
the wide layout could not be re-observed here.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-08 13:47:34 +07:00
Sergey KozyrenkoandClaude Opus 4.8 217ee785c4 docs(markdown-editor): drop the height comment (obvious CSS + bug-history)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-08 13:24:54 +07:00
Sergey KozyrenkoandClaude Opus 4.8 fdc533aba4 docs(markdown-editor): trim the height comment to the two load-bearing gotchas
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-08 13:22:06 +07:00
Sergey KozyrenkoandClaude Opus 4.8 d378b9f582 fix(markdown-editor): cap the mobile editor height so a long doc scrolls inside
The mobile/tablet branch used `min-h-[calc(100dvh-5rem)]`, only a floor — the
stacked forms have no flex parent to cap it, so a long document (a big agent
prompt is ~10k px of text) stretched the editor to its full content height and
the whole page grew with it. Make it a FIXED `h-[calc(100dvh-5rem)]` so the box
stays one viewport tall and the content scrolls inside it. Desktop (fills its
pane) is unchanged. Live-verified: the Adviser prompt editor is now 1194px with
an internal scrollbar instead of 10.6k px.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-08 13:08:22 +07:00
Sergey KozyrenkoandClaude Opus 4.8 b4949eada3 refactor(markdown-editor): field owns its responsive height for every consumer
The mobile fixed height was knowledge-only; make it the field's job for all. The
field now derives its own height from useBreakpoint — the SAME hook the layouts
switch on — so it fills its flex parent on desktop and takes a near-viewport fixed
height on mobile/tablet, everywhere. Knowledge drops its last height className.
This also fixes the settings-prompt and template editors, which had no mobile
height and were cramped in their stacked mobile layouts. Live-verified all three
on desktop (fills) and mobile (min-h calc(100dvh-5rem)).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-08 12:55:08 +07:00
Sergey KozyrenkoandClaude Opus 4.8 57988fba58 refactor(markdown-editor): default the field to fill its flex parent
Every consumer embedded MarkdownEditorField in a `flex min-h-0 flex-col` column and
repeated `min-h-0 flex-1` to make it fill. Bake that default into the field (applied
first so a consumer can still override the height), and drop the boilerplate:
settings-prompt and template pass no className now, and the knowledge field only
keeps its one deviation — a fixed `min-h-[calc(100dvh-5rem)]` for the mobile stack
where it isn't inside a flex box. Live-verified all four surfaces: rich editor fills
(flex-1, min-h 0) on prompt/template/knowledge-desktop, and knowledge-mobile keeps
the fixed 100dvh-5rem height.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-08 12:41:33 +07:00
Sergey KozyrenkoandClaude Opus 4.8 05394d1492 fix(settings): widen two dialogs pinned to 512px by the same sm:max-w-lg default
The prompt-validation dialog (max-w-2xl) and the provider-test-results dialog
(max-w-3xl) had the same latent bug as the Diff dialog: a bare max-w-* cannot
override DialogContent's default sm:max-w-lg at ≥sm, so both rendered at 512px
instead of 672/768px. Prefix with sm: so they reach their intended width.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-08 01:46:13 +07:00
Sergey KozyrenkoandClaude Opus 4.8 be04e03239 fix(settings-prompt): widen the Diff dialog (max-w-7xl never applied on desktop)
The Diff dialog passed a bare `max-w-7xl`, but DialogContent's default already
sets `sm:max-w-lg`. tailwind-merge keeps both (different variants), and at ≥sm the
`sm:` rule wins the cascade — so the dialog was pinned at 512px and the split diff
overflowed with a horizontal scrollbar. Use `sm:max-w-7xl` so it overrides the
default at the same breakpoint, matching the app's other wide dialogs. Verified
live: the real Diff dialog now renders at 1280px with no horizontal scroll.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-08 01:43:52 +07:00
Sergey KozyrenkoandClaude Opus 4.8 87662d419a refactor(ui): rename DetailTwoPanelLayout → DetailSplitLayout, left/right → panel/content
Renames the shared two-pane detail layout to DetailSplitLayout (file
detail-split-layout.tsx) and its slots left/right/rightClassName to
panel/content/contentClassName, which name the actual roles — a form/meta panel
beside the main editor content — instead of bare position. Updates all four
consumers (knowledge form, template, settings prompt, settings provider).

Also drops a dead GripVertical child passed to <ResizableHandle withHandle /> (the
handle renders its own grip and ignores children) and gives the left panel a
bg-card fill so the gutters around the centered card match the card colour.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-08 00:34:39 +07:00
Sergey KozyrenkoandClaude Opus 4.8 a1d3f13793 test(markdown-editor): exhaustive HeadingAutoformat coverage; fix multi-line promotion
Adds markdown-editor-heading-autoformat.test.ts (57 cases): levels, marker stripping,
negatives, hardBreak protection, every trigger path (delete/split/merge/insertText/
setContent/insertContent), the canReplaceWith container gate, multi-target ordering,
mark/variable/tag preservation, byte-fidelity interaction, and re-entrancy. The 6
ad-hoc Case B tests move here from the extensions suite.

Writing the coverage surfaced a soundness bug: promoting a MULTI-LINE paragraph whose
first line starts with `# ` (e.g. `# a`+Shift+Enter+`# b`, then deleting the lead-in)
emitted a heading containing a hardBreak, which re-parsed as TWO headings on the next
load. HeadingAutoformat now skips any paragraph that contains a hardBreak — a heading
is single-line — so such a block stays body text and escapeLineLeadingBlockMarkers
round-trips it. Single-line promotion is unchanged.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-08 00:11:01 +07:00
Sergey KozyrenkoandClaude Opus 4.8 9d0e1924a1 feat(markdown-editor): promote a block that starts with # to a heading on any edit
The heading input-rule fires only on the keystroke that types `# ` at a block
start. A block that comes to start with `# ` any other way — deleting the text
before an existing `#`, pressing Enter in front of it, pasting — stayed a
paragraph, diverging from CommonMark (a leading ATX marker IS a heading) and from
what the same text becomes on reload.

HeadingAutoformat, a ProseMirror appendTransaction plugin, promotes such a
paragraph to the matching heading (stripping the marker) on every doc-changing
transaction. It keys off the block's first child, not textContent, so a `# ` after
a hardBreak (Shift+Enter) correctly stays body text — that is a soft break inside
the paragraph, so the block does not start with `#`.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 23:22:38 +07:00
Sergey KozyrenkoandClaude Opus 4.8 cb9012ce11 fix(markdown-editor): keep line-leading # / > in a paragraph as body text
A paragraph line starting with "# " or "> " (reachable by Shift+Enter then such a
line — the heading input-rule only fires at a block start, not after a soft break)
serialized verbatim through the identity encoder and re-parsed as a heading /
blockquote on the next load, silently changing the block TYPE of body text.

Fix it as a symmetric pair: the paragraph serializer escapes a line-leading
`# `/`> ` to `\# `/`\> `, and the tuned marked Lexer's escape tokenizer — otherwise
off to keep `\d`/`\|`/`\\` literal — unescapes exactly `\#`/`\>` back on load. Only
these two markers are handled; `-`/`*`/`+`/`1.`/fences overlap with literal
regex/glob/backref escapes (`\*`, `\1`, `\|`) the editor must preserve, so they are
left alone. Real headings/blockquotes, regex/glob literals, and mid-line `#` are
unchanged (full byte-fidelity corpus stays green); adds pin tests.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 22:14:56 +07:00
Sergey KozyrenkoandClaude Opus 4.8 2b7931732a refactor(markdown-editor): drop the toolbar roving-focus childList observation
The roving-tabindex MutationObserver watched childList:true/subtree:true, justified
by a comment claiming "the table control swaps button↔menu". Verified against the
source: the toolbar's item set is static (every control renders unconditionally;
state only drives pressed/disabled props), and each menu keeps its `data-toolbar-item`
trigger in the bar while swapping its content in a Radix body portal — outside the
observed subtree. So childList observed nothing. Keep only the load-bearing
attributeFilter:['disabled'] + subtree (a disabled toggle changes the roving set),
and correct the comment.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 21:24:33 +07:00
Sergey KozyrenkoandClaude Opus 4.8 2835fd3302 test(markdown-editor): close four coverage gaps found in review
- history: assert resetUndoHistory actually empties the undo stack
  (editor.can().undo() === false), not just that it doesn't throw — a silent
  no-op regression would otherwise pass.
- field: assert insertAtCursor is a no-op (no onChange) when the field is
  disabled — the documented "a mid-save variable click can't dirty the form"
  guard was untested.
- content-integrity: the pipe-table generative test now also asserts each
  pipe-bearing atom survives as an escaped code span, not just the row sentinels.
- code-fence: fix the pinned-limitation comment — an upstream fix turns this
  test RED (the canary), it does not "flip green".

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 20:45:32 +07:00
Sergey KozyrenkoandClaude Opus 4.8 786e416dc5 fix(markdown-editor): add a sub-pixel tolerance to the toolbar wheel end-check
The horizontal wheel-scroll handler treated the strip as "at end" only when
scrollLeft + clientWidth exactly reached scrollWidth. At fractional browser zoom
(125%/150%) those metrics never line up to the pixel, so the end was never
detected and the handler kept preventDefault-ing the wheel — locking page
scroll while the pointer was over the toolbar. Allow a 1px tolerance.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 20:41:26 +07:00
Sergey KozyrenkoandClaude Opus 4.8 cf34a7b3df refactor(markdown-editor): drop a dead barrel export, a band-aid, and rename a param
- index.ts: stop re-exporting findVariableUseRanges — every consumer imports it
  from the module directly, so the barrel entry was dead.
- textarea.ts: drop Math.max(0, …) around textarea.selectionStart/End; both are
  spec non-negative and non-nullable for a real HTMLTextAreaElement, so the guard
  protected nothing. (The Math.max in the scrollTop math stays — it guards a real
  negative subtraction.)
- link/image handles: rename the Popover onOpenChange param `next` → `isOpen`,
  matching the boolean-naming convention and TableHandles.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 20:39:50 +07:00
Sergey KozyrenkoandClaude Opus 4.8 bca7b6747f refactor(markdown-editor): trim restating/defending comments per the zero-comment rule
Drop comments that restate adjacent code or defend a design choice, keeping only
the clauses that carry a non-derivable contract:
- useMarkdownEditor / useTableHandles: delete the responsibility-enumeration and
  "rewriting only this hook" banners.
- clearLineContents: drop the "(Notion's Clear contents)" trivia, keep the
  "structure intact, not a delete" distinction.
- normalizeImageSrc: keep the SVG-can-carry-script rationale, drop the restatement.
- nextVariableRange: keep the shared-by-both-panels invariant, drop the algorithm
  walkthrough.
- image edit-form isEditing prop, two highlight-test negatives, and a table-pipes
  test perf war-story: drop the restatements.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 20:37:32 +07:00
Sergey KozyrenkoandClaude Opus 4.8 fde073e393 fix(markdown-editor): give the link edit-form label/aria-describedby parity
The link edit-form relied on a placeholder + aria-label with no visible <Label>,
and its invalid-URL alert had no aria-describedby back to the input — both
present on the sibling image edit-form. A screen-reader user who tabbed onto the
field after the error fired never heard why it was invalid. Add a visible Label
(via useId) and wire aria-describedby to the error id, matching ImageEditForm.

Also trim two comments per the zero-comment rule: the normalizeLinkUrl-return
restatement (documented at the callee) and the "(matches Docs/Notion)"
competitor-justification.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 20:33:31 +07:00
Sergey KozyrenkoandClaude Opus 4.8 215c1cd8c9 test(markdown-editor): raise the generative content-integrity test timeouts
The three property-based tests each run 120–300 full editor round-trips and sit
right at vitest's default 5s limit, so they flaked to a timeout under a loaded
or serialized full-suite run (never in isolation, and never on an assertion).
Give them an explicit 30s budget so the full suite is deterministic.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 20:25:40 +07:00
Sergey KozyrenkoandClaude Opus 4.8 418b1eae65 fix(markdown-editor): write the table-grip open ref synchronously to close a race
openRef was mirrored from the `open` state through a passive effect, but the
document-level mousemove handler and the stale-target droppers read
openRef.current on continuous events. Between a grip click (setOpen) and the
effect flush, a mousemove saw the stale null and retargeted the grip — and the
about-to-open menu — onto a neighbouring cell. Set the ref synchronously inside
onMenuChange before setOpen and drop the mirroring effect.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 19:54:30 +07:00
Sergey KozyrenkoandClaude Opus 4.8 b4fb572efa fix(markdown-editor): dismiss table hover-grips on window resize
Unlike the link and image handles, TableHandles registered only scroll (and,
now, editor update) invalidation — never resize. Resizing the window reflowed
the table but left the fixed-position grips glued to their old coordinates,
detached from the table, until the next hover. Mirror the sibling handles and
drop the target on resize too.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 19:44:36 +07:00
Sergey KozyrenkoandClaude Opus 4.8 6c3a011fe2 refactor(markdown-editor): share the .tiptap-content scroll-parent hook
The three overlay handles (link/image/table) each found their dismiss-on-scroll
parent with a hardcoded closest('.tiptap-content') ?? window, while the class
itself lived only inside markdown-editor.tsx's className string. A styling
refactor renaming that token would have silently sent all three to `window`
(whose scroll never fires for the inner overflow-auto), freezing popovers/grips
at stale coordinates — with no type error or failing test.

Export EDITOR_CONTENT_CLASS + getEditorScrollParent from the leaf styles module
and consume both from the className and the three handles. Behavior-neutral.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 19:41:35 +07:00
Sergey KozyrenkoandClaude Opus 4.8 b214bafe60 fix(markdown-editor): key the link popover on the link start, not its full range
The link edit popover was keyed on `${range.from}-${range.to}`. Typing inside a
link grows range.to on every keystroke (the character inherits the link mark), so
<LinkEditForm key={key}> unmounted and remounted each keystroke and re-seeded its
URL field from initialUrl — silently discarding an in-progress URL edit and
churning the popover DOM.

Key on range.from alone: it is stable while the caret stays in the same link, and
still changes when the selection moves onto a different link.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 19:27:50 +07:00
Sergey KozyrenkoandClaude Opus 4.8 bfc6b7a0d1 fix(markdown-editor): reject root-relative paths instead of mangling the host
normalizeLinkUrl/normalizeImageSrc prepended https:// after stripping ALL
leading slashes (url.replace(/^\/+/, '')), so a root-relative path was
re-hosted onto its first segment: '/settings/profile' → 'https://settings/profile',
'/uploads/logo.png' → 'https://uploads/logo.png'. The result was non-null, so the
Apply button stayed enabled and the bogus href/src was persisted.

Extract toAbsoluteCandidate: only //host (protocol-relative) is promoted (prepend
the scheme); a single leading slash returns null (this field only accepts absolute
external URLs). Scheme-less hosts and existing protocol-relative cases are unchanged.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 19:22:40 +07:00
Sergey KozyrenkoandClaude Opus 4.8 3ea784bc2f fix(markdown-editor): stop a stale table hover-grip from crashing or misediting
A hover grip captures its cell position once on mousemove and was never
invalidated when the document changed. Editing elsewhere (without moving the
mouse) then left cellPos pointing past the shifted doc, so two things could
happen: RowHeaderToggleItem's useEditorState selector called
hasHeaderRow(editor, cellPos) → doc.resolve(pos) → a synchronous RangeError
that takes down the whole editor render tree; and a "Delete row/column" ran
setTextSelection against the stale offset, editing the wrong line.

Guard doc.resolve in hasHeaderRow (an out-of-bounds position has no header
row), and extend the grip's existing scroll-invalidation to fire on editor
'update' too, so the target drops on any doc change and reappears on the next
hover. Adds the first unit tests for table-commands.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 19:19:10 +07:00
Sergey KozyrenkoandClaude Opus 4.8 c87a31f38b fix(markdown-editor): drop the U+001F cell-join byte from saved table markdown
Pressing Enter in a table cell makes a second paragraph, and
renderTableToMarkdown joins a cell's block children with a raw U+001F
separator (outside renderChildren). That control byte was written verbatim
into the saved .tmpl/knowledge markdown and round-tripped back unchanged —
an invisible, persisted corruption of the file.

A GFM cell is single-line, so collapse the separator to a space on the
table's rendered output.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 19:13:11 +07:00
Sergey KozyrenkoandClaude Opus 4.8 2067b50359 fix(markdown-editor): protect tables inside a blockquote from cell loss
The line scanner only recognized top-level tables (^ {0,3}), so a `> `-prefixed
delimiter row failed TABLE_DELIMITER_LINE and the whole blockquote table went
unprotected — marked then stripped the prefix, parsed the table, and dropped
cells whose code span / template / URL held a pipe.

Detect a blockquote run, strip each line's prefix, recurse on the inner content
(reusing every rule here, so nested `> >` and fenced blocks inside the quote are
handled too), then re-apply the original prefix. Escaping never touches the
prefix, so untouched rows stay byte-exact.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 19:04:12 +07:00
Sergey KozyrenkoandClaude Opus 4.8 5e7dbb7441 fix(markdown-editor): escape URL pipes by cell-count, killing a table-row DoS
escapeRowPipes escaped pipes inside any `scheme://` run via a greedy
/[^\s]*:\/\/[^\s]*/g. Two bugs: (1) a long non-URL token (base64, a hash)
made that regex backtrack quadratically — 120k chars froze for ~11s on every
rich load, a stored, target-influenceable client-side DoS; (2) in a compact,
spaceless row like `|http://a.com|b|` the run swallowed the structural pipes
and escaped them, collapsing the row into one cell.

A URL pipe and a spaceless cell separator are indistinguishable in isolation,
so disambiguate by cell count: only escape scheme-run pipes when the row splits
into MORE cells than the header expects (a genuine phantom-cell URL pipe). A row
already at the right count keeps its structural pipes. The guard also skips the
scan on ordinary rows, and the replacement is a linear /\S+/g pass, so a long
token can no longer drive it superlinearly.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 19:00:25 +07:00
Sergey KozyrenkoandClaude Opus 4.8 19fc4b3092 fix(markdown-editor): track fence length so a 4-backtick block isn't closed early
The escapeTablePipes fence tracker matched a fixed 3-char run (```/~~~) and
compared truncated tokens, so a 4-backtick block — which renderTunedCodeBlock
emits whenever the block's content holds a ``` line — was "closed" by that inner
3-backtick line. Two failures followed: pipes inside the real code block got
`\|` injected into the saved bytes, and a genuine table AFTER the block lost its
protection (the tracker thought it was still inside a fence), dropping cells.

Capture the full run and its trailing text; close only on a same-char run of
length >= the opener with no info string, mirroring CommonMark.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 18:56:09 +07:00
Sergey KozyrenkoandClaude Opus 4.8 81e448cf05 fix(markdown-editor): normalize CRLF in escapeTablePipes so tables keep cells
The pre-lex pipe protection split on '\n', leaving a trailing '\r' on every
line. The '$'-anchored TABLE_DELIMITER_LINE then failed to match '| --- |\r',
so the whole module no-op'd on CRLF input and marked dropped cells whose code
spans / templates / URLs held a pipe — silently losing data on the first load
of Windows- or API-authored content.

Normalize '\r\n' and lone '\r' to '\n' up front (marked re-normalizes the
returned string anyway). Original bytes are preserved when nothing is escaped.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 18:53:11 +07:00
Sergey KozyrenkoandClaude Opus 4.8 b015f3ba98 fix(markdown-editor): bound paste link cue to kill ReDoS on large pastes
The link cue in MARKDOWN_CUES was /\[.+\]\(.+\)/ — a double-`.+` that
catastrophically backtracks. isMarkdownLike runs synchronously in
handlePaste on every paste carrying an html flavor, so a large
bracket-heavy non-link paste froze the tab: 40k `[x]` reps → 3.7s,
120k → 33s (measured against the exact regex).

Bound both spans with negated classes (`[^\]]+`/`[^)]+`): linear-time,
matches real links identically (120k adversarial input drops to <1ms),
and now also catches multi-line link text. Add a ReDoS-budget regression
test and an invariant comment for future cue additions.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 18:46:15 +07:00
Sergey KozyrenkoandClaude Opus 4.8 6326719ae1 fix(file-manager): mark the built-in delete action destructive
The built-in single deleteAction's JSDoc promised a "destructive variant"
but the object never set variant:'destructive', so the row-menu Delete
rendered as a default (non-red) item — unlike the bulk delete. Now that
the DropdownMenu/ContextMenu items support variant="destructive" and
file-manager-row forwards action.variant, set the flag so single deletes
read as destructive, matching the bulk action and the documented intent.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 17:15:02 +07:00
Sergey KozyrenkoandClaude Opus 4.8 1ef56d1972 refactor(forms): migrate FlowForm to useAppForm
FlowForm was the last form on raw useForm with mode:'onChange' (behind the
lint guard's inline disable). Migrating is behavior-neutral: the file has no
error UI, and RHF recomputes isValid eagerly on every change when it's
subscribed — so the send button keeps toggling live under useAppForm's
mode:'onSubmit' exactly as before, verified live (empty→disabled, typed→
enabled, cleared→disabled) across the composer.

Swaps useForm({mode,resolver}) for useAppForm({schema}) and drops the
eslint-disable. The !isValid submit gate and the three
setValue(...,{shouldValidate:true}) calls are load-bearing for the send
button (imperative setValue doesn't refresh isValid without the flag) and
are kept intentionally.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 15:51:48 +07:00
Sergey KozyrenkoandClaude Opus 4.8 3ac35ee0d2 feat(forms): enforce the validation convention (noValidate + useForm lint guard)
Two convention hardenings on top of useAppForm:

- noValidate on every react-hook-form <form>: validation runs through zod,
  so native HTML5 constraint validation (type="email"/required) firing
  browser-locale popups on submit is unwanted everywhere — not just the
  email-change form that first hit it.
- no-restricted-syntax lint rule flagging mode/reValidateMode on useForm,
  steering new forms to useAppForm (the single owner of the timing).
  use-app-form.ts is exempted (it's the definition); flow-form keeps its
  live-validation mode behind an inline disable pending its migration.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 15:24:31 +07:00
Sergey KozyrenkoandClaude Opus 4.8 dcce62397f test(auth): cover LoginForm silent-until-submit convention
LoginForm had no unit tests. Adds the convention-critical cases: fields
stay silent until the first submit (even after type+blur), submit surfaces
errors without calling login, fixing a field clears its error live once
submitted, and a valid submit calls login and navigates.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 15:23:54 +07:00
Sergey KozyrenkoandClaude Opus 4.8 0a5a9a6cda refactor(ui): adopt shadcn v4 data-slot + aria-invalid, fix primitive drift
Our ui/* primitives were an older shadcn v4 generation. This ports the
low-risk, invisible/bugfix tier (Tier A of the drift audit), preserving all
local customizations (badge color variants, input spinner suppression,
textarea autoSize API, skeleton bg-primary/10, sidebar Cmd+B guard, etc.).

- data-slot="..." on ~33 primitives (was only 6); bare re-exports wrapped in
  functions to host it. className strings verified identical to before.
- aria-invalid destructive styling on checkbox/button/toggle (was already on
  input/textarea/select).
- resizable: replace dead data-[panel-group-direction=vertical] selectors with
  the aria-[orientation=*] ones react-resizable-panels@4.11.2 actually emits
  (latent — no vertical groups today; proven live via DOM experiment).
- dropdown-menu: viewport-aware max-h + overflow-y-auto on Content; add
  variant="destructive" (mirrored on context-menu) and rewire file-manager-row
  to use it instead of a hand-rolled className.
- checkbox: neutral border-input when unchecked, border-primary only when
  checked (was always primary).
- input/textarea: min-w-0, disabled:pointer-events-none, dark:bg-input/30,
  text-base md:text-sm (prevents iOS focus-zoom on mobile).
- sidebar: give the mobile Sheet real sr-only title/description.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 14:51:05 +07:00
Sergey KozyrenkoandClaude Opus 4.8 73d8c27e46 fix(ui): show the destructive border on invalid Input/Textarea/Select
These primitives set aria-invalid (via FormControl) but never styled it, so an
invalid plain field showed a red label and message yet kept a neutral border —
while InputGroup/InputPassword and textarea-autosize already went red. Add the
same aria-invalid:border-destructive + ring the group primitives use, so every
field type reads the same when invalid (Input also fixes Autocomplete, which
wraps it).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 13:21:27 +07:00
Sergey KozyrenkoandClaude Opus 4.8 31b91c56be fix(auth): suppress native email validation popup on the email-change form
The New Email field is type="email", so on submit the browser fired its own
locale-styled constraint-validation popup, pre-empting our zod error and looking
out of place. Add noValidate to the form so validation runs through zod/RHF and
surfaces the consistent in-app FormMessage ("Invalid email address") instead —
and it no longer masks the current-password error the native popup shadowed.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 13:13:23 +07:00
Sergey KozyrenkoandClaude Opus 4.8 a3f2a73ca0 feat(forms): migrate auth forms to useAppForm
Move login, password-change, email-change, and name-change onto the shared
useAppForm wrapper — the last data-entry forms still on raw useForm. These were
already on react-hook-form's default timing (onSubmit + onChange revalidate), so
this is behavior-neutral: it only routes them through the single timing source
so none can later drift to eager validation, and keeps every form consistent.
Schemas and submit buttons (FormSubmitButton) are untouched, so the password
policy and login flow are unchanged.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 12:49:32 +07:00
Sergey KozyrenkoandClaude Opus 4.8 d31c73d35a feat(forms): silent-until-submit validation convention via useAppForm
Introduce a useAppForm wrapper that owns the validation timing (mode 'onSubmit'
+ reValidateMode 'onChange') and the zod resolver, so no form can drift back to
eager 'onTouched'/'onChange' that paints fields red before the user tries to
save. Three generics mirror useForm<Input, ctx, Output> for transform schemas.
Migrate every data-entry form to it (knowledge, templates, prompts, providers,
api-tokens, resources copy/move/mkdir, flow-files promote); submit buttons no
longer gate on isValid before the first submit (which would dead-lock a fresh
invalid form), except api-tokens which keeps its documented "disabled until a
date is set" gate. Full-height editor fields show the invalid state as a red
border (aria-invalid) with an sr-only message instead of layout-breaking text.
Also fills the knowledge editor to 100dvh-5rem on mobile.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 05:28:43 +07:00
Sergey KozyrenkoandClaude Opus 4.8 7912ebab1e feat(markdown-editor): purpose-built highlight tokens with WCAG-AA contrast
Add feature-scoped --editor-* tokens (link/variable/tag/inline-code) instead of
reusing --primary, which is a fill color that fails WCAG AA as text on the dark
surface. Four distinct hues so adjacent tokens don't blur (blue link, violet
variable, teal tag, red inline code on a visible chip); every token clears
4.5:1 in both themes. Drop the Tailwind Typography literal `backticks` around
inline code, and mirror the editor's inline-code styling in the read-only .prose
viewer so a document reads the same whether it is edited or viewed.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 05:27:49 +07:00
Sergey KozyrenkoandClaude Opus 4.8 36608a9dd0 feat(markdown-editor): shadcn toolbar with link/image popovers and table controls
Rework the editor toolbar into a shadcn-styled family of small modules:
heading and list dropdowns, an adaptive table menu (GFM-safe: no merge/split),
inline popovers for links and images with inline validation + URL normalization
(replacing window.prompt), click-to-edit link/image handles anchored to the
node, a reset-formatting action, roving-tabindex a11y, and tooltips. URL/image
sources are normalized to absolute https and gated by a protocol allowlist.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 05:27:26 +07:00
Osamaali313 36872809f1 fix(cast): delete pruned tool-call parts in reverse to avoid index shift
NewBodyPair collects the indices of ToolCall parts with a nil
FunctionCall into partsToDelete, then deletes them in a forward loop
using those pre-collected ascending indices. Each deletion shifts every
later element left by one, so with two or more collected indices the
second and subsequent deletions remove the wrong elements: a valid
TextContent can be dropped while an invalid nil-FunctionCall tool call
survives into the message chain (feeding malformed messages downstream).

Iterate the collected indices in reverse so earlier indices stay valid
during deletion. Adds a regression test covering two leading
nil-FunctionCall tool calls followed by a text part.
2026-07-06 00:02:03 +03:00
Sergey KozyrenkoandClaude Opus 4.8 30b22f9c17 refactor(markdown-editor): clearer names for three helpers
- insertTextareaText → insertAtTextareaCaret: mirrors the handle method it backs
  (insertAtCursor) and its sibling selectNextTextareaUse, and says WHERE it inserts
  ("textarea text" read as a noun phrase, not "text into a textarea").
- variableProbe → variableUseRegex: it returns a RegExp; the old name didn't signal
  the return type (read as if it returned a boolean).
- dropUnderscore → dropUnderscoreRules: it filters input/paste RULES, not a character.

Behavior unchanged; 889 vitest green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-05 19:07:54 +07:00
Sergey KozyrenkoandClaude Opus 4.8 d1ed015778 refactor(markdown-editor): rename cycleToVariable → selectNextUse
`cycleToVariable` read as "move to a variable" (a single target), but the method
advances the selection to the variable's NEXT use, wrapping — it cycles through the
variable's occurrences. `selectNextUse` says what it targets and matches the panel's
own "used ×N" terminology + findVariableUseRanges; it's the same family as code
editors' next-occurrence selection (CodeMirror's selectNextOccurrence, VS Code's
add-next-occurrence). The raw helper becomes selectNextTextareaUse. Behavior unchanged.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-05 18:59:16 +07:00
Sergey KozyrenkoandClaude Opus 4.8 831d9b8be2 docs(markdown-editor): trim restatement/redundant comments
A comment audit against the zero-default policy: the module's comments are overwhelmingly
genuine framework gotchas (undo → silent data corruption / crash / perf regression) and stay.
Cut only the handful that fail the wrong-action test:
- the "closures read latest props" reassurance (no wrong action it prevents),
- two JSDoc lines that restated self-documenting function names (cycleTextareaToVariable,
  insertTextareaText — the caret gotcha stays inline),
- two per-member handle JSDocs that restated method names (the interface-level mode contract stays),
- tightened the 6-line undo-clear block to 2.

No behavior change; 220 module tests green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-05 18:20:44 +07:00
Sergey KozyrenkoandClaude Opus 4.8 587d8a0ecf fix(markdown-editor): guard the link toolbar against non-navigable protocols (M3)
handleSetLink passed window.prompt output straight to setLink with no protocol check,
while the image toolbar already guards via isSafeImageSrc — so a user could toolbar-insert
`javascript:alert(1)` as a link href into the persisted document. Not a live XSS today (the
read-only viewer's react-markdown urlTransform and tiptap Link's isAllowedUri both sanitize
on render), but defense-in-depth: keep dangerous protocols out of the document at authoring
time so it never relies on every future render path sanitizing them.

Add isSafeUrl (mirror of isSafeImageSrc): allow http/https/mailto/tel + relative/anchor
(which resolve to the page protocol); reject javascript:/data:/vbscript:/file:/malformed.
Apply it in handleSetLink. Unit-tested alongside isSafeImageSrc; 889 vitest green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-05 18:04:41 +07:00
Sergey KozyrenkoandClaude Opus 4.8 5eb4ea22ad fix(markdown-editor): close two table-pipe defects missed by prior reviews + hardening
A full-feature review surfaced two real defects both living in the file that fixes
the table-pipe class — verified first-hand (repro + fix) through the real extension
stack and live on docker:

MEDIUM (data loss): escapeTablePipes escaped pipes only inside code spans and Go-template
actions, NOT inside link/image destinations or bare autolink URLs. A cell like
`[x](https://h/?a=1|2)` had its URL truncated at the pipe and the trailing cells silently
dropped on the FIRST load — the exact H1 corruption class, uncovered for URLs. Fix: a
URL_RUN pass escapes pipes inside any `scheme://` run (which never legitimately contains a
space, so a `|` in it is always content, never a real separator). Live: the URL and
trailing row now survive intact.

MEDIUM (ReDoS): TABLE_DELIMITER_LINE `/…\|? *:?-+:? *(?:…)*\|? *$/` had two adjacent ` *`
runs competing for the same characters, so a `|`-line followed by "dashes + a long space
run + a non-matching tail" backtracked O(n²) (2.4s at 64k) on every parse — mount, external
reset, paste. A crafted/AI-emitted doc froze the tab. Fix: a linear rewrite (trailing
`(?: *\|)? *$`, per-cell spacing) — same matches, sub-millisecond on the pathological input.

LOW: the imperative handle's insertAtCursor mutated a disabled editor (dispatch bypasses
the editable gate) and dirtied the form — guard rich on `editor.isEditable`, raw on `disabled`.

LOW (styleguide): `cs`→`computedStyle`, `looksLikeMarkdown`→`isMarkdownLike`, `endsTableBody`→`isTableBodyEnd`.

Tests: URL-pipe round-trip (link/image/bare, converges) + a real-separator-safety case +
a linear-regex ReDoS budget guard. 877 vitest green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-05 17:51:17 +07:00
Sergey KozyrenkoandClaude Opus 4.8 2e9eb96f75 refactor(markdown-editor): complete the field handle in raw mode, delete the settings-prompt bypass
Third-review MEDIUM-1: the field's imperative handle implemented cycleToVariable/
insertAtCursor only in rich mode, so settings-prompt reached around the component
with document.querySelector('#{formId} textarea') and hand-rolled a cycle algorithm
that was a structural duplicate of the rich one (drift hazard) plus formId plumbing,
a synthetic field object, a setTimeout caret restore, and a 35-line caretOffsetTop
mirror — ~80 lines of consumer bypass. This completes the already-shipped handle
contract (the same principle as making focus() work in both modes): the raw branch
now cycles/inserts over its textarea, both methods are required (drop the optional
`?`), and the cyclic "next occurrence" pick is one shared pure helper
(nextVariableRange) used by both surfaces. settings-prompt's handleVariableClick
collapses to mode-agnostic editorRef.current.cycleToVariable/insertAtCursor.

Also from the third review: LOW-1 the raw cn() argument order now puts the byte-exact
font-mono/no-resize classes last so a consumer className genuinely can't override them
(the comment claimed a contract the code didn't enforce); LOW-3 the handle contract is
JSDoc; LOW-5 the Suspense fallback forwards id/aria/disabled; LOW-6 the loading skeleton
and the editor's own placeholder share one wrapper class (extracted to a chunk-light
module) so first rich mount no longer flashes a different box; INFO-1 drop the unused
MarkdownEditorHandle barrel export; and a field-level unit test pins the mode-aware handle.

Live-verified on docker: raw + rich variable cycle work through the handle (querySelector
gone), console clean; 872 vitest green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-05 13:21:35 +07:00
Sergey KozyrenkoandClaude Opus 4.8 943b2aab01 fix(markdown-editor): honor field ref in both modes; unify to one handle
Post-review fixes (CODE-REVIEW 2026-07-05_1048):

LOW-1 + LOW-2 (ref contract): the field's `ref` was typed `Ref<MarkdownEditorHandle>`
but only wired in rich mode, so RHF's focus-on-validation-error silently no-oped in
raw mode (a regression: the pre-extraction `<Textarea {...field}>` wired field.ref).
MarkdownEditorField now exposes one honest `MarkdownEditorFieldHandle` — `focus()` in
BOTH modes (raw textarea / rich editor), variable-panel methods optional (rich-only).
Consumers forward `field.ref`; settings-prompt composes it with its variable-panel
editorRef via a new `composeRefs` util. Added `focus()` to the rich editor handle.
Fixed Textarea's ref typing (was an accidental Ref<HTMLTextAreaElement> ∩ Ref<TextareaRef>
intersection; TextareaRef also now declares the focus() it exposes at runtime).

LOW-3 (fallback duplication): dropped the `fallback` prop — both consumers used it only
to swap the spinner glyph while hardcoding layout classes that had to track `className`
by hand. All three now use the default spinner, which threads `className` and carries
aria-busy for the lazy-load window.

Live-verified on docker: invalid submit focuses the field in raw AND rich; the prompt
variable panel still cycles/scrolls through the composed ref; console clean.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-05 11:27:04 +07:00
Sergey KozyrenkoandClaude Opus 4.8 aba7589cb4 refactor(markdown-editor): collapse MarkdownEditorField class props to one className
MarkdownEditorField exposed three class props — className (rich wrapper),
contentClassName (rich content area), rawClassName (raw textarea). They are the
same concept: "size the field's outer box." The rich wrapper and the raw textarea
take identical flex/min-height layout, and contentClassName was used by exactly
one consumer for a mobile content floor that a wrapper min-height expresses just
as well.

Collapse to a single `className` applied to whichever element renders. Drop the
now-dead contentClassName prop from the underlying MarkdownEditor too. Consumers:
knowledge non-fillParent bumps min-h-[280px]→min-h-[320px] to keep the mobile
content area at ~240px once the toolbar wraps (previously floored via
contentClassName); template/prompt raw drop the min-h-[640px] floor and become
min-h-0 flex-1 like rich — flex-1 already fills at normal viewports (820px
measured), and raw now shrinks-and-scrolls consistently with rich on short ones.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-05 10:29:15 +07:00
Sergey KozyrenkoandClaude Opus 4.8 e9551f767f refactor(markdown-editor): extract MarkdownEditorField, own lazy() + raw/rich switch
The raw-textarea ⇄ rich-editor switch was hand-wired in all three consumers
(knowledge form, template page, settings-prompt), each repeating the byte-exact
raw config (autoSize={false} + resize-none font-mono) and its own lazy()/Suspense
boundary — and only template/prompt were lazy, knowledge pulled tiptap eagerly.

MarkdownEditorField centralises it: one owner of the mode switch, one place for
the raw="byte-exact source" contract, and one lazy() boundary so raw-only routes
never load the tiptap chunk. Because the field owns the boundary, the barrel can
re-export it eagerly (chunk-free until rich renders) and the a11y passthrough
now reaches the editor in template/prompt too.

Net -112 lines across consumers; settings-prompt's FormCodeItem + FormTextareaItem
collapse into one FormMarkdownItem (5 prop interfaces → 1).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-05 02:18:59 +07:00
Sergey KozyrenkoandClaude Opus 4.8 37d1739024 docs(markdown-editor): drop resetUndoHistory restatement comment
The lead comment restated what the function name/body already say and
asserted a caller contract the single-arg function cannot enforce — that
"must not run on user edits" invariant is enforced and documented at the sole
call site (the value-sync effect's guard). Comment audit: everything else in
the module is current + earns its place.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-05 01:45:43 +07:00
Sergey KozyrenkoandClaude Opus 4.8 5de52c125c refactor(markdown-editor): scope the table-pipe escape to the tuned marked Lexer
The load-side escapeTablePipes was installed by patching MarkdownManager.parse
on the shared library CLASS PROTOTYPE — a process-global mutation that every
@tiptap/markdown consumer would inherit. Move it onto the module's own private
marked instance instead: subclass `tunedMarked.Lexer` so `lex()` runs
escapeTablePipes first. The manager builds its block lexer via
`new markedInstance.Lexer(...)` (including the construction-time initial parse),
so this is instance-scoped, catches every load, and touches no shared class.
`inlineTokens` is inherited unchanged, so inline fragments are unaffected.

Behaviour-identical (866/866 green, incl. the pipe-less table regressions);
drops patchManagerParse + the isManagerParsePatched guard + the MarkdownManager
import. Independent-review follow-up (CODE-REVIEW-markdown-editor-2026-07-04_1437).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-05 01:16:54 +07:00
Sergey KozyrenkoandClaude Opus 4.8 4d96cb3567 fix(markdown-editor): protect pipe-less GFM table rows too (H1 gap)
The H1 table-pipe load fix (escapeTablePipes) only escaped body rows with a
leading `|` and stopped at the first row without one, and never escaped the
header. But GFM makes the outer pipe optional and marked treats a pipe-less
row as a table row, so a `|` inside a code span / Go action in a no-outer-pipe
table (`` A | B\n--- | ---\n`git log | head` | notes | done ``) was left
unescaped and marked dropped the trailing cell on first load — the exact H1
data loss, for the most common table style.

Widen the escaper to every row marked itself treats as the table: the header
plus all body rows up to a block boundary (blank line / heading / blockquote /
fence / list / hr / indented code — mirroring marked's gfmTable body-row
negative lookahead), never touching non-table lines (the escape tokenizer is
neutralised, so a stray `\|` outside a real table row would surface literally).

Regression tests for the pipe-less style + the block-boundary stop; the M7
generative oracle now emits both outer-pipe and pipe-less tables.

Found by an independent adversarial review (CODE-REVIEW-markdown-editor-2026-07-04_1437),
hand-reproduced via the round-trip harness before fixing.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-05 01:09:24 +07:00
Sergey KozyrenkoandClaude Opus 4.8 1b0c67da4e fix(markdown-editor): stop dropping table cells with piped code spans (H1)
marked's GFM table tokenizer splits a row on raw `|` before inline
tokenization, so a pipe inside a code span (`` `x | y` ``) or a Go action
(`{{.X | upper}}`) in a body cell spawned a phantom column and silently
dropped the trailing cells on load. Pre-escape those pipes as `\|` before
the manager lexes (escapeTablePipes, scoped to real table body rows, fences
skipped); the splitter honors `\|` and restores the literal `|` in the cell.
Symmetric with TunedTable's existing save-side pipe escape, so it converges.

Patched on MarkdownManager.prototype because the Markdown extension parses
the initial content inside its own onBeforeCreate, before any lower-priority
extension can wrap the manager instance.

M7: extend the generative content-integrity oracle with a table-cell context
+ pipe-bearing atoms — the one class the single-context oracle can't produce.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-04 12:23:20 +07:00
Sergey KozyrenkoandClaude Opus 4.8 773e9de5d8 fix(markdown-editor): keep inline formatting from rich-HTML pastes
An inline-only rich paste (Google Docs/Word/mail single paragraph - <b>,
<a href>, styled spans) carries no block tags, so the paste plugin hijacked
it into a plain-text markdown parse and silently dropped bold/italic/links.
Defer to ProseMirror's native HTML parse when the clipboard has HTML and the
text/plain shows no markdown cues - the schema DOMParser keeps those marks.
Markdown-looking text (a VS Code copy of markdown source wrapped in
syntax-color spans) still parses as markdown, matching load.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-04 12:11:13 +07:00
Sergey KozyrenkoandClaude Opus 4.8 c2d04a1d94 test(markdown-editor): pin multi-cycle entity-decode semantics
A multi-encoded entity in prose (`&amp;lt;`) intentionally loses one
encoding level per open+save cycle until fully decoded; inside code it is
byte-stable. Pinned so the cross-session behavior stays an explicit product
decision. Also correct the decode attribution in the tokenizer comment
(@tiptap/markdown's decodeHtmlEntities, not marked).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-04 12:08:53 +07:00
Sergey KozyrenkoandClaude Opus 4.8 430306193e refactor(markdown-editor): apply mechanical review batch (11 findings)
- M5: replace hand-rolled unknown-typed markdown types with the official
  @tiptap/core exports (MarkdownToken/ParseHelpers/RendererHelpers) and
  drop both casts they forced on the fidelity-critical paths
- M3: forward FormControl-injected id/aria-describedby/aria-invalid to the
  ProseMirror contenteditable (field<->label association + error announce)
- M2: skip the redundant whole-document re-parse on mount (compare against
  the captured initialContent instead of the normalized getMarkdown())
- L1+L10: extract the toolbar + isSafeImageSrc to markdown-editor-toolbar.tsx
  and memo() it (parent re-renders per keystroke under RHF)
- L2: delete dead autoFocus/hasToolbar props (zero consumers)
- L3: drop dead match.index narrowing (required number under es2023 lib)
- L4: own vite chunk for marked; drop stale tiptap-markdown chunk pattern
- L8: TunedStarterKit / TunedTable (consistent Tuned* prefix)
- L9: shouldExternalSync -> isExternalChange
- L14: isSafeImageSrc data: allowlist narrowed to base64 raster formats
  (data:image/svg+xml can carry script)
- L7: trim narration/restatement comments across module + tests

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-04 12:07:30 +07:00
Sergey KozyrenkoandClaude Opus 4.8 2b54a0a6b4 refactor(markdown-editor): review-driven quality pass (5 findings)
- content: capture the initial value via useState so useEditor's
  compareOptions no longer fires a redundant setOptions -> view.updateState
  on every keystroke; the value-sync effect stays the single owner of
  later content updates
- setEditable: guard on editor.isEditable to skip the redundant update +
  getMarkdown() serialization emitted on mount
- drop the unreachable `if (!manager) return` in TunedMarkdownText -- the
  Markdown extension always assigns editor.markdown; a non-optional cast now
  fails loud on regression instead of silently reverting to the lossy encoder
- rename param h -> helpers in renderTunedCodeBlock (matches sibling helpers)
- trim the variable-highlight banner to the load-bearing node/mark invariant

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-04 04:15:28 +07:00
Sergey KozyrenkoandClaude Opus 4.8 a858d81cea refactor(markdown-editor): rename Faithful* -> Tuned* (createTunedMarked etc.)
"faithful" connoted a byte-faithful round-trip, but the editor now deliberately
normalizes some cases toward GFM (bare URLs autolink, named entities decode), so
the output is no longer byte-exact. "tuned" names what the code actually does —
tune marked's tokenizers + the code-block/table serializers for our content —
without claiming a fidelity property the output no longer guarantees. Pure
rename (createFaithfulMarked/FaithfulMarkdownText/parse+renderFaithfulCodeBlock/
StarterKitFaithful -> Tuned), no behavior change; 834 tests green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-04 03:07:59 +07:00
Sergey KozyrenkoandClaude Opus 4.8 e4f80badd4 feat(markdown-editor): decode named HTML entities outside code instead of freezing them
The `literalAmpersand` extension pre-encoded every `&` so @tiptap/markdown's
decodeHtmlEntities netted to a no-op, keeping `&lt;`/`&gt;`/`&amp;`/`&quot;`
byte-verbatim. But bare-prose entities in the knowledge corpus are HTML-encoding
artifacts from ingestion (e.g. `Time difference &gt; 5 min` meaning `>`), and
freezing them as `&gt;` is not what the author wrote. Drop the extension so
marked decodes the 4 named entities in prose (`&lt;`->`<`, etc.).

Verified scoped and safe: numeric refs (`&#123;`, `&#40;`) and any entity inside
code / inline-code are NOT decoded (code content bypasses inline tokenizers), a
bare `&` survives as `&` (only valid entities decode), raw `<tags>` unaffected,
and the identity serializer keeps the decoded `<` from being re-encoded on save.
Full corpus (378 real knowledge docs): zero new non-convergence, zero
bare-&->&amp; regressions. Live on :8000: `&gt; 5 min` -> `> 5 min` on load+save
while numeric/code entities stay put.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-04 00:34:47 +07:00
Sergey KozyrenkoandClaude Opus 4.8 b73350ae2f feat(markdown-editor): autolink bare URLs/emails instead of freezing them as text
The faithful marked layer neutralised marked's `autolink`/`url` tokenizers so a
bare `https://…`, `<url>` or email round-tripped as literal text. That was a
deliberate byte-fidelity choice, but the product decision is now to let URLs
become links. Drop the two tokenizer overrides and flip the tiptap Link config
to `autolink/linkOnPaste: true` so load, paste and typing all linkify alike
(the typing==load invariant is preserved).

Verified: removing the two lines has zero collateral — `<input>`, `__init__`,
`\d+`, `&lt;` still round-trip byte-identical (handled by the other tokenizers),
and full-corpus convergence is unchanged (same 7/378 pre-existing non-convergent
docs with and without the change). URLs with `{PLACEHOLDER}` don't autolink;
URLs with balanced `$(…)` linkify and converge. Live on :8000: prose URLs render
clickable, code-block URLs stay literal, raw source stays byte-exact, load does
not dirty the form.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 22:32:30 +07:00
Sergey KozyrenkoandClaude Opus 4.8 db9b832f48 docs(markdown-editor): trim a narration comment + pin the shared-editorRef assumption
- Drop the insertAtCursor 'focus before scroll (same as cycleToVariable)' comment — the
  gotcha is already documented at cycleToVariable's focus() 15 lines up; the parenthetical
  was pure back-reference narration (report comment-audit).
- settings-prompt: document why one editorRef is shared by both prompt tabs (Radix unmounts
  the inactive TabsContent, so only one editor mounts) and what would break it (F12).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 11:51:27 +07:00
Sergey KozyrenkoandClaude Opus 4.8 968d5f85d2 refactor(markdown-editor): make the barrel tiptap-free so lazy(MarkdownEditor) is real (L1)
index.ts re-exported the heavy MarkdownEditor value, so any route statically importing
a light util from the barrel (settings-prompt / template import EditorViewModeToggle +
the variable probes) pulled the 527KB tiptap chunk into its eager graph — defeating
their lazy(() => import(MarkdownEditor)). Extract the pure {{ }} helpers (VARIABLE_RE,
variableProbe, findVariableUseRanges) into markdown-editor-variable-syntax.ts (no
tiptap), export only light utils + the erased Handle type from the barrel, and import
MarkdownEditor directly from its module (static in knowledge-form-controls, dynamic in
the two lazy routes). Verified at build-artifact level: settings-prompt/template chunks
now have ZERO static import of the tiptap/markdown-editor chunks — they reference the
editor only via import("./markdown-editor-…"). tsc + lint + build + 831 vitest green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 11:49:38 +07:00
Sergey KozyrenkoandClaude Opus 4.8 996fcf49fa fix(markdown-editor): drive toolbar state via useEditorState (M4)
tiptap v3's useEditor does not re-render the component on every transaction, so the
toolbar's 16 editor.isActive()/can() reads went stale on selection-only cursor moves
— click into a bold word and the Bold button stayed unlit until the next doc edit.
Read all button states through a single useEditorState selector, which re-runs per
transaction and re-renders only when a state flips. Fixes the staleness and drops the
incidental full re-render. Idiomatic tiptap v3 pattern.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 11:42:34 +07:00
Sergey KozyrenkoandClaude Opus 4.8 e324db3488 test(markdown-editor): assert cycleToVariable actually advances the selection (F7)
The handle test asserted only cycleToVariable's boolean return, so a regression to
'always select hits[0]' would stay green. jsdom has no layout, so the selection can't
be read directly — but insertAtCursor replaces the SELECTED range, making the target
observable: cycle twice, insert, and assert the SECOND occurrence (not the first) was
replaced. Distinguishes real advancement from a stuck-on-first regression.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 11:39:13 +07:00
Sergey KozyrenkoandClaude Opus 4.8 0d862d1e18 refactor(markdown-editor): fix false comments, simplify setContent, dedup wrapper (L2/L4/L5/L6/F9)
- L2: the value-sync comment claimed setContent doesn't honor contentType — false for
  @tiptap/markdown 3.27.1 (dist setContent parses via editor.markdown.parse). Collapse
  the manual parse+setContent to setContent(value,{contentType:'markdown',emitUpdate:false});
  verified byte-identical across 45 inputs (39 .tmpl + edge cases).
- L4: isSafeImageSrc comment overstated 'for saved content' — it guards only the toolbar
  button; load/paste bypass it (inert; viewer sanitizes on render). Comment corrected.
- F9: the table pipe-escape comment implied the load path was handled — clarified it is
  save-side only; a raw pipe in inline code on LOAD is a marked-tokenizer limitation.
- L5: hoisted the duplicated ~200-char wrapper className to WRAPPER_CLASS.
- L6: dropped the dead MarkdownEditorProps barrel export (+ its now-dead export keyword).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 11:35:45 +07:00
Sergey KozyrenkoandClaude Opus 4.8 b7012ee2af test(markdown-editor): add structure-count invariant + nested-composition coverage (M2, M3)
The round-trip tests asserted idempotence + word-multiset but not STRUCTURE, so a
word-preserving structural downgrade (a code block splitting, a dropped list item)
converged and passed green — the exact reason M1 shipped invisible. Add
structuralCounts() (structural node types, paragraph/text excluded as benign reflow)
and assert it in the corpus test (all 39 .tmpl) and a new generative nesting test that
composes primitives to depth ≥2 (ordered>bullet>code, blockquote>list, fence-in-fence)
— the historical drop class, now structure-preserving after the indented-fence + M1
fixes. Updates the stale 'ordered>bullet>code NOT generated' comment.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 11:31:22 +07:00
Sergey KozyrenkoandClaude Opus 4.8 15fab1b405 fix(markdown-editor): widen code-block fence past inner backtick runs (M1)
@tiptap/extension-code-block's renderMarkdown always emitted a 3-backtick fence, so
a code block whose content contains a ``` line (a doc demonstrating fenced markdown)
re-parsed as TWO blocks on the next load — the inner fence closed the outer. Override
renderMarkdown to widen the fence to longer than any backtick run inside (CommonMark).
Regression test: the nested-fence doc now stays one codeBlock and converges.

Also documents (with a pinned test) the sibling F2 case — a backtick INSIDE inline
code — as a genuine upstream limitation: @tiptap/markdown derives a mark's delimiter
from a fixed placeholder (getMarkOpening/getMarkClosing), so unlike a node it can't be
content-aware; the reviewer's suggested mark renderMarkdown override is a no-op
(verified against dist). Fixes the stale editor-markdown.ts pointer (L3).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 11:27:01 +07:00
Sergey KozyrenkoandClaude Opus 4.8 ed6b779395 style(frontend): fix prettier drift blocking CI
CI runs prettier --check over src/**; 10 files failed. The markdown-editor module
(7) + settings-prompt (1) drifted this session (eslint --fix was run without a
prettier pass after the rename/barrel + dep edits); knowledge-form-blocker.test /
knowledge-form.test (2) were pre-existing drift from an earlier commit. prettier
--write all; no logic change.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 11:20:17 +07:00
Sergey KozyrenkoandClaude Opus 4.8 8c67ed29fe test(markdown-editor): extract shared jsdom setup + roundTrip helper
The 7-line jsdom polyfill (elementFromPoint + Range rects, needed for any editor
mount) was byte-identical across 7 test files, and the parse↔serialize roundTrip
harness re-declared in 3. Extract both into markdown-editor-test-setup.ts
(setupEditorJsdom + roundTrip); each test now imports them, killing the copy-paste
and the silent-drift risk if the required stubs change.

tsc + lint + full vitest (826) green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-02 16:00:37 +07:00
Sergey KozyrenkoandClaude Opus 4.8 b9130d2a6c test(markdown-editor): cover the imperative handle + value sync
Component-level test (renders MarkdownEditor with a ref, reusing the jsdom
elementFromPoint/Range polyfills): cycleToVariable rejects a missing variable and
cycles/wraps an existing one without throwing; insertAtCursor emits the inserted
text through onChange; and the value-sync path suppresses onChange for an echoed
value while applying a real external change to the editor content. Exercises the
previously-buggy imperative-handle orchestration that composes the (individually
covered) findVariableOccurrences / resetUndoHistory pieces.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-02 15:56:06 +07:00
Sergey KozyrenkoandClaude Opus 4.8 3004d94226 test(markdown-editor): cover isSafeImageSrc image-src allowlist
Export isSafeImageSrc (was module-private, so no test could reach the folder's only
security guard) and add an it.each unit test: allows http(s):// and data:image/*,
rejects javascript:, data:text/html, data:application/*, vbscript:, file:, and a
malformed URL (catch branch). Note: a bare relative string resolves to the page
origin and is intentionally allowed — the guard blocks dangerous protocols, not
non-absolute URLs (verified against the actual implementation, not assumed).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-02 15:53:07 +07:00
Sergey KozyrenkoandClaude Opus 4.8 b59de20556 refactor(markdown-editor): drop dead export + trim duplicated comment
- FaithfulMarkdownText: drop the `export` — it has zero importers, used only
  inline by createMarkdownLayer in the same file (its sibling createFaithfulMarked
  is already a private const).
- markdown-editor.tsx: remove the reset-history tail comment that restated verbatim
  the invariant already in resetUndoHistory's header (lines 52-53); the 'when it
  fires' explanation above it stays.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-02 15:50:50 +07:00
Sergey KozyrenkoandClaude Opus 4.8 c699c152a3 refactor(markdown-editor): standardize file prefix + add index barrel
The folder was the only shared/ folder mixing editor-* and markdown-editor-*
prefixes and lacking an index.ts barrel (all 6 siblings use the full folder-name
prefix + a barrel). Rename every non-entry module to markdown-editor-* (editor-markdown
-> markdown-editor-marked names its subject better), add an index.ts exporting the
public surface (MarkdownEditor + types, EditorViewMode/Toggle, the variable-highlight
probes), and migrate all 6 consumers off deep imports onto the barrel so future
renames stay internal.

tsc + lint + build + full vitest (813) green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-02 15:49:25 +07:00
Sergey KozyrenkoandClaude Opus 4.8 ebdf8b012e chore(frontend): replace lodash/debounce with use-debounce, drop lodash
The 8 flow-view search inputs used lodash/debounce via useMemo(()=>debounce(fn,500))
+ .cancel() cleanup. Swap to useDebouncedCallback(fn,500) from use-debounce — already
the repo idiom (data-table, input-search, use-table-state) with identical
leading:false/trailing:true semantics and the same .cancel() API. Drops lodash +
@types/lodash (a whole general-purpose lib kept for one function).

tsc + lint + build + full vitest (813) green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-02 14:21:33 +07:00
Sergey KozyrenkoandClaude Opus 4.8 54ac6c4adb chore(frontend): consolidate icons onto lucide-react, drop @radix-ui/react-icons
The 7 base UI components still on @radix-ui/react-icons now use lucide-react
(already the dominant icon lib, ~79 files). 1:1 name map: Cross2->X,
DragHandleDots2->GripVertical, Chevron{Down,Right,Up}, DotsHorizontal->MoreHorizontal,
MagnifyingGlass->Search, Check, DotFilled->Circle (kept a small filled dot for the
radio indicator via h-2 w-2 fill-current). One icon library instead of two.

tsc + lint + build + full vitest (813) green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-02 14:17:24 +07:00
Sergey KozyrenkoandClaude Opus 4.8 7315a9f99f chore(frontend): drop redundant-direct tiptap subs + dead vaul/drawer
- @tiptap/extension-{code,code-block,hard-break}: bundled transitively by
  @tiptap/starter-kit, never imported directly in src — remove the redundant
  top-level pins (functionality unchanged, editor tests 161/161 green).
- vaul + src/components/ui/drawer.tsx: dead shadcn wrapper with zero consumers.

tsc + lint + build + editor suite all green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-02 14:13:29 +07:00
Sergey KozyrenkoandClaude Opus 4.8 de6859d935 fix(editor): keep indented fenced code blocks on load
@tiptap/extension-code-block's parseMarkdown gates on token.raw.startsWith('```'),
but CommonMark lets a fenced code block's opening fence be indented up to 3 spaces.
marked emits a valid code token whose raw then starts with that whitespace, so the
gate rejected it and the block was dropped on load. When a document mixed fence
indents the mis-detection cascaded and silently deleted everything after the first
dropped fence — a real knowledge doc lost 556 words (its entire second half) this way.
Override the codeBlock parseMarkdown to trim the leading indent before the gate;
otherwise identical to upstream. Also fixes the previously-pinned ordered>bullet>code
drop (same root cause) and recovers ~583 words across the 366-doc knowledge corpus.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-02 12:58:47 +07:00
Sergey KozyrenkoandClaude Opus 4.8 647e28a48e test(editor): rename armed flag to isArmed per boolean-naming rule
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-02 02:27:17 +07:00
Sergey KozyrenkoandClaude Opus 4.8 c4eb983c44 fix(editor): make placeholder mount-only instead of a dead reactive dep
extensions was memoized on [placeholder], implying a live placeholder update,
but useEditor runs with empty deps and tiptap's setOptions merges options
without re-registering extensions — so a changed placeholder never reaches the
already-installed Placeholder plugin (verified: data-placeholder stays at the
mount value across a prop change). Drop placeholder from the deps to match the
autoFocus mount-only decision, removing the misleading reactivity signal and the
per-change rebuild of the whole extension array.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-02 02:26:34 +07:00
Sergey KozyrenkoandClaude Opus 4.8 4ddb76f9ff test(editor): make content-integrity catch backslash-punct load loss
The generative oracle shipped green over the escape-tokenizer bug: its atoms
held only backslash-before-letter (which survives), and both oracles are too
weak for a first-load loss — survives/includes never ran on the missing class,
and convergence passes because the drop happens once then stabilizes. Add
backslash-before-punctuation atoms to the generative pool and a direct
byte-exact source-fidelity assertion for the escape class (regex/glob/UNC/
line-leading star), which is strictly stronger than survives+converges.

Fails on the pre-fix escape-active parser, passes on the neutralized one.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-02 02:24:36 +07:00
Sergey KozyrenkoandClaude Opus 4.8 f04c9da10f fix(editor): keep backslash-escaped punctuation literal on load
createFaithfulMarked neutralized marked's del/emStrong/html/tag/autolink/url
tokenizers but left `escape` active, so marked dropped the backslash before any
CommonMark punctuation on the first load — corrupting regex `\.`, globs `\*`,
UNC paths `\\`, escaped `\[`/`\|` in real knowledge docs. A serialize-side
re-escape cannot recover a byte already gone from the doc model.

Neutralize `escape` too, so a source `\.` stays literal `\.`. With no escape
decoded on parse, the serialize side must emit text verbatim rather than
re-escaping (which would resurface as a literal backslash on the next load), so
encodeTextForMarkdown collapses to identity — load and save stay byte-symmetric.

Verified over the 405-sample corpus (39 templates + 366 knowledge): backslash-
punct loss 5 samples -> 0, byte-identical 104 -> 106, word-loss unchanged; 15
adversarial inline cases and table pipe cells round-trip clean.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-02 02:22:41 +07:00
Sergey KozyrenkoandClaude Opus 4.8 4d1e1161ee test(editor): regression-cover the mismatched-transaction list crash
Exports resetUndoHistory and drives it with a synthetic plugin that advances
view.state during the reconfiguring updateState — reproducing the exact
"Applying a mismatched transaction" RangeError in jsdom. Fails on the pre-fix
newState.tr, passes on the live-view.state.tr fix, so a future revert can't
silently reintroduce the production-only crash.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-02 00:00:46 +07:00
Sergey KozyrenkoandClaude Opus 4.8 6457a5a86a fix(editor): derive undo-reset poke transaction from live view.state
resetUndoHistory dispatched newState.tr after view.updateState(newState).
updateState can synchronously advance view.state (a plugin view or tiptap's
deferred initial-content transaction firing during reconfigure), leaving the
stale tr's before-doc mismatched against the current doc — ProseMirror then
throws "Applying a mismatched transaction". This crashed the editor detail
page for ANY document containing a list, but only in the production build
(React StrictMode's dev double-mount masked the timing). Build the wake-up
transaction from the live view.state instead, whose before-doc is the current
doc by construction.

Live side-by-side verified on the docker prod build: the same list document
that hit the error boundary now renders; full torture doc keeps all atoms.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-01 19:59:18 +07:00
Sergey KozyrenkoandClaude Opus 4.8 c0ac3d6f90 test(editor): generative content-integrity round-trip + correct the code-drop comment
Add a seeded generative round-trip test (300 random docs combining every
content atom — dunders, {{.vars}}, <tags>, regex/path backslashes, HTML
entities, C++ — across paragraph/heading/list/quote/inline-code contexts):
asserts convergence and that no atom is dropped, catching combination-only
regressions the per-atom byte tests can't. Also correct the ordered>bullet>code
pinned-bug comment: marked keeps the code token; the drop is in
@tiptap/markdown's list reconstruction, not the marked parser.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-01 18:49:25 +07:00
Sergey KozyrenkoandClaude Opus 4.8 2e59e9e122 fix(editor): keep literal HTML entities (&lt; &amp; &gt; &quot;) on load
@tiptap/markdown runs a module-scope decodeHtmlEntities on every text token
during parse, so a pentest doc that stores literal `&lt;script&gt;` (teaching
the encoded form) loaded as raw `<script>`, and `AT&amp;T` as `AT&T`. Its
`.lexer()`/`.inlineTokens()` path never routes through marked's walkTokens or
hooks, so add a private-instance inline extension that emits each `&` as its
own text token pre-encoded to `&amp;`; the decode then nets back to the
original byte, keeping the entity literal. Code tokens are untouched (decode
skips them) and literal `<tags>` still pass through unencoded.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-01 18:44:14 +07:00
Sergey KozyrenkoandClaude Opus 4.8 b7e4dea1a2 fix(editor): disable Underline + underscore/URL auto-format so typing matches load
Three StarterKit defaults corrupted content or diverged from the load path:
- Underline (`underline: false`): its `++text++` markdown tokenizer collapsed
  the space in `C++ then C++` on load, and Ctrl+U emitted non-standard `++`.
  No underline semantics in our content, so drop it outright.
- Bold/Italic underscore input+paste rules: typing `__init__`/`_word_` created
  emphasis (`**init**`/`*word*`) while the same text loaded stays literal (the
  marked layer neutralizes `_`), breaking identifiers on the typing path only
  (input rules don't run on paste/load). Extend StarterKit to drop the
  underscore rules (regex mentions `_`), keeping the `*`/`**` rules.
- Link autolink/linkOnPaste (`false`): a typed/pasted bare URL now stays
  literal, matching load; explicit [text](url) and the toolbar still work.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-01 18:37:59 +07:00
Sergey KozyrenkoandClaude Opus 4.8 18041520c3 fix(editor): stop doubling literal backslashes on save
faithfulEscape backslash-escaped every `\`, so a save doubled regex classes
(\d -> \\d) and Windows paths (C:\Users -> C:\\Users) — 210/366 knowledge
docs carry such content. marked only treats `\` as an escape when it
precedes a CommonMark-escapable punctuation char; a `\` before a
letter/digit/space is literal. Escape a `\` only in that punctuation case,
leaving content backslashes verbatim.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-01 18:30:29 +07:00
jinhaosong-source 2abeecbc63 Add OrcaRouter pre-configured provider config 2026-07-01 19:29:48 +08:00
Sergey KozyrenkoandClaude Opus 4.8 5abfede29a test(editor): cover markdown-on-paste (decision branches + parsed payload)
Extract the paste decision into a pure `shouldParseMarkdownOnPaste` and
test all branches (plain text parses; empty, in-editor copy, block-tag
HTML, and code-context defer; styled-inline HTML still parses). Plus
integration over the real handler: pasted block markdown becomes rich
blocks, `_`/`__` stay literal like load, and rich block HTML defers to
ProseMirror.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-01 16:16:12 +07:00
Sergey KozyrenkoandClaude Opus 4.8 d4c0880405 fix(editor): point the corpus test at the moved fixture path
The folder move nested the corpus test one level deeper, so its relative
walk to backend/pkg/templates/prompts needs one more `..`. The fix landed
in the working tree (tests were green locally) but missed the move commit's
staging, so HEAD carried the pre-move path.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-01 15:47:11 +07:00
Sergey KozyrenkoandClaude Opus 4.8 3b3c4cf7bd feat(editor): parse markdown on paste so paste matches load
@tiptap/markdown only parses markdown for initial content / insertContent,
never for the clipboard — so pasting block markdown (headings, lists,
tables, quotes, fences) landed as literal text while only StarterKit's
inline mark paste-rules fired, and `_`/`__` formatted on paste even though
load keeps them literal. Add a MarkdownPaste extension that routes
plain-text pastes through the same faithful markdown layer as load, so the
two are consistent. Rich sources keep ProseMirror's own fidelity: an
in-editor copy (data-pm-slice) and web/Office HTML (block tags) fall
through to the default path, and pastes inside code stay literal.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-01 15:45:51 +07:00
Sergey KozyrenkoandClaude Opus 4.8 4e11fd96a4 refactor(editor): group the markdown-editor files under one folder
Move the 10 round-trip editor files (markdown-editor, its extensions, the
marked layer, inline-scan, tag/variable highlights, view-mode toggle, and
their tests) from components/shared/ into components/shared/markdown-editor/.
Consumers now import from the folder path; internal cross-references stay
relative. The read-only markdown viewer (markdown.tsx) stays put — it is a
react-markdown renderer, not part of the editor. Corpus test walks up one
more level to reach the backend prompt fixtures.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-01 15:15:43 +07:00
Sergey KozyrenkoandClaude Opus 4.8 cab4bde25c feat(prompts): always show both prompt tabs, disable Human when absent
Tool prompts (and agents without a human template) rendered a lone
"System Prompt" tab, which looks unbalanced. Always render both tabs and
disable the Human tab when the prompt has no human template
(hasHumanPrompt = agent && hasHuman), so it greys out at 50% opacity
instead of vanishing.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-01 14:48:53 +07:00
Sergey KozyrenkoandClaude Opus 4.8 b8ec524c87 fix(editor): scope the System/Human prompt tabs restyle to dark mode
Same light-mode collapse as the view toggle: an unconditional
bg-background track + bg-card active render as white-on-white in light
(background == card == popover), hiding the track. Scope both to dark
(dark:bg-background, dark:data-[state=active]:bg-card) so light falls back
to the default bg-muted track + bg-background active.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-01 14:36:30 +07:00
Sergey KozyrenkoandClaude Opus 4.8 d08f4ee780 fix(editor): light-mode track for the view toggle, drop its row hover
The dark-only restyle set an unconditional bg-background track + bg-card
active, which collapse to the same white in light mode (background ==
card == popover), so the segmented track vanished. Scope the raised
treatment to dark (dark:bg-background track, dark:data-[state=active]:bg-card)
and let light fall back to the default bg-muted track + bg-background
active. Same fix on the Theme picker. Also silence the hover/focus
highlight on the View row so it reads as a control host, not an action —
matching the Theme row.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-01 14:26:55 +07:00
Sergey KozyrenkoandClaude Opus 4.8 a63a48db44 refactor(editor): reposition the view toggle and restyle its segments
Move the "View" row to the bottom of each actions dropdown — directly
above Delete when a Delete row exists, otherwise last. Swap the segment
icons to SquareMenu (rich editor) and Type (raw source), and give the
segmented control a dark-friendly treatment (bg-background track with a
bg-card active segment, matching the System/Human prompt tabs) so the
active segment reads as raised on dark. Apply the same treatment to the
Theme picker in the sidebar for consistency.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-01 14:08:43 +07:00
Sergey KozyrenkoandClaude Opus 4.8 15d8026180 refactor(editor): standardize view mode as Rich/Raw segmented toggle
Replace the ad-hoc per-surface view-mode enums (`code`/`plain`,
`visual`/`plain`) and dropdown-item toggles with one shared
`EditorViewMode = 'raw' | 'rich'` type and an `EditorViewModeToggle`
segmented control (matching the Theme picker in main-sidebar). Applied
across all three editing surfaces: prompts, templates, and knowledge.
Rich is the default everywhere.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-01 11:26:03 +07:00
Sergey KozyrenkoandClaude Opus 4.8 55335cccbe fix(editor): keep bare URLs and emails literal (no autolink rewrite)
marked's url/autolink tokenizers wrapped a bare https://…, <url> or email in
[text](text) on save — a content-changing rewrite of prompt/template/knowledge
prose. Neutralize both (same pattern as the html/tag/del/emphasis tokenizers);
explicit [link](url) and ![image](url) still work via the untouched link
tokenizer. Pinned by byte-identity tests.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-01 10:24:38 +07:00
Sergey KozyrenkoandClaude Opus 4.8 d652585e36 fix(editor): validate image src protocol before insert (defense-in-depth)
The Image toolbar passed window.prompt output straight to setImage; unlike the
link path, the Image extension does not validate the protocol, so a
javascript:/data:text/html src was stored. Not active XSS (the viewer strips it),
but a stored-content hygiene gap. Reject non-http(s)/non-image-data URLs before
setImage.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-01 09:38:45 +07:00
Sergey KozyrenkoandClaude Opus 4.8 1386f5e747 test(editor): corpus asserts a word multiset, not a Set
The corpus fidelity check compared word Sets, so a count drop / duplication /
reorder passed as long as each distinct word survived once. Assert the sorted
word multiset instead (the real guard the reviews flagged as degraded). Keep the
existing <=2-save convergence check — some templates canonicalize over two saves,
so save1 === save2 would be stricter than the codebase's contract.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-01 09:38:44 +07:00
Sergey KozyrenkoandClaude Opus 4.8 67b6521f9f fix(settings/prompt): keep the other tab's unsaved edits on save (keepDirtyValues)
The promptInfo-sync effect unconditionally reset BOTH the System and Human forms
on every promptInfo identity change, and neither useForm set keepDirtyValues. A
Save refetches settingsPrompts → promptInfo gets a new identity → the effect fires
→ the inactive tab's unsaved edits were silently wiped. This is the exact M3
data-loss class already fixed in template.tsx/knowledge-form.tsx, left unfixed in
this sibling. Add resetOptions.keepDirtyValues to both forms.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-01 09:38:44 +07:00
Sergey KozyrenkoandClaude Opus 4.8 81c7eaf3d2 fix(editor): keep _-delimited text literal so dunders survive the round-trip
marked's emphasis tokenizer fires on `_`, so `__init__`/`_word_` parsed to
strong/em marks and re-serialized as `**init**`/`*word*` — the underscores were
gone by serialize time (a serialize-side escape can't recover them). Two
external reviews reproduced this at DB level on real knowledge content. Neutralize
the `_` case of marked's emStrong tokenizer (defer `*`/`**` to the default, which
the toolbar emits) so Python dunders, snake_case and `_`-wrapped prose round-trip
verbatim; `*`/`**` emphasis is unaffected. Pinned by byte-identity tests.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-01 09:38:44 +07:00
Sergey KozyrenkoandClaude Opus 4.8 fef780de71 chore(editor): trim review-flagged restatement comments
Post-review comment hygiene: drop the editor-highlight-regex test header that
restated the describe/it names; drop the diffStyles "Tailwind vars" comment (the
satisfies type + name already convey it, and it mislabeled the one hard-coded
green); trim the knowledge-form performSave comment to its load-bearing half (the
backend trims/normalizes). The (M1) test-name tag was dropped with the
single-tilde test rename.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-01 07:06:00 +07:00
Sergey KozyrenkoandClaude Opus 4.8 f25c26d7d5 fix(editor): only treat ~~ as strikethrough so single-tilde prose survives
marked's GFM del tokenizer accepts a single ~text~ as strikethrough, so prose
like "from ~5~ to ~10~" parsed into <del> and re-serialized as ~~5~~ —
corrupting ranges/paths in prompt/template/knowledge content. Neutralize the
single-tilde case in createFaithfulMarked (defer real ~~ to the default
tokenizer, drop a lone ~…~ to literal text), symmetric with the html/tag
neutralization already there. Double-tilde ~~strike~~ (the toolbar feature) is
unaffected.

Pinned by byte-identity tests for ~x~ pairs; the 366+39 corpus still converges.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-01 07:04:31 +07:00
Sergey KozyrenkoandClaude Opus 4.8 f68964f52e fix(templates): skip the unsaved-guard blocker on the post-create navigation
The M3 unsaved-changes guard trapped the user after a successful CREATE: a new
template's form stays dirty (performSave reset only on the update branch) and
handleSubmit navigated to the list without telling the guard the navigation was
intentional, so useBlocker intercepted it and popped the "Unsaved changes"
dialog right after the template was saved. Move handleSubmit below the guard and
call guard.skipNextBlock() before navigate (mirroring knowledge-form).

Live-verified side-by-side: before — create stuck on /new with the dialog;
after — create lands on the list, no dialog.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-01 00:29:54 +07:00
Sergey KozyrenkoandClaude Opus 4.8 768d733c88 chore(editor): trim review-flagged comments that restate or narrate
Drop comments that restate the code or narrate a test assertion: the value-sync
intro (the skip-echo block below already explains it), the two PM descendants
return-value notes, the marked-cast type trivia, the 6-line aria-label essay,
the corpus-test harness/per-assertion narration (the it() title already lists
the checks), and two table/nesting assertion labels. Tightened the knowledge-form
"server's canonical document" note to its load-bearing line.

Kept the genuinely load-bearing ones the pass also flagged: the performSave
navigation/cycle warning (removing it invites reintroducing the guard cycle) and
the test "sanity" assertions (they prove the split/hard-break case is exercised).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-30 22:15:02 +07:00
Sergey KozyrenkoandClaude Opus 4.8 7c8f017b27 refactor(layouts): extract DetailTwoPanelLayout, consume in the 4 detail pages
The desktop two-panel resizable shell (outer flex, ResizablePanelGroup, left
45/30 panel + scroll + Card, GripVertical handle, right 55/30 panel) was
copy-pasted byte-identical across knowledge-form-layout, template,
settings-prompt and settings-provider. Extract a presentational
DetailTwoPanelLayout({left, right, rightClassName?}); the only per-page variance
is the right pane's inner className, exposed as an optional prop. Net -44 lines.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-30 22:00:39 +07:00
Sergey KozyrenkoandClaude Opus 4.8 2ee3d6ecf9 fix(knowledges): make the Plain/Visual toggle reachable on a new document
The Plain/Visual DropdownMenuItem sat inside the `canShowActions` (!isNew)
block, and the dropdown trigger itself was gated the same way, so a brand-new
knowledge doc was locked to the visual editor until first save — inconsistent
with templates, where the toggle is outside that gate. Move the toggle out of
`canShowActions` (Rename/Delete still require a saved doc) and show the trigger
whenever a toggle handler is supplied.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-30 21:47:36 +07:00
Sergey KozyrenkoandClaude Opus 4.8 501473ba5a refactor(settings/prompt): hoist the static diffStyles object to module scope
diffStyles is a ~40-key constant (only literals + CSS var strings, no closure
over props/state) that sat in the component body. Lift it to module scope so it
is defined once, with a `satisfies` clause for the ReactDiffViewer styles type.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-30 21:47:25 +07:00
Sergey KozyrenkoandClaude Opus 4.8 992302b3d7 fix(templates): stop a cache re-emit from wiping unsaved body edits
The page reset({text,title}) in an effect on every templateData change. Since
UpdateFlowTemplate returns the flowTemplateFragment, an inline title rename
normalizes the Apollo cache → the FlowTemplate query re-emits → the effect
refired → reset() clobbered the user's unsaved editor body. Switch to the
knowledge-form pattern: reactive `values` + resetOptions.keepDirtyValues, which
re-syncs server changes while preserving in-flight edits; delete the manual
reset-in-effect. Also add useUnsavedChangesGuard + UnsavedChangesDialog (the
page was the only detail page without navigate-away protection) and switch
mode onChange→onTouched (no full-schema zod on every editor keystroke).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-30 21:08:25 +07:00
Sergey KozyrenkoandClaude Opus 4.8 d3d0a0f955 fix(editor): kill ReDoS in the variable cycle — block-first instead of lazy regex
variableUseRegex built `{{[^{}]*?\.Name\b[^{}]*?}}` with two lazy spans; on an
unclosed `{{` with many `.Name` anchors it backtracked O(n²) (measured 25KB 49ms
/ 100KB 782ms / 250KB 4.9s — a multi-second main-thread freeze from one
variable-panel click). The panel COUNT path already extracted `{{…}}` blocks
linearly via VARIABLE_RE then probed each; apply the same block-first shape to
the two CYCLE consumers (findVariableOccurrences for the editor, the plain-mode
textarea cycle in settings-prompt) via shared findVariableUseRanges/variableProbe.
Same inputs now 0.16/0.21/0.48ms (~10000x at 250KB). Also escape the interpolated
variable name (a `.` in a name would otherwise match any char). Drop the dead
variableUseRegex; re-add InlineMatch.text so the doc scan can probe per block.

Pinned by a linear-time regression test on the pathological input + an escape
test; de-stales the editor-highlight-regex test header (scan is per-textblock
since 69f86ae, not per-text-node).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-30 21:01:11 +07:00
Sergey KozyrenkoandClaude Opus 4.8 443fcc90ee fix(editor): stop escaping a lone ~ so Go-template prose round-trips byte-exact
faithfulEscape backslash-escaped every ~, but in GFM only ~~ is strikethrough —
a lone ~ is literal. Escaping it injected a stray \ into prompt prose (e.g.
~10%/~30% in generator.tmpl + refiner.tmpl), and since the editor's getMarkdown
output is the Go text/template stored and sent to the LLM, the \ shipped to the
model. Escape ~ only in runs of 2+ (a balanced ~~strike~~ is handled by the
Strike mark upstream and never reaches this path); backtick/backslash unchanged.

Pinned by byte-identity tests for lone tildes (the corpus test asserts only
word-multiset + convergence, so \~ slipped through).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-30 20:09:58 +07:00
Sergey KozyrenkoandClaude Opus 4.8 7a96d9dbd4 refactor(editor): rename show{Label,Toolbar} -> has{Label,Toolbar}
Boolean presence flags use the has* prefix per the project naming convention.
showToolbar (MarkdownEditor) had no external callers; showLabel had one
(knowledge-form-layout) — renamed both together to stay consistent.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-30 13:41:38 +07:00
Sergey KozyrenkoandClaude Opus 4.8 52ec6667b6 chore(editor): trim comments that restate code or defend implementation
Review follow-ups:
- knowledge-form.tsx: drop the DirtyFlags comment (restates the type) and the
  "backend also wipes subtypes" parenthetical (defends a redundant path).
- markdown-editor-extensions.test.ts: drop the roundTrip narration.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-30 13:21:54 +07:00
Sergey KozyrenkoandClaude Opus 4.8 26441bfd5a refactor(editor): drop redundant callback refs, memoize extensions, trim comments
Review follow-ups on markdown-editor.tsx:
- drop onChangeRef/onBlurRef + their sync effect: tiptap invokes onBlur/onUpdate
  via its own live options ref (`mostRecentOptions.current = options` every
  render, @tiptap/react 3.27.1), so the closures already see the latest props —
  call onChange/onBlur directly.
- memoize createMarkdownExtensions(placeholder) so it isn't rebuilt per render.
- trim three paragraph-length ref comments + the resetUndoHistory tail to their
  load-bearing kernel.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-30 13:20:04 +07:00
Sergey KozyrenkoandClaude Opus 4.8 bb695df721 fix(editor): map token end so a hard break inside {{.Var}}/<tag> spans fully
collectInlineMatches derived `to = from + match.length`, which undershoots
when a non-text inline node (a hard break from Shift+Enter) sits inside a
{{...}} or <tag> token: the highlight decoration and the cycle/select then
land one char short (off by the node's size). Read `to` from the per-character
position map instead. View-only — getMarkdown() was already byte-identical.

The module comment asserted the opposite (false) invariant; corrected. Test
inserts a hard break inside a token.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-30 12:58:04 +07:00
Sergey KozyrenkoandClaude Opus 4.8 69f86ae566 fix(editor): mark-boundary-safe inline scan shared by highlights + cycle
A {{.Var}} (or <tag>) split across text nodes by a mark — e.g. a user
styles one brace — was missed by the per-text-node scan: the cycle then
inserted a duplicate while the panel still counted it used, and the
highlight silently dropped on the fragment.

- new collectInlineMatches (editor-inline-scan.ts) scans each textblock's
  concatenated inline text and maps offsets back to doc positions, so a
  split token reunites in one block string.
- VariableHighlight, TagHighlight and findVariableOccurrences all use it.
- share one variableUseRegex + VARIABLE_RE between the editor and
  settings-prompt (countVariableUses + the plain-mode cycle), replacing the
  hand-synced duplicate regexes.
- test: a brace-styled {{.Foo}} is now found (was 0 before).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-30 12:17:33 +07:00
Sergey KozyrenkoandClaude Opus 4.8 55f105ffa1 fix(editor): focus before scroll in insertAtCursor + drop dead handle methods
insertAtCursor dispatched scrollIntoView before view.focus() — the reverse
of cycleToVariable — so the first post-load variable insert (fired from a
button outside the editor, before it is focused) would not scroll the
inserted text into view. Reorder to match cycleToVariable.

Also drop the unused getEditor() and focus() from MarkdownEditorHandle:
the only callers are cycleToVariable + insertAtCursor (verified by grep).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-30 06:25:59 +07:00
Sergey KozyrenkoandClaude Opus 4.8 e29582958d feat(editor): cycle through variable uses in the tiptap variable panel
The "Available variables" panel could insert {{.X}} but, in the rich
(tiptap) editor, could not jump to an existing use the way the plain
textarea already did — the used-highlight + go-to-next were plain-only,
which read as a regression.

- cycleToVariable on MarkdownEditorHandle: finds {{.var}} occurrences in
  the doc and selects + scrolls to the next one; returns false when there
  are none so the caller inserts instead (cycle-or-insert contract).
- findVariableOccurrences (editor-variable-highlight.ts): the doc scan,
  position-mapped to match the VariableHighlight decoration.
- panel isUsed = count > 0 in BOTH modes; handleVariableClick cycles when
  the variable is used, inserts when not.
- focus before scrollIntoView: ProseMirror no-ops scrollToSelection on an
  unfocused view, so the first post-load click would otherwise not scroll
  (looked like a lost/double click).
- perf: the value-sync effect re-serialized the whole ~24KB doc twice per
  keystroke only to no-op on self-echo; early-return when value is our own
  last-emitted output (mount + real external form.reset still sync).
- tests: findVariableOccurrences span/word-boundary/unused cases.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-30 06:23:12 +07:00
Sergey KozyrenkoandClaude Opus 4.8 fb1c15926f chore(deps): dedup marked to one v18 via pnpm override
@tiptap/markdown pins marked ^17 while our direct dep (report-pdf + the
editor's parser instance) is ^18, so two marked copies were installed and
the marked config needed an `as never` to bridge the version skew.

Add `overrides: { marked: ^18.0.5 }` so @tiptap/markdown resolves onto v18
too — one copy. Behaviourally a no-op for the editor (it already passed a
v18 Marked instance to the MarkdownManager; only @tiptap/markdown's unused
default + types change, and the lexer API is identical 17↔18). Narrow the
createMarkdownLayer cast from `as never` to a typed cast now that the
versions match.

Verified on the forced v18: tsc, 747 vitest, lint, production build green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-30 01:22:05 +07:00
Sergey KozyrenkoandClaude Opus 4.8 7e6410debf refactor(editor): apply review follow-ups (history-key identity, narrow cast, trim comments)
Multi-dimension review found no bugs, leaks, or security issues; these are
the confirmed robustness + comment nits:
- resetUndoHistory: match the history plugin by PluginKey identity (a fresh
  history() shares prosemirror-history's module-level singleton key) instead
  of sniffing the undocumented stringified `history$` name — so an upstream
  change fails loudly instead of silently turning the reset into a no-op.
- MarkdownTable: narrow `pipeEscaping as never` to
  `as Parameters<typeof renderTableToMarkdown>[1]` so a future signature
  change is caught at compile time rather than swallowed.
- Trim restating/duplicated comments in markdown-editor.tsx and
  editor-markdown.ts; kept the genuine framework gotchas (reconfigure trap,
  onBeforeCreate timing, setContent contentType, pipe re-parse).

tsc, lint, 747 vitest green; verified history() spec.key is a singleton.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-29 22:55:02 +07:00
Sergey KozyrenkoandClaude Opus 4.8 e1e7817dd6 feat(editor): migrate markdown round-trip to official @tiptap/markdown
Replace the unified rich editor's markdown engine: drop the community
tiptap-markdown (markdown-it parse + prosemirror-markdown serialize) and
our 5 prosemirror-internal monkey-patch extensions for the official
@tiptap/markdown (marked-based MarkdownManager). The consumer moves to the
new API (editor.getMarkdown() / contentType:'markdown' / markdown.parse).

editor-markdown.ts adds three small, supported-API customizations:
- a private HTML-neutralized marked instance so literal <xml-tags> survive
  (marked otherwise swallows real-HTML-element names like <input>);
- FaithfulMarkdownText overrides MarkdownManager.encodeTextForMarkdown to
  drop entity-encoding and over-escaping of literal punctuation;
- MarkdownTable wraps renderTableToMarkdown to escape cell pipes (#7884).

Verified: tsc, 747 vitest (rewritten extension + 39-prompt corpus tests),
lint, build; live on the dev stand — knowledge tables render and resize,
prompt <tags> stay literal (124 tag + 116 variable highlights, no
entity-encoding), console clean.

Known accepted bug, pinned by a test (marked parser, 0 corpus impact):
a code block nested ordered-list > bullet-sublist > code is dropped on
parse. Repro recorded for an upstream report.

Folds in the in-progress unified-editor work it depends on: knowledge
Plain/Visual toggle, settings-prompt and template editor wiring, the
CodeMirror removal, and the editor table/tag/variable styles.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-29 22:33:22 +07:00
Sergey KozyrenkoandClaude Opus 4.8 18839b3487 refactor(templates): adopt the 2-panel resizable layout of the other detail pages
templates/{id} now mirrors knowledges/{id} and settings/prompts/{id}: a left
ResizablePanel (intro + title + the Presets panel, in the spot where the prompt
page shows "Available variables") and a right panel holding the Code/Plain
editor that fills the space. Save moves to the header (FormSubmitButton
form="template-form"); the right-side Presets sidebar/Sheet, the PanelRight
toggle, the in-input save button, and the Enter-to-submit handler are removed.

Live-verified on the stand: 2-panel render (create + edit), preset apply,
create->DB->reload byte-fidelity (incl. the blank line, reconstructed from
.cm-line), the Code editor filling the right panel, delete. tsc/eslint/build
+ 652 frontend tests green; console clean.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-28 01:41:26 +07:00
Sergey KozyrenkoandClaude Opus 4.8 d3c46c7158 test: close the coverage gaps flagged by the review
- providers: prove a stale user-provider row does not knock out a valid USER
  sibling (TestGetProviders_StaleUserRowSpansValidSibling — ollama builds keyless
  so it survives beside a skipped minimax; side-by-side verified).
- settings-provider: cover the create-form ?type=/?id= guards (disabled/unknown
  type and clone-of-disabled bounce to the list; an enabled type renders). These
  had zero coverage — a swap/drop-return regression would have shipped green.
- knowledge-form: cover performSave's server-document reset branch (untouched
  fields reflect the returned document under keepDirtyValues), and the useBlocker
  "Save and leave" path via a real data router (proceeds the blocked nav, does
  NOT honor a CREATE redirect). Swap the negative no-navigate assertion's
  setTimeout(0) flush for a deterministic Save-disabled anchor.

Each test mutation-verified to fail on the reverted production code; 652 frontend
tests + go test green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-28 00:55:29 +07:00
Sergey KozyrenkoandClaude Opus 4.8 84d87cf474 refactor(providers): apply review follow-ups (degrade log, count helper, empty menu)
From a strict re-review of the recent commits (no blocker/high/security found):
- providers.go GetProviders: the skip covers ANY unbuildable saved provider, not
  only a disabled type — drop the misleading "of unavailable type" wording and
  lower the line to Debug (it re-fires on every providers fetch; WithError keeps
  the reason).
- settings-prompt countVariableUses: drop the redundant seed-in-map side effect;
  the component already falls back to `?? 0` for unused variables, so the loop's
  own `?? 0` is the only seed needed.
- settings-providers create menu: render a disabled "No available provider types"
  placeholder instead of a silently-empty menu (loading / no-keys / failed-query
  states), with a test covering it.

Counts live-verified unchanged (AgentType 1->3 on the stand); go test + 646
frontend tests green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-27 23:45:36 +07:00
Sergey KozyrenkoandClaude Opus 4.8 579fac8b69 feat(providers): guard cloning a disabled-type provider + test the menu filter
Follow-up to b6d1036. Cloning an existing provider whose type is now disabled
(?id=) would have produced another dead provider — apply the same enabled-check
on the clone path. Adds a Vitest covering the create menu's enabled-only filter
(exports SettingsProvidersHeader for the render test; eslint sort-modules then
reorders it above the page component — declaration hoisting, no runtime change).

Live-verified: clone of the disabled minimax (?id=3) redirects to the list;
clone of bedrock (?id=2) still opens with a "(Copy)" name.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-27 23:24:52 +07:00
Sergey KozyrenkoandClaude Opus 4.8 b6d10362cf feat(providers): hide disabled types from create menu + guard ?type= URL
A user could create a provider of a type whose API key isn't configured: it
saved fine and showed in settings, but was dead for flow creation with no
signal (and used to break the whole providers query — see 08a24c9). Two layers:
- the "Create provider" menu now only offers types whose key is set
  (settingsProviders.enabled, already fetched by the page), and
- the create form bounces a hand-typed ?type= that is unknown or disabled to
  the list, closing the direct-URL bypass of the filtered menu.

Frontend-only. Live-verified on the docker stand: minimax/custom drop from the
menu (11 -> 9); ?type=minimax and ?type=garbage123 redirect; ?type=anthropic
still opens the form.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-27 23:07:53 +07:00
Sergey KozyrenkoandClaude Opus 4.8 4664cf8f53 test(knowledges): cover knowledge-form save/navigation + partial-update mapping
The knowledges feature had zero coverage while 01fa02d reworked its save/guard
logic. Add Vitest tests for the exported pure mappers (create/update inputs —
including the dirty-gated "" vs undefined distinction — and the zod
docType->subtype superRefine) and the component wiring (create -> navigate to
redirect, update -> no navigate, save-disabled-until-dirty, scoped
anonymize-disabled). The useBlocker dialog path stays covered by manual/live
testing (it needs a data router the component tests intentionally stub out).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-27 22:19:51 +07:00
Sergey KozyrenkoandClaude Opus 4.8 08a24c9abd fix(providers): skip unavailable user providers instead of failing the whole list
A saved user provider whose type is no longer enabled (e.g. its API key was
removed) made GetProviders return an error for the ENTIRE `providers` query —
one stale row blocked all flow creation in the UI ("No available providers").
Skip and log such rows, mirroring how startup already tolerates disabled
default providers. Pre-existing robustness gap, not introduced by this branch.

Verified live on the docker stand: the `providers` query went from a hard
error to returning all 10 enabled providers (the stale minimax row skipped),
and flow creation works again. Adds a side-by-side regression test.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-27 22:10:40 +07:00
Sergey KozyrenkoandClaude Opus 4.8 c752bb2737 perf(settings/prompt): count variable uses in one pass + bound regex
The "Available variables" badges recomputed a per-variable `.match` over
the whole template on every keystroke (O(variables × length)); fold them
into a single pass over the `{{ … }}` blocks. Tighten the action regex to
`[^{}]` so an unclosed `{{` cannot drive quadratic backtracking — closes
the self-DoS flagged by the security review.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-27 20:37:26 +07:00
Sergey KozyrenkoandClaude Opus 4.8 4472daa0d1 refactor(knowledges): trim performSave doc-comment to the load-bearing invariant
Drop the function-behavior restatement; keep the actionable invariant (navigation
stays with the caller, else the guard↔onSaveFromDialog↔performSave cycle returns).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-27 15:45:58 +07:00
Sergey KozyrenkoandClaude Opus 4.8 0cd37effed refactor: apply prompt/provider code-review findings + unify perf-scope comments
From .cursor/rules/CODE-REVIEW-prompt-provider-commits.md (settings-prompt, code-editor):
- rename abbreviations currentIdx->currentIndex, pos->position
- drop the cycle-ternary restatement comment
- gate the green "go to occurrence" badge affordance to plain view (code view only inserts)
- move code-editor's byte-faithful note into an actionable JSDoc warning on the component

Cross-component uniformity: collapse the four scoped-useWatch wrappers (DiffContent,
VariablesPanelContainer, KnowledgeFormHeader, DeleteProviderDialog) to one consistent
"Don't hoist this useWatch..." warning, dropping the duplicated narration + provenance.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-27 15:42:08 +07:00
Sergey KozyrenkoandClaude Opus 4.8 62e5afa04d perf(settings/provider): scope provider-name watch out of the main form
The provider `name` field was watched at the top of SettingsProvider but only
fed the delete dialog's itemName, so every keystroke re-rendered the whole form
tree (Accordion + 12 agent configs + resizable panels). Move the watch into a
small DeleteProviderDialog wrapper that subscribes on its own. Measured: typing
10 chars now re-renders SettingsProvider 2x (the one-time isDirty flip) instead
of once per keystroke; the per-keystroke re-renders land on the tiny dialog.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-27 15:29:12 +07:00
Sergey KozyrenkoandClaude Opus 4.8 50a272501b feat(templates): add byte-faithful code editor view for template content
A Code/Plain toggle in the ⋯ menu swaps the autosize textarea for the
lazy-loaded CodeMirror CodeEditor, mirroring the prompt-template editor, so
flow templates with {{VAR}} placeholders edit byte-faithfully (no markdown
normalization). The toggle is available for new templates too; the editor
nests in the existing InputGroup shell so the in-input save button is shared
across both modes.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-27 15:19:19 +07:00
Sergey KozyrenkoandClaude Opus 4.8 01fa02d3b4 perf(knowledges): scope content subscription off the form + untangle save/guard cycle
Typing in the knowledge markdown editor re-rendered the whole KnowledgeForm on
every keystroke: form.watch('content') — used only to toggle the anonymize
button's disabled state — subscribed the top-level component, dragging the form
body, layout, and metadata fields through a re-render per character. Measured on
a multi-KB document: max input processing 58ms -> 21ms, keystrokes over 25ms
20 -> 0, long tasks 1 -> 0.

- Move the content subscription into a small module-scope KnowledgeFormHeader
  wrapper (scoped useWatch), so only the header reacts to typing; the form body,
  layout, and editor stay put. Mirrors the existing pattern in
  knowledge-form-controls.tsx.
- Removing the watch let the React Compiler optimize KnowledgeForm, which then
  flagged the skipNextBlockRef latest-ref (react-hooks/immutability). Rather than
  suppress it, untangle the performSave<->guard cycle the ref existed to break:
  performSave now returns the result and the *caller* owns navigation. The form
  Save button (defined after the guard) does the CREATE redirect via the stable
  skipNextBlock; the unsaved-changes dialog's "Save and leave" saves and lets the
  guard proceed the navigation the user initiated. No eslint-disable, no memo.

Behavior note: on CREATE, the Save button lands on the new document; the
"Save and leave" dialog now lands on the destination the user was navigating to
(it previously raced between the two). Verified live on the local stack:
create/update via button and dialog, delete on a dirty form, anonymize toggle.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-27 12:58:51 +07:00
Sergey KozyrenkoandClaude Opus 4.8 bb8739072b perf(prompts): scope template subscription to stop per-keystroke full-page re-render
SettingsPrompt called form.watch('template') on both forms at the top level, which
subscribes the whole ~1000-line component to re-render on every keystroke (header,
tabs, panels, meta, all four dialogs). Move the live-template reads into small
useWatch children so only they re-render:

- VariablesPanelContainer wraps the variables panel (needs the live ×N counts).
- DiffContent wraps the diff viewer — live while the dialog is open, and Radix
  unmounts it (and its subscription) when closed.
- handleValidate and the variable-insert callback read form.getValues() at call
  time instead of the watched vars; the diff dialog's derived currentTemplate is
  dropped.

Mirrors the existing knowledge-form-controls.tsx pattern. Verified with render-count
instrumentation that the parent no longer renders per keystroke (only the scoped
children do), and that the live count, variable insert/cycle, validate, diff (live
while open), reset, code-editor insert, and dual-tab dirty flows are unchanged.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 21:15:46 +07:00
Sergey KozyrenkoandClaude Opus 4.8 65a037b91a feat(prompts): add byte-faithful code editor view for prompt templates
Prompt templates are Go templates with markdown tables, <xml-tags>, and
significant whitespace — content a markdown (Tiptap) editor normalizes and
corrupts on round-trip. Add a CodeMirror-based view instead, toggled from the
prompt page actions menu, that edits the raw template verbatim.

- New shared CodeEditor (CodeMirror 6 + markdown highlighting, line wrapping,
  theme-aware), lazy-loaded so its chunk only loads when code view is opened.
- "Code editor" / "Plain text" toggle in the prompt actions menu.
- Available-variables click inserts {{.Var}} into the code editor at the caret.
- Fix a pre-existing tsc error in the variable-cycling code
  (noUncheckedIndexedAccess on the matched-occurrence lookup).

Round-trip verified byte-exact end to end: original -> code edit -> plain, and
save -> DB -> reload, all identical to source (tables, tags, whitespace intact).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 19:55:31 +07:00
Sergey KozyrenkoandClaude Opus 4.8 3114d13fcd feat(settings/prompt): cycle through all variable occurrences + show use count
Clicking an in-use variable in "Available variables" jumped only to the first
occurrence. Now it cycles: from the occurrence the caret is on it advances to
the next (wrapping past the last), else jumps to the first at/after the caret.
Each badge also shows a ×N count when the variable is used more than once.

Verified live (vite dev → docker backend) on the adviser prompt: a ×7 variable
steps through all 7 occurrences in order and wraps.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 15:21:02 +07:00
Sergey KozyrenkoandClaude Opus 4.8 a47caa4ff9 refactor(settings): use InputGroup for the model combobox input+trigger
FormModelComboboxItem manually glued an Input and a dropdown Button by
stripping adjacent borders/corners and juggling z-index on focus/hover.
Replace that with the project's InputGroup primitive (single border, ghost
trigger, native group focus-ring) — matching InputPassword and the ~20 other
input-group usages. Also gives the icon-only trigger an accessible name.

Verified live (vite dev against the docker backend): input editable, dropdown
opens via the asChild trigger, option/price autofill intact.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 14:46:22 +07:00
Sergey KozyrenkoandClaude Opus 4.8 a1908536b7 test(providers): extend the price-consistency guard to all 9 providers
anthropic, bedrock, and gemini also carry per-agent prices in config.yml but
were not covered. Adding them confirms no current drift and guards them going
forward. bedrock's loaders take a *config.Config, so they're wrapped with an
empty config to read the embedded catalog.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 13:55:26 +07:00
Sergey KozyrenkoandClaude Opus 4.8 4ecf2bbac1 fix(providers): correct model prices from a full official-source audit
Audited all 133 catalog models across 9 providers against official pricing
pages, each delta independently re-verified. openai/anthropic/gemini/glm/kimi
were already correct (0 changes). Corrections:

- deepseek-v4-pro: 1.74/3.48/0.0145 -> 0.435/0.87/0.003625 (catalog was 4x the
  official DeepSeek rate).
- bedrock mistral-large-3-675b: 4.0/12.0 -> 0.5/1.5 (8x overstatement; old
  Mistral Large 24.07 rate).
- minimax M3 0.6/2.4 -> 0.3/1.2, M2.7 0.4/1.1 -> 0.3/1.2, M2.7-highspeed
  0.4/1.1 -> 0.6/2.4, all +0.06 cache (permanent-50%-off effective rates).
- qwen3.6-35b-a3b: 0.248/1.485 -> 0.375/2.25 (catalog had the China-mainland
  price, not the International endpoint the rest of the catalog uses).
- qwen: add cache_read = 0.20 x input (implicit-cache rule) to 16 open-source
  models that were missing it.

config.yml agent prices synced for deepseek-v4-pro and MiniMax-M3 (guard test
keeps them aligned).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 13:44:59 +07:00
Sergey KozyrenkoandClaude Opus 4.8 dad1be429e feat(providers): declare reasoning efforts for gpt-5.2-codex and gpt-5-pro
Verified per the official OpenAI model pages:
- gpt-5.2-codex: [low, medium, high, xhigh]
- gpt-5-pro: [high] (the page states it "only supports reasoning.effort: high")

Other openai reasoning models (gpt-5, gpt-5.1 = no xhigh; gpt-5-mini/nano,
codex variants, o-series) keep the default — their official pages do not
enumerate an accepted effort set.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 13:44:58 +07:00
Sergey KozyrenkoandClaude Opus 4.8 ebeddf4e76 fix(providers): set qwen cache_read to the documented 20% implicit-cache rate
Alibaba Model Studio's context-cache doc bills cached input tokens at 20% of the
input price (implicit hits, International endpoint). Most of the qwen catalog
already used 20%; align the outliers and guard against future drift.

- qwen3.7-max 1.25 -> 0.5, qwen3.7-plus 0.2 -> 0.08: corrects an earlier change
  that read a "50% discount" off the model-pricing page; the authoritative rate
  is 20%, so the original 0.5 for qwen3.7-max was already correct.
- qwen3.6-{max-preview,plus,flash}, qwen3.5-{plus,flash}: 10% -> 20% stale
  outliers, with matching config.yml agent-price updates.

Add TestAgentConfigPricesMatchCatalog: GetPriceInfoForType returns the agent
price with no catalog fallback, so config.yml drift silently mis-prices cost.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 05:04:13 +07:00
Sergey KozyrenkoandClaude Opus 4.8 2f9e86391e feat(providers): declare reasoning efforts for the remaining xhigh openai models
Verified per the OpenAI model pages (reasoning.effort support):
- gpt-5.4-mini, gpt-5.4-nano, gpt-5.2: [low, medium, high, xhigh]
- gpt-5.2-pro: [medium, high, xhigh] (no low)

gpt-5 / gpt-5.1 keep the default [low, medium, high] (no xhigh; gpt-5 uses
"minimal", not representable in the UI enum). Codex variants are unverified
and left for a follow-up.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 05:04:12 +07:00
Sergey KozyrenkoandClaude Opus 4.8 de7db21448 feat(providers): declare reasoning efforts so xhigh/max surface in the UI
The settings effort dropdown is driven by a model's reasoning.efforts and
falls back to [low, medium, high] when absent, so xhigh/max were never
selectable for OpenAI-compatible models even though the backend accepts them.

Declare the verified accepted levels:
- glm-5.2: [high, max] (Z.AI: GLM-5.2 reasoning_effort accepts only high/max,
  so the default low/medium were also wrong for it)
- gpt-5.4: [low, medium, high, xhigh] (OpenAI GPT-5.4/5.5 effort enum)

Other openai/gpt-5.x entries still need per-model effort verification.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 04:39:31 +07:00
Sergey KozyrenkoandClaude Opus 4.8 8bbbdbf7c5 fix(providers): correct qwen3.7-max cache_read to the official rate
cache_read was 0.5; the Alibaba Model Studio official price (International)
is 1.25 per 1M tokens (a 50% discount on the 2.5 input rate). Pre-existing
inaccuracy, unrelated to the qwen3.7-plus addition.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 03:56:04 +07:00
Sergey KozyrenkoandClaude Opus 4.8 b40091d68f fix(providers): correct kimi-k2.7-code and qwen3.7-plus prices to official rates
Replace the placeholder estimates with verified list prices (USD per 1M tokens):
- kimi-k2.7-code: 0.95 / 4.00 / 0.19 cache (platform.kimi.ai official) —
  identical input/output to k2.6, only the cache rate differs.
- qwen3.7-plus: 0.4 / 1.6 / 0.2 cache (Alibaba Model Studio official,
  International base <=256K tier) — the earlier estimate conflated it with
  the qwen3.7-max tier and was ~2.5x too high.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 03:54:31 +07:00
Sergey KozyrenkoandClaude Opus 4.8 f489e13ed4 docs(providers): drop unverifiable superlative from glm-5.2 description
"the only GLM model that honors reasoning_effort" is an unenforceable
prose claim; state the capability the entry actually carries instead.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 03:47:13 +07:00
Sergey KozyrenkoandClaude Opus 4.8 c3504b1839 test(evidence-receipts): cover unterminated and oversized tail reads
The tail reader's no-trailing-newline branch (a torn/truncated final
append, the case M3's fsync defends) and the over-window error branch
had no coverage. Add cases for a newline-free last line, a torn final
append that must be rejected, and a single line exceeding the 64KiB
window.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 03:47:13 +07:00
Sergey KozyrenkoandClaude Opus 4.8 35c77ae5aa test(providers): scan the whole catalog for adaptive modes in the M7 pin
The M7 pin only checked models actually assigned to an agent type, so an
adaptive reasoning mode declared on an unassigned catalog model would pass
silently. Add a second loop over every catalog model so any openaicompat
provider that declares adaptive/adaptive-only fails loudly — matching the
guard's stated intent.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 03:47:12 +07:00
Sergey KozyrenkoandClaude Opus 4.8 83bff62d3b refactor(evidence-receipts): drop change-narration comment on the lock pool
The comment narrated the replaced sync.Map design and defended the
choice; the fixed-stripe array plus FNV indexing is self-evident and
the rationale already lives in commit d12b984.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 03:32:02 +07:00
Sergey KozyrenkoandClaude Sonnet 4.6 2d8bce7ccb feat(providers): add glm-5.2, kimi-k2.7-code, qwen3.7-plus to model catalogs
- glm/models.yml: add glm-5.2 (only GLM model supporting reasoning_effort=high/max)
- kimi/models.yml: add kimi-k2.7-code (code-specialist above k2.6)
- qwen/models.yml: add qwen3.7-plus (cost-efficient tier below qwen3.7-max)

Prices for kimi-k2.7-code and qwen3.7-plus are estimated from adjacent
catalog entries and should be verified against official pricing pages.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 03:11:20 +07:00
Sergey KozyrenkoandClaude Sonnet 4.6 a69e19f751 feat(providers): allow xhigh/max reasoning_effort on the OpenAI-compatible path
The per-agent options builder only emitted WithReasoning for low/medium/high,
and the langchaingo fork clamped xhigh/max to high in GetEffort (treating them
as adaptive-only). OpenAI GPT-5.5 and GLM-5.2 now expose xhigh/max as real
reasoning_effort levels, so that clamp encodes a stale invariant.

Extend the effort switch to pass xhigh/max through; the fork's GetEffort clamp
is removed in the local langchaingo (propagated via vendor) so the OpenAI
transport emits the real level. Adaptive (anthropic/bedrock) and budget paths
are unaffected — GetEffort is called only by the OpenAI transport. Validity is
gated per model by ModelReasoningInfo.Efforts.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 02:18:57 +07:00
Sergey KozyrenkoandClaude Sonnet 4.6 40debd150d test(providers): pin openaicompat providers off adaptive thinking (M7)
Adaptive thinking (thinking.type=adaptive + output_config.effort) is an
Anthropic-protocol mode the langchaingo OpenAI transport cannot emit, and
the openaicompat Call path never threads PrepareAdaptiveCallOptions. So an
adaptive reasoning mode declared in an openaicompat provider's models.yml
would silently no-op.

Assert that none of the openaicompat-backed providers (qwen, glm, deepseek,
kimi, minimax) resolve to adaptive thinking for any agent type. The day
someone adds an adaptive model/mode to one of their configs, this fails
loudly instead of dropping the thinking budget in silence.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 00:52:49 +07:00
Sergey KozyrenkoandClaude Sonnet 4.6 4d25cf5c51 perf(evidence-receipts): read only the file tail for the previous hash
record() called readLastEvidenceReceiptHash on every append, which re-read
and re-hashed the entire receipts.jsonl just to get the last hash and verify
the whole chain — O(N^2) over a flow's receipts, on the tool-call hot path
under the per-path lock (M2).

Read only the last line instead (windowed ReadAt from the end), failing
closed if that line is missing, wrong-schema, or hash-mismatched. This is
O(1) per append and stays correct across the multiple recorder instances
that write one path (L6): the file stays the single source of truth, so
there is no per-instance cache to go stale. Full-chain verification belongs
in a separate read-time verify tool, not on every write.

Off by default (EVIDENCE_RECEIPTS_ENABLED=false). Measured: 1024 concurrent
appends under -race dropped from ~49s to ~7.5s.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-25 21:43:19 +07:00
Sergey KozyrenkoandClaude Sonnet 4.6 4b9e4b4972 fix(evidence-receipts): fsync each receipt append for durability
The append wrote the receipt line and returned without flushing, so a crash
between the write and the OS flushing its page cache could lose or truncate
the last receipt, after which the fail-closed chain check halts all further
writes until the file is repaired (M3). Sync the file before returning.

Off by default (EVIDENCE_RECEIPTS_ENABLED=false), so standard deployments are
unaffected; the cost lands only when the feature is explicitly enabled.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-25 21:21:07 +07:00
Sergey KozyrenkoandClaude Sonnet 4.6 09383063ac test(evidence-receipts): pin sharded lock pool bounds and concurrency
Three guards for the L6 sharded mutex pool (d12b984):
- bounded: 100k distinct flows resolve to <= 256 mutexes, so reverting to a
  per-path map (the original unbounded leak) fails the test.
- high concurrency: 16 cross-executor writers on one path keep the hash chain
  intact under -race.
- stripe collision: two flows that hash to the same stripe keep their own
  chains intact, confirming shared stripes add contention but not corruption.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-25 21:00:27 +07:00
Sergey Kozyrenko 124a1e1084 Merge remote-tracking branch 'origin/fix/ram-consumption' into integrate/open-prs 2026-06-25 20:11:59 +07:00
Sergey KozyrenkoandClaude Sonnet 4.6 d12b984631 fix(evidence-receipts): replace per-path sync.Map with sharded mutex pool
A sync.Map holding one *sync.Mutex per flow path grew unbounded for the
whole server uptime. A fixed 256-stripe array keyed by FNV-32a hash of
the path caps memory at a constant cost while preserving per-path append
serialization required by the hash-chain invariant.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-25 20:10:32 +07:00
Dmitry Ng c543831205 feat(backend): enhance graphiti search tool with langfuse integration
- Added langfuse observability support to the graphiti search tool, allowing for detailed tracking of search operations.
- Introduced a mapping of search types to human-readable titles for better traceability in logs.
- Implemented a new method to build the input payload for langfuse retrievers, encapsulating relevant search parameters.
- Enhanced error handling to include retriever status updates on success and failure, improving observability and debugging capabilities.
2026-06-25 12:29:14 +03:00
Dmitry Ng e909f40b2e fix(backend): implement singleton pattern for anonymizer replacer
- Introduced a process-level singleton for the anonymizer replacer to enhance performance and ensure thread safety.
- The replacer is built once using patterns loaded at startup, allowing it to be shared across all flow executor instances.
- Updated the flow tools executor to utilize the shared replacer, simplifying the creation process and improving efficiency.
2026-06-25 12:28:49 +03:00
Dmitry Ng 9caa6a8775 fix(backend): update LRU cache implementation to use non-expirable version
- Replaced expirable LRU cache with non-expirable lru.Cache in multiple files for improved performance and reduced resource usage.
- Introduced a new function, newSummarizerCache, to create a fixed-size LRU cache for summarizer results, eliminating the need for background goroutines.
- Updated related code to ensure compatibility with the new cache implementation.
2026-06-25 12:28:10 +03:00
Sergey KozyrenkoandClaude Opus 4.8 2d2aea5785 fix(auth): reject OAuth logins with a provider-unverified email
The OAuth callback links/creates an account by the email from ResolveEmail, and
Google/GitHub only ever return a verified address — but that invariant lived
inside each provider and was invisible at the callback. A future OAuth provider
that omitted the verified check would let an attacker register a victim's email
there (unverified), "sign in", and be linked straight into the victim's account:
instant takeover.

Make verification part of the contract: ResolveEmail now returns
(email, verified, err), and the callback refuses to proceed when !verified.
Because Go's bool zero value is false and the compiler forces the new return, a
provider that forgets to report verification fails closed (its own login breaks)
rather than opening a takeover. Google reports claims.EmailVerified; GitHub only
selects verified addresses, so reports true. Added a callback test: a provider
reporting an unverified email is rejected (no link, no session) — red before the
gate, green after.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-25 14:43:16 +07:00
Sergey KozyrenkoandClaude Opus 4.8 497cfdd555 fix(users): require a real email on user-initiated email change
EmailChange.Mail validated with `vmail`, which accepts not just a real address
but also the literal "admin" and any UUID — escape hatches that exist so the
seeded admin row (mail "admin") passes User.Mail's Valid(). The account's
change-email form (added this branch) reaches it, so a user could save "admin"
or a UUID as their own email — a non-deliverable value (no privilege gain: roles
come from role_id, and UNIQUE(mail) blocks colliding with the real admin row).

Add a strict `realemail` validator (same address regex as vmail, minus the
hatches) and use it for EmailChange.Mail; User.Mail keeps `vmail` so the seeded
admin still validates. Tests cover the validator (admin/UUID rejected, real
address accepted) and the handler (changing to a UUID or "admin" now 400s).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-25 13:00:36 +07:00
Sergey KozyrenkoandClaude Opus 4.8 14e0a0ae71 fix(users): preserve email case on change to match login, OAuth and create
ChangeEmailCurrentUser was the only path that lowercased the email
(strings.ToLower), while local login, the OAuth callback and CreateUser all
store/compare it raw against a case-sensitive UNIQUE(mail). That lone
normalization let a changed address (now lowercased) miss a later raw-case
login, and let the uniqueness pre-check (run on the lowercased value) skip an
existing mixed-case row. Drop the ToLower so every path is consistently
case-sensitive again — the pre-branch invariant. The email validator already
rejects surrounding whitespace, so the paired TrimSpace was dead.

Update the test that codified the old lowercasing to assert case preservation.
A fully case-insensitive scheme (normalize everywhere, or citext /
UNIQUE(lower(mail))) is tracked separately as a follow-up.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-25 10:15:44 +07:00
Sergey Kozyrenko 14b3da2d6f fixup! fix(detail-navigation): re-seed the sheet search mirror from the controller on open 2026-06-25 09:56:14 +07:00
Sergey Kozyrenko ac32a8e996 fixup! fix(providers): don't crash startup when a disabled provider's external config is unreadable 2026-06-25 09:56:14 +07:00
Sergey KozyrenkoandClaude Opus 4.8 f441ec1c4d fix(providers): don't crash startup when a disabled provider's external config is unreadable
NewProviderController loaded every provider's default config (NewConfig) in an
ungated loop that treated any error as fatal, while actual provider construction
(New) is correctly gated on Enabled. A disabled provider pointed at an unreadable
BEDROCK_CONFIG_PATH (or the equivalent custom/ollama external config) therefore
aborted startup, even though that provider was never going to be used.

Extract the config-loading loop into buildDefaultConfigs and gate the failure on
Enabled: a disabled provider whose external config can't be read is logged and
skipped; an enabled provider still fails loudly. Tests cover both paths
(disabled + bad path non-fatal, enabled + bad path fatal).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-25 09:26:00 +07:00
Sergey KozyrenkoandClaude Opus 4.8 8ca83137a1 fix(detail-navigation): re-seed the sheet search mirror from the controller on open
DetailNavigationSheet keeps a local input mirror (localQuery) seeded once from
controller.searchQuery — a deliberate perf decouple (92a9e59) so typing in the
sheet doesn't re-render the whole detail page. But in the controller's documented
controlled mode (a page-level search box that owns searchQuery), an external
change made while the sheet was closed left the mirror stale: reopening the sheet
showed the old text.

Re-seed the mirror from the controller on each open, folded into the existing
open-transition reconciliation. The sheet is modal, so searchQuery can only
change externally while closed — on-open re-seeding suffices and never clobbers
in-progress typing. Add a controlled-mode test that reproduces the stale input
(red before, green after).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-25 09:16:26 +07:00
Sergey KozyrenkoandClaude Opus 4.8 47c1ea108b fix(report-pdf): drop dead CJK font ternary, document the Hangul gap, add tests
renderTextWithCJK selected the CJK font via `bold ? 'NotoSansSC' : 'NotoSansSC'`
— both branches identical, so the ternary was dead. Collapse it to the single
family. The CJK detection regex matches Han, kana, Hangul and Bopomofo, but the
only registered CJK font (NotoSansSC) lacks Hangul — verified with fontkit — so
Korean renders as missing-glyph boxes; document that limitation and the
NotoSansKR fix path.

splitByCJK and renderTextWithCJK had no tests; add a suite covering segmentation
(mixed Latin/CJK, kana, hangul, CJK punctuation, empty input) and per-segment
font assignment.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-25 09:03:53 +07:00
Sergey KozyrenkoandClaude Opus 4.8 d440eafea9 test(detail-navigation): cover the virtualized sheet branch (>100 items)
The DetailNavigationSheet virtualized branch (items.length > 100) was never
exercised — the fixture had 4 items, always below the threshold. Add a 150-item
suite covering the virtualized path: a windowed subset of options, the roving
tabIndex on the current option, and in-window ArrowDown navigation. The
@tanstack virtualizer can't measure a viewport under jsdom, so the hook is mocked
to a fixed window (the windowing math is @tanstack's own coverage).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-25 08:43:14 +07:00
Sergey KozyrenkoandClaude Opus 4.8 28377ab4a4 fix(webui): reset price/reasoning when a model name is typed, not just picked
The provider model field is an Input + dropdown combobox. Picking from the
dropdown (or "Use as custom") fires onOptionSelect, which resets price/reasoning
to the new model's catalog values — but typing the model name only updated the
field, leaving stale price/reasoning from the previously-selected model. Fire
onOptionSelect from the Input's onChange when the typed value exactly matches a
catalog option, so a typed known model behaves like a picked one.

Live-verified: typing us.anthropic.claude-sonnet-4-5-... into an agent on
gpt-oss reset Input Price 0.15->3, Output 0.6->15, cache 0->0.3/3.75.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-25 08:35:59 +07:00
Sergey KozyrenkoandClaude Opus 4.8 49af50d4ab refactor(webui): apply Apollo Client v4 review fixes to apollo.ts
From a doc-grounded review against @apollo/client 4.2.3 + graphql-ws 6 (all
findings low/info, adversarially verified):

- streaming link: fold the throttle timestamp into the LRU StreamingLogEntry so
  it is evicted with its log — removes the unbounded lastUpdateTimestamps Map
  that leaked for streams that never receive a closing (non-appendPart) message.
- errorLink: also dispatch auth:refresh on a ServerParseError 401/403 (the narrow
  application/graphql-response+json path that ServerError.is() does not match).
- WS retryWait: add jitter so a mass reconnect (e.g. backend restart) does not
  thundering-herd the server.
- cache: log instead of silently swallowing a storeFieldName parse failure in
  matchesCacheVariant, so a future Apollo serialization change is observable.
- v4 deprecations: onError -> new ErrorLink, createHttpLink -> new HttpLink,
  FetchResult -> ApolloLink.Result, Operation -> ApolloLink.Operation.

Verified: tsc -b + vite build, 604 vitest pass, and a live smoke on the docker
stand (queries + subscription WS connect, no auth/JS errors).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-25 07:48:55 +07:00
Sergey KozyrenkoandClaude Opus 4.8 ec608d7091 fix(webui): redirect to login when the GraphQL subscription WS auth fails
The subscription WebSocket retries forever on a 403 handshake (expired/invalid
cookie), but its error handler only escalated to auth:refresh when the error
*message* contained "403"/"auth required" — and browsers never expose the
handshake HTTP status on a WebSocket error event, so that detection never fired.
An idle page with active subscriptions therefore looped on 403 with no redirect
to login (the redirect only fired once a REST/axios call hit a 403). Dispatch
auth:refresh unconditionally on any WS error and let /info decide: it redirects
on a real 401/403 and is a no-op while the session holds. Live-verified both
ways: an invalid cookie now redirects to login from an idle page, and a
transient WS drop on a valid session keeps the user logged in. Pre-existing (the
WS handler is unchanged from main); surfaced by a tester.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-25 06:45:06 +07:00
manusjs a50ba4c7a4 fix(sandbox): harden sandbox containers against privilege escalation
Address the container escape risk reported in issue #337 (Docker socket
bind-mount when DOCKER_INSIDE=true).

Changes:

backend/pkg/docker/client.go — RunContainer hardening
  • Add `no-new-privileges:true` to SecurityOpt on every sandbox container.
    Prevents setuid/setgid and file-capability escalation inside the sandbox.
  • Add PidsLimit=2048 as a cheap fork-bomb / resource exhaustion guard.
  • Add startup warning (logrus.Warn) when DOCKER_INSIDE=true so operators
    see the socket-escape risk at boot rather than only in documentation.
  • Correct the comment to not imply the socket-escape vector is mitigated
    by no-new-privileges alone (it is not; the real fix is DOCKER_INSIDE=false
    or a least-privilege socket proxy).

backend/pkg/tools/tools.go — CapDrop ALL on primary terminal container
  • Drop all Linux capabilities then add back only NET_RAW (always) and
    NET_ADMIN (when DOCKER_NET_ADMIN=true). Removes ~14 unnecessary caps
    from the default Docker set (e.g. SYS_CHROOT, AUDIT_WRITE, MKNOD) that
    pentest tools should not need and that could be abused in an escape chain.

.env.example
  • Flip DOCKER_INSIDE default to false (aligned with config.go envDefault).
    The previous example was contradicting the code default.
  • Expand the DOCKER_INSIDE comment: explains socket-escape risk, DinD
    guidance, and links to docker-socket-proxy as a least-privilege alternative.

Note: DOCKER_INSIDE=false is the safest configuration; operators who need
DinD should consider fronting /var/run/docker.sock with a proxy rather than
mounting it directly.
2026-06-24 17:46:42 +00:00
Sergey KozyrenkoandClaude Opus 4.8 3d447c582f ci: gate frontend install on frozen-lockfile drift
The "Frontend - Install dependencies" step ran pnpm install --frozen-lockfile
with continue-on-error: true, swallowing the ERR_PNPM_OUTDATED_LOCKFILE that the
flag exists to raise. The rest of the frontend pipeline (prettier, lint,
type-check, test) already gates strictly, so a stale pnpm-lock.yaml would only
surface later as a confusing downstream "command not found". Drop the flag so
lockfile drift fails loudly at the install step. Backend steps left as-is.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-24 10:44:31 +07:00
Sergey KozyrenkoandClaude Opus 4.8 7867a73a6a test(providers): guard providerRegistry against AllProviderTypes drift
A type present in only one of the two hand-maintained lists fails silently:
accepted by the API then erroring "unknown provider type" at construction, or
rejected 422 despite working. Assert set-equality and canonical names so drift
fails in CI instead.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-24 09:49:00 +07:00
Sergey KozyrenkoandClaude Opus 4.8 2f3df495fa test(pconfig): cover the adaptive-thinking backstop (refs #288)
UsesAdaptiveThinking/PrepareAdaptiveCallOptions had no test coverage after the
native-langchaingo migration removed the old transport-layer tests. Add table
tests: an adaptive-only model forces adaptive over an agent's budget choice or an
absent reasoning block, while budget-only models stay untouched.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-24 09:49:00 +07:00
Sergey KozyrenkoandClaude Opus 4.8 9e8ee58786 fix(resources,flowfiles): propagate zip Close() error instead of swallowing it
The four Zip* builders deferred zw.Close() with an unnamed return, dropping the
error from the central-directory flush. After the resources download moved to
direct socket streaming, a dropped connection during that final flush could
return a truncated archive under HTTP 200. Capture Close() via a named return so
streamZipArchive logs and aborts the partial response. Regression tests in both
packages drive the Close() error path with a failing writer.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-24 09:48:45 +07:00
Sergey KozyrenkoandClaude Opus 4.8 b8151c95ba fix(frontend): resolve review nits in settings (toast re-fire, chip a11y, dead export)
- settings-provider: handleTest/handleTestAgent/onSaveAndLeave now reset
  submitError before re-validating. The error toast is driven by a
  submitError-change effect, so a repeated identical validation failure
  previously set the same string and never re-fired; the await between the
  reset and the re-set splits the React batch so the toast shows every time.
- settings-prompt: the variables palette marks "used" chips with a leading
  check icon, giving a non-color signal alongside the green variant (the
  used/available distinction was conveyed by hue alone for sighted users).
- settings-sidebar: drop the unused `export` on the MenuItem interface — it has
  no importers; the extraction from settings-layout was the moment to clean it.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 20:44:28 +07:00
Sergey KozyrenkoandClaude Opus 4.8 4214f3b26d refactor(frontend): unify provider/prompt unsaved-changes onto the shared guard
The provider and prompt edit pages each carried a bespoke unsaved-changes
mechanism: a synthetic history.pushState + popstate listener that only caught
the browser back gesture, a "Discard changes?" ConfirmationDialog, and (after
the in-page Cancel button was dropped in the redesign) a chunk of unreachable
leave-handler code. In-app sidebar navigation while dirty silently discarded
edits, and the discard dialog rendered a Trash icon via confirmIcon={undefined}.

Both pages now use the same useUnsavedChangesGuard + UnsavedChangesDialog the
knowledge editor uses:

- useBlocker intercepts in-app router navigation (the sidebar links), and
  beforeunload covers reload/tab-close — not just the back gesture.
- The dialog offers Cancel / Discard / Save & leave (the old one was Stay /
  Leave with no save path).
- Forms switch to mode: 'onTouched' so isValid drives the dialog's Save button.
- Provider keeps "Save navigates to the list" via the guard's skipNextBlock;
  prompt's Save & leave saves every dirty tab (snapshotting both before the
  refetch-driven reset can clobber the other tab).

Removes the popstate/pushState refs, the dead handleConfirmLeave/-OpenChange
branches, and the misleading Trash icon. Resolves review findings on the
removed Cancel affordance, the dead leave-guard code, and the discard icon.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 10:37:13 +07:00
Sergey KozyrenkoandClaude Opus 4.8 916961d68d fix(frontend): harden the prompt variables palette (used-detection, dirty, a11y, scroll)
A code review of the "Available variables" block surfaced several real issues:

- Used-detection only matched bare {{.X}} interpolations, so variables used
  only in conditionals/ranges/nested access ({{if .X}}, {{range .X}}, {{.X.Y}})
  showed as "available" and clicking them inserted a stray bare {{.X}} instead
  of jumping to the existing usage. Detection and the click-to-locate logic now
  share one regex matching a top-level field in any {{ }} action, mirroring the
  backend's variable extraction; clicking a used variable selects its real
  occurrence.
- Clicking a used variable scrolled to it by counting logical newlines, which
  undershot badly once the textarea soft-wraps long lines (the default
  templates lay out ~40% more visual lines than logical), so the jumped-to
  variable landed off-screen. Measure the true pixel offset through a hidden
  mirror element and center it, so the selection is always scrolled into view.
- Inserting a variable via a chip called setValue without { shouldDirty: true },
  so the change never marked the form dirty and the unsaved-changes guard stayed
  silent. Both insert paths now mark the form dirty, matching keyboard typing.
- The chips were click-only <div>s (no keyboard/screen-reader access). They are
  now role="button" with tabIndex, Enter/Space handling, and a state-aware
  aria-label/title ("Insert …" / "Go to …"), which also activates the Badge's
  existing focus ring.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 07:47:26 +07:00
Sergey KozyrenkoandClaude Opus 4.8 161ff10315 feat(frontend): restyle the prompt variables palette
The "Available variables" block merged into the background on desktop and the
hand-rolled chips used light-theme greens (bg-green-100/text-green-800) that
clashed with the dark UI. Rebuild it on the project's primitives:

- Container: a delineated `rounded-lg border bg-card` panel with a `border-b`
  header (title + "click to insert" hint); the chips sit in a recessed
  `bg-background` tray below it, so the section reads as a distinct group with
  depth instead of a faint box.
- Chips: the shared `Badge` component — `green` (theme-aware) for variables
  already used in the template, `secondary` for the rest; monospace, normal
  weight, clickable.
- Badge: give the color variants (blue/green/orange/pink/purple/red/yellow)
  hover states to match default/secondary/destructive, so consumers don't
  hand-roll hover colors.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 06:55:13 +07:00
Sergey KozyrenkoandClaude Opus 4.8 6408310950 feat(frontend): move the prompt variables palette below the editor on mobile
Extract the "Available Variables" panel out of promptMeta into its own
`variablesPanel`. Desktop keeps it in the left pane under the tab selector
(reference beside the editor); mobile now renders it after the editor instead of
between the tabs and the editor, so the template editor sits directly under the
tabs on small screens.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 06:25:58 +07:00
Sergey KozyrenkoandClaude Opus 4.8 fd6185969d refactor(frontend): unify mobile layout + intro across the 2-pane edit pages
The provider, knowledge and prompt edit pages share one 2-pane shell, but
mobile and the intro block had drifted. Align them:

- Mobile: drop the wrapping Card on provider + knowledge (knowledge-form-layout,
  settings-provider) so all three render the stacked form directly in
  `flex min-h-0 flex-1 flex-col gap-4 p-4` (matches the prompt page; gap-4 to
  match the p-4 edge padding).
- Intro: use a `flex flex-col gap-2 text-center` wrapper with
  `<h2 class="text-2xl font-semibold">` + a `text-muted-foreground` description
  everywhere — knowledge was an `<h1>`, the prompt used `items-center gap-1`, and
  both leaned on a `mt-2` margin instead of the container gap.

Desktop shell (root, ResizablePanelGroup 45/55, left Card + CardContent py-6,
grip handle, per-pane scroll) was already uniform. The right-pane content stays
page-specific (accordion / markdown editor / textarea).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 06:22:28 +07:00
Sergey KozyrenkoandClaude Opus 4.8 a5633cf959 feat(frontend): redesign prompt edit page (2-pane layout, header actions, toasts)
Mirror the knowledge/provider edit pages: replace the single-column form +
sticky footer with a responsive 2-pane layout (desktop ResizablePanelGroup,
mobile single column). Left pane = centered intro + prompt identity + the
System/Human tab selector + the variables palette; right pane = the template
editor that fills the panel.

Move actions into the AppHeader: Validate + Save, plus an ellipsis menu (Reset,
Diff) shown only when a user override exists — no Cancel. Convert the inline
error alerts to a single submitError-driven toast, and the loading/error/
not-found branches to StatusCard. Drop the now-unused handleBack.

Shared UI tweaks supporting the editor:
- Textarea: add an `autoSize` opt-out (default true) so the editor can flex-fill
  its parent (the auto-size hook's inline max-height otherwise clamps it).
- TabsTrigger: add `gap-2` (matches Button) so an icon + label aren't glued.

Align the panel/Card structure with the knowledge layout (py-6 intro,
overflow-y-auto left, overflow-hidden fill-editor right, grip handle, 45/55
split); style the tab bar like the dashboard analytics tabs (bg-background list
+ bg-card active, full-width flex-1 triggers).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 05:50:43 +07:00
Sergey KozyrenkoandClaude Opus 4.8 174a0ba819 refactor(frontend): AppHeader component family + reorganize layouts by area
Introduce a shared AppHeader compound family (AppHeader / AppHeaderAction /
AppHeaderActions / AppHeaderContent / AppHeaderTitle) in a single module and
fold the page-header action button into it as AppHeaderAction (renamed from the
former HeaderButton). Every page header now composes this family instead of
copy-pasting the sticky <header> shell:

- settings pages (account, api-tokens, prompt(s), provider(s))
- main-app lists (dashboard, flows, templates, resources, knowledges, new-flow)
- detail headers (flow, template, knowledge) keep their bespoke breadcrumb
  content as AppHeaderContent children; their action clusters move into
  AppHeaderActions; sibling sheets/dialogs stay outside the header

This removes the duplicated shell across ~15 sites and the drift between copies
(the family owns the one canonical sticky shell + the SidebarTrigger/Separator).

Reorganize components/layouts into per-area subfolders:
- app/      app-layout + the AppHeader family (app-header.tsx)
- main/     main-layout, main-sidebar (+ test)
- settings/ settings-layout, settings-sidebar (+ test)
- flows/    flows-layout

Delete settings-page-header.tsx (superseded by AppHeader).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 03:01:15 +07:00
Sergey KozyrenkoandClaude Opus 4.8 8594a159a7 feat(frontend): redesign provider edit page (2-pane layout, header actions, toasts)
Rebuild the provider settings page to match the knowledge editor:
- responsive 2-pane layout — left Card with the centered intro + Type/Name,
  right scrollable panel with the agent-config accordion; mobile collapses
  to a single-column Card (via useBreakpoint). Each pane scrolls
  independently inside a fixed-height root (no whole-page scroll).
- move Save / Test / Delete into the page header (SettingsPageHeader actions);
  drop the sticky-bottom action bar and the now-unused Cancel/handleBack.
- surface mutation/validation errors as sonner toasts instead of inline
  Alerts (single submitError-driven effect).
- redesign the test-results modal: shrink-0 status icon, result/metadata as
  badges, wrapping monospace error block, colored per-agent pass count.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 06:37:28 +07:00
Sergey KozyrenkoandClaude Opus 4.8 73c5500bb2 refactor(frontend): per-page headers for settings, extract SettingsSidebar
Mirror the main app layout: SettingsLayout now renders only
SidebarProvider + SettingsSidebar + SidebarInset + Outlet, with no shared
header. Each settings page renders its own header via a new shared
SettingsPageHeader (sticky h-12 bar with an optional actions slot). The
sidebar is extracted into a self-contained SettingsSidebar component that
computes the "Back to App" returnUrl from location.state; its behavior is
covered by the new settings-sidebar.test (migrated from the removed
settings-layout.test). settings-account.test now wraps the page in a
SidebarProvider since the page renders its own SidebarTrigger.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 06:37:12 +07:00
Sergey KozyrenkoandClaude Opus 4.8 b8b90f8349 refactor(providers): use native adaptive thinking from the langchaingo fork
Adaptive thinking (Claude Opus 4.7+) is now implemented natively in the
vxcontrol/langchaingo fork (v0.1.14-update.6): the anthropic and bedrock clients
emit thinking.type=adaptive + output_config.effort and omit the sampling params
adaptive models reject. PentAGI no longer patches the serialized request body.

- pconfig.PrepareAdaptiveCallOptions appends llms.WithAdaptiveReasoning; the
  ctx-effort plumbing (WithAdaptiveEffort/AdaptiveEffortFromContext) is removed.
- Delete the bedrock smithy Build middleware and anthropic http RoundTripper
  (adaptive_thinking.go + tests in both packages) that rewrote the request body.
- Bump the langchaingo require to v0.1.14-update.6; refresh llms_how_to.md.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 00:47:32 +07:00
Sergey KozyrenkoandClaude Opus 4.8 8670ce4b1e fix(docker): add pnpm global bin to PATH in frontend build stage
pnpm 11 installs globally-added binaries to $PNPM_HOME/bin and treats that
directory being absent from PATH as a hard error, so `pnpm add -g license-checker`
in the frontend-compiler stage failed ("global bin directory is not in PATH")
whenever the frontend layer cache was invalidated. Prepend $PNPM_HOME/bin to PATH.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-21 19:31:18 +07:00
Sergey KozyrenkoandClaude Opus 4.8 9623e9b77a refactor(frontend): reuse the shared provider-icon map in settings-providers
settings-providers.tsx redeclared its own ProviderType→icon map (and imported all
11 icon components) duplicating the registry already in provider-icon.tsx. Export
that map and consume it here, dropping the duplicate map and the 11 icon imports.
providerLabels/providerTypes stay (labels, single-use). No visual change — the
icons still render monochrome at their existing sizes.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-21 19:12:04 +07:00
Sergey KozyrenkoandClaude Opus 4.8 28036f652c refactor(providers): table-driven provider registry
The provider controller repeated every provider type across five hand-written
blocks (default-config wiring, key-gated instantiation, GetProvider fallback,
NewProvider, buildProviderFromConfig) plus the API-layer Valid() whitelist.

Introduce pkg/providers/registry.go: a providerRegistry table whose entries hold
the per-type constructors and credential gating, with small adapter helpers
(ignoreConfig/fromData) absorbing the signature variance (bedrock/ollama/custom
take *config.Config; the rest don't). The controller now wires and looks up
providers in loops over the table. Valid() validates against the new canonical
provider.AllProviderTypes list (no heavyweight import, no cycle).

Adding a provider's backend wiring drops from ~6 edits across these functions to
one registry entry. providers.go shrinks ~300 lines; behavior is unchanged
(same exported funcs, same gating) and all provider/server/graph tests stay green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-21 19:07:11 +07:00
Sergey KozyrenkoandClaude Opus 4.8 93c36483c7 refactor(providers): extract shared openaicompat base for OpenAI-compatible providers
deepseek/glm/kimi/qwen/minimax were near-verbatim clones — identical struct +
13 interface methods, differing only in constants, env accessors, and two flags.
Extract pkg/providers/openaicompat with a Spec + a shared Provider implementing
the interface; each provider now keeps only its constants, embedded config/models,
the Default*/Build* loaders, and a thin New() that delegates to openaicompat.New.
Each provider file drops from ~190 to ~78 lines with zero behavior change (same
exported funcs; per-provider tests stay green). The native openai provider is
intentionally left separate (no model prefix / reasoning-preservation).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-21 18:58:11 +07:00
Sergey KozyrenkoandClaude Opus 4.8 652b8b3bed docs: fix README model-catalog table alignment for opus-4-7/4-8 rows (refs #288)
The added Claude/Bedrock rows put "✅ adaptive-only" in the narrow Thinking
column, which broke the source pipe alignment of the carefully-padded tables.
Use a plain ✅ in the Thinking column (the adaptive-only detail already lives in
the Use Case text and the Adaptive Thinking note) and re-pad the rows so the
columns line up again.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-21 18:25:10 +07:00
Sergey KozyrenkoandClaude Opus 4.8 86b1329c43 fix(providers): surface bedrock models error, make provider type list exhaustive, trim comments (refs #288, #328)
Review nits:
- schema.resolvers.go: log (not swallow) bedrock.DefaultModels errors so an
  invalid BEDROCK_MODELS_PATH no longer yields a silently-empty model list.
- settings-providers.tsx: derive the create-provider type list from an
  exhaustive Record<ProviderType,string> so a future ProviderType is a compile
  error here instead of silently missing from the menu.
- trim two doc comments (convertModelReasoningMode, ReasoningFields) to lead
  with the load-bearing contract instead of restating the name.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-21 18:05:26 +07:00
Sergey KozyrenkoandClaude Opus 4.8 7e61bbea61 refactor(pconfig): centralize adaptive-thinking helpers, dedup bedrock/anthropic (refs #288)
The bedrock and anthropic adaptive_thinking.go files carried ~96 byte-identical
lines (prepareCallOptions, usesAdaptiveThinking, modelReasoningMode,
reasoningConfigForType, agentConfigForType, the effort context key), and
agentConfigForType was a third copy of the agent-type switch pconfig already
owns in GetPriceInfoForType.

Move the model-agnostic logic onto pconfig.ProviderConfig:
AgentConfigForType (now also backing GetPriceInfoForType), UsesAdaptiveThinking,
PrepareAdaptiveCallOptions, and the WithAdaptiveEffort/AdaptiveEffortFromContext
context helpers. Each provider now keeps only its transport-specific pieces:
the smithy Build middleware (bedrock) / http RoundTripper (anthropic) and
rewriteAdaptiveThinkingBody. Also drop the dead delete(payload,"top_k") in the
anthropic rewrite — langchaingo's Messages payload only serializes
temperature/top_p. Backstop tests rewired to the pconfig API; all provider tests
+ go vet pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-21 18:05:07 +07:00
Sergey KozyrenkoandClaude Opus 4.8 d765345051 docs: propagate MiniMax + Claude 4.7/4.8 across deploy files and guides (refs #288, #328)
Code review found the providers were fully wired in code but missing from
several user-facing surfaces:

- MiniMax (#328): add to .env.example, docker-compose env passthrough,
  backend/docs/config.md env table, README provider list + a MiniMax
  configuration section, and backend/docs/database.md PROVIDER_TYPE enum.
- Claude Opus 4.7/4.8 (#288): add to the README Claude and Bedrock model
  catalogs and correct the model counts (10→11 Claude, 21→24 Bedrock); note
  4.7/4.8 are adaptive-thinking-only in the Adaptive Thinking section.
- llms_how_to.md: scope the "Temperature=1.0" rule to budget thinking and add
  an adaptive-thinking caveat (4.7/4.8 reject sampling params), so the guide no
  longer contradicts the shipped adaptive code path.
- docker-compose: point the Bedrock config/models default mount at the tracked
  examples/configs/bedrock-glm-flash.* files (the README-documented path) so a
  plain `docker compose up` no longer creates empty placeholder directories.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-21 18:04:43 +07:00
Sergey KozyrenkoandClaude Opus 4.8 3fc57ff7b7 fix(frontend): reasoning robustness — custom-model reset, max/xhigh→adaptive, range refines (refs #288)
Three QA-found edge cases in the provider form:
- Choosing "Use <x> as custom" set the model without running onOptionSelect, so
  reasoning/price stayed stale for the typed model. Fire onOptionSelect with the
  synthetic option so they reset like a dropdown pick.
- Selecting effort max/xhigh on an adaptive-capable model with mode unset left
  the backend with no way to route the reasoning (it dropped it). Auto-set mode
  to Adaptive, since max/xhigh are adaptive-thinking effort levels.
- Add zod cross-field refines (minLength<=maxLength, reasoning.maxTokens<=32000)
  that native HTML5 validation can't express, mirroring the new backend checks.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-21 16:46:22 +07:00
Sergey KozyrenkoandClaude Opus 4.8 4c0f4204ca feat(pconfig): validate agent config ranges on create/update (refs #288)
The GraphQL createProvider/updateProvider path applied no field validation, so
a direct API call (bypassing the browser's native HTML5 form validation) could
persist nonsensical values (temperature 99, negative price, an inverted
min/max length window, a reasoning budget over the 32000 engine cap).

Add ProviderConfig.Validate()/AgentConfig.Validate(), called after
patchProviderConfig in both CreateProvider and UpdateProvider. It is deliberately
permissive — 0 means "unset" and provider-specific tuning ranges remain the LLM
API's responsibility — so it only rejects universally-invalid values and never a
valid provider-specific config. Found during comprehensive provider QA.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-21 16:46:21 +07:00
Sergey KozyrenkoandClaude Opus 4.8 bfd80b1de9 test(minimax): cover provider whitelist + secret pattern parity (refs #328)
The QA audit found minimax was wired into production everywhere but omitted
from provider-enumeration test data, so a future regression dropping it would
go uncaught. Add minimax to ProviderType.Valid()'s validTypes table, to the
GetSecretPatterns config (expected count 29→30, exercising the "MiniMax Key"
redaction pattern), and to clearConfigEnv's hermetic env list.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-21 16:25:51 +07:00
Sergey KozyrenkoandClaude Opus 4.8 e18169f1a6 fix(frontend): clear stale reasoning.maxTokens on model change (refs #288)
onOptionSelect reset reasoning.mode and reasoning.effort when the agent model
changes but left reasoning.maxTokens untouched, so a budget token value set for
a previous model leaked into the next one (e.g. switching from a budget-capable
model to an adaptive-only model kept the stale value in the form). Reset it
alongside mode/effort. Found during comprehensive provider QA.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-21 16:25:51 +07:00
Sergey KozyrenkoandClaude Opus 4.8 55335feb17 feat(minimax): add MiniMax provider with full app/UI/installer parity (refs #328)
Reworks external PR #328 (octo-patch). The PR added only the provider core;
this brings MiniMax to full parity with the other providers (qwen) so it is
selectable and configurable in the UI and installer.

Applied from the PR (verified against MiniMax's official API docs — M3/M2.7/
M2.7-highspeed are real current models; corrected the M3 description from the
PR's "512K" to the documented ~1M context):
- minimax provider package (OpenAI-compatible https://api.minimax.io/v1),
  config.yml, models.yml, tests; MINIMAX_API_KEY/SERVER_URL/PROVIDER env vars;
  ProviderMiniMax type + DefaultProviderNameMiniMax; providers.go wiring;
  Valid() whitelist.

Added for completeness:
- goose migration adding 'minimax' to the PROVIDER_TYPE enum + database
  ProviderTypeMinimax const.
- GraphQL: minimax in ProviderType enum, ProvidersModelsList,
  ProvidersReadinessStatus, DefaultProvidersConfig; resolvers wire default
  config/models + enabled status; gqlgen regenerated.
- Frontend: MiniMax icon (lobehub), provider-icon + settings-providers
  registration + provider type list; regenerated GraphQL types.
- Installer wizard: provider form, screen, list, registry, env-var mappings,
  locale strings + help text.
- ctester/ftester: -type/-provider minimax support.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-21 15:24:04 +07:00
Sergey KozyrenkoandClaude Opus 4.8 907440609c fix(frontend): control reasoning mode/effort selects so model-change reset shows (refs #288)
The ReasoningFields mode/effort selects used `defaultValue`, making them
uncontrolled — Radix reads it once on mount, so the `setValue` resets in
onOptionSelect (reset reasoning on model change) updated form state but never
the visible selection. Result: after switching models the selectors showed
stale values (e.g. mode "Adaptive" when the field was cleared to null; effort
left blank when a stale 4.7/4.8 "xhigh" had no item under opus-4-6). Switch to
controlled `value` so the display follows the reset. Also drop a dead
empty-comment block in onOptionSelect.

Found during Layer 3 live verification on the docker stack.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-21 06:04:06 +07:00
Sergey KozyrenkoandClaude Opus 4.8 4910b62468 fix(frontend): type ReasoningFields control as Control<FormInput> (refs #288)
The component declared control as Control<FormData> (z.output, required
name/type) but receives the form's Control<FormInput> (z.input, optional
name/type), which `tsc -b` (the production build typecheck) rejects with
"Type 'undefined' is not assignable to type 'string'". `tsc --noEmit -p
tsconfig.json` did not catch it; `pnpm run build` (tsc -b && vite build) now
passes.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-21 05:36:54 +07:00
Sergey KozyrenkoandClaude Opus 4.8 001566c11a test(bedrock,pconfig,converter): cover adaptive-thinking backstop + reasoning (refs #288)
Closes audit-found coverage gaps:
- bedrock: TestBackstopForcesAdaptiveForAdaptiveOnlyModel (adaptive-only model
  forces adaptive with no agent reasoning block) + a negative case for a
  non-reasoning model. The Anthropic backstop already had an httptest test;
  Bedrock had none.
- pconfig: ReasoningConfig.EffectiveMode (incl. max_tokens->budget inference)
  and IsZero.
- converter: ConvertModels reasoning mapping (pconfig adaptive-only ->
  GraphQL adaptive_only, efforts passthrough, nil for no descriptor).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-20 14:35:34 +07:00
Sergey KozyrenkoandClaude Opus 4.8 0fa53a551e fix(frontend): reset agent reasoning when the model changes (refs #288)
Switching an agent's model left the prior reasoning.mode/effort in the form
(onOptionSelect only reset price), so a stale budget mode or an effort the new
model doesn't support could be persisted. Now the model picker also resets
reasoning: adaptive-only models lock to adaptive, others clear mode + effort.

Verified: tsc --noEmit + eslint clean.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-20 14:35:33 +07:00
Sergey KozyrenkoandClaude Opus 4.8 1501aec843 feat(frontend): adaptive thinking controls in provider settings (refs #288)
Ports the per-agent reasoning UI to support adaptive thinking, gated by each
model's declared capability (the reasoning fragment) instead of a model-name
regex:
- new ReasoningFields component: a reasoning Mode select (adaptive | budget,
  shown only for adaptive-capable models, locked to adaptive for adaptive-only)
  and an effort select whose options follow the model's allowed efforts
  (incl. xhigh/max).
- getReasoningEffort handles xhigh/max; getReasoningMode + the form schema and
  transformFormToGraphQL carry the chosen mode through to the API.

Verified locally: tsc --noEmit and eslint clean. Runtime verification on the
stack (Layer 3) is the next step.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-20 11:22:15 +07:00
Sergey KozyrenkoandClaude Opus 4.8 177b138851 feat(anthropic): adaptive thinking + Opus 4.7/4.8 (refs #288)
Extends adaptive-thinking support from Bedrock to the direct Anthropic provider.
langchaingo emits only budget thinking, so adaptive is applied by rewriting the
request body — for Anthropic via an http RoundTripper (the Messages API carries
thinking and sampling params at the top level), wired through the injectable
http.Client. prepareCallOptions forces adaptive for adaptive-only models (the
models.yml capability descriptor is the single source of truth) and stashes the
effort in context for the transport.

- adaptive_thinking.go: RoundTripper + rewrite (thinking->adaptive,
  output_config.effort, display=summarized, strip temperature/top_p/top_k).
- models.yml: add claude-opus-4-7 / claude-opus-4-8 (adaptive-only) + reasoning
  descriptors on the adaptive models (4.6/sonnet-4.6).
- Verified by a credit-free httptest integration test asserting the rewritten
  body on the wire; the shape is also accepted by the real Anthropic API. Full
  live e2e pending account credits/model access.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-20 11:05:59 +07:00
Sergey KozyrenkoandClaude Opus 4.8 014e49494e fix(pconfig): parse ModelConfig.reasoning in custom (un)marshalers (refs #288)
ModelConfig has custom UnmarshalYAML/UnmarshalJSON/MarshalYAML/MarshalJSON that
map fields by hand, so the reasoning capability descriptor added earlier was
silently dropped on load (Reasoning stayed nil). That made the Bedrock
adaptive-only backstop a no-op (modelReasoningMode never saw adaptive-only).
Handle `reasoning` in all four marshalers, mirroring `price`, plus a round-trip
regression test. Found via the anthropic adaptive integration test.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-20 11:05:59 +07:00
Sergey KozyrenkoandClaude Opus 4.8 1cd8a6878c feat(frontend): fetch model reasoning capability (refs #288)
Adds reasoning { mode efforts } to the modelConfigFragment and regenerates
GraphQL types, so the provider settings UI can gate the reasoning mode/effort
controls by each model's declared capability (ModelReasoningMode incl.
adaptive_only) instead of a model-name regex.

Groundwork for the adaptive-thinking settings UI port.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-20 10:29:57 +07:00
Sergey KozyrenkoandClaude Opus 4.8 31780e5262 feat(graph): expose model reasoning capability via GraphQL (refs #288)
Adds ModelReasoningInfo (mode + allowed efforts) to the GraphQL ModelConfig so
the frontend can gate the reasoning mode/effort UI by each model's declared
capability instead of a model-name regex. New ModelReasoningMode enum
(budget | adaptive | adaptive_only) mirrors the models.yml descriptor; the
converter maps pconfig adaptive-only -> GraphQL adaptive_only.

Backend groundwork for the Layer 2 frontend adaptive-thinking UI.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-20 10:26:16 +07:00
Sergey KozyrenkoandClaude Opus 4.8 7b01517bcd feat(bedrock): harden adaptive thinking + add Opus 4.7/4.8 (refs #288)
Makes adaptive-thinking models usable safely and adds Opus 4.7/4.8 to the
catalog so they are selectable and configurable.

- middleware: strip temperature/top_p/top_k and set thinking.display=summarized
  when rewriting to adaptive. Opus 4.7+ reject sampling params (AWS: "no longer
  supported", 400) and default display to "omitted" (empty reasoning text).
- models.yml: add us.anthropic.claude-opus-4-7 and us.anthropic.claude-opus-4-8,
  plus a ModelReasoningInfo capability descriptor (mode + allowed efforts) on the
  adaptive models (4.6/4.7/4.8/sonnet-4.6).
- provider backstop: force adaptive for adaptive-only models (Opus 4.7/4.8)
  regardless of agent config, so selecting them cannot 400 on budget thinking.
  The capability descriptor is the single source of truth (no model-name regex).

Verified: unit tests cover the body rewrite (sampling strip + display); a live
Bedrock run of the adaptive path on us.anthropic.claude-opus-4-6-v1 passed 21/23
(the 2 failures were 429 throttling, not the mechanism). Opus 4.7/4.8 could not
be exercised live -- this AWS account lacks model access (403), not a code
issue; their correctness rests on the AWS docs + the 4.6 live run + unit tests.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-20 10:19:30 +07:00
Sergey KozyrenkoandClaude Opus 4.8 ca9283b93e feat(bedrock): integrate adaptive thinking mechanism backend (refs #288)
Integrates the backend half of PR #288 onto our branch (the frontend is
reworked separately in our codegen style), 3-way merged so the #233
config/models-path changes are preserved:
- adaptive_thinking.go: smithy Build middleware that rewrites the langchaingo
  Converse body from thinking{type:enabled,budget_tokens} to
  thinking{type:adaptive} + output_config.effort, wired via WithAPIOptions and
  prepareCallOptions in Call/CallEx/CallWithTools.
- pconfig: ReasoningConfig.Mode (adaptive|budget) + EffectiveMode/IsZero.
- GraphQL: ReasoningMode enum, reasoning.mode field, xhigh/max effort levels.

Drops the dead llms.WithMetadata adaptive branch from AgentConfig.BuildOptions
(nothing reads opts.Metadata on the Bedrock path; adaptive is applied per-call
by the provider) and updates the unit test accordingly.

Hardening still pending (next commit): strip temperature/top_p/top_k and set
display:summarized for adaptive requests, add Opus 4.7/4.8 catalog entries with
a model reasoning-capability descriptor + force-adaptive backstop, and a live
Bedrock repro. Until then Opus 4.7 should not be selected for an agent.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-20 09:59:48 +07:00
Sergey KozyrenkoandClaude Opus 4.8 06e37d8026 feat(bedrock): support external config and model catalog paths (refs #233)
Reworks PR #233 to follow the existing config-path pattern and make an
externally-added Bedrock model fully usable from the web UI.

- BEDROCK_CONFIG_PATH: replace the embedded per-agent config (model
  assignments + prices), mirroring OLLAMA_SERVER_CONFIG_PATH /
  LLM_SERVER_CONFIG_PATH. DefaultProviderConfig now takes *config.Config
  and reads the external file when set, else the embedded config.yml.
- BEDROCK_MODELS_PATH: merge an external model catalog onto the embedded
  models.yml so new ids appear and are selectable under Settings ->
  Providers. DefaultModels now takes *config.Config and the resolver +
  provider construction pass it through; new ids are added, a matching
  name overrides the embedded entry.

Wires both through docker-compose, .env.example, config.md and the README,
and ships examples/configs/bedrock-glm-flash.{provider,models}.yml using the
real AWS Bedrock id zai.glm-4.7-flash (In-Region, no inference-profile
prefix, 4K max output).

Dropped from #233: the ProviderConfig.Name field and the SeedDefaultProviders
mechanism (a per-user DB write fired on startup and inside the read-only
SettingsProviders resolver) -- the config already reaches the UI through
DefaultProvidersConfig without any DB rows.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-20 08:30:10 +07:00
Sergey KozyrenkoandClaude Opus 4.8 ebe0618dee docs: add Atlas Cloud as a custom OpenAI-compatible provider (refs #332)
Reworks PR #332 to follow the repo's provider-doc convention instead of
its README-marketing form:
- add examples/configs/atlas.provider.yml, modeled on the existing
  aggregator example configs (deepinfra/openrouter/novita)
- list Atlas Cloud in the README aggregators line
- LLM_SERVER_PROVIDER left EMPTY for direct access — it is a LiteLLM
  model-name prefix, and #332 incorrectly recommended `openai`, which
  would break /models discovery for Atlas's vendor-prefixed model ids

Dropped from #332 (not matching any existing aggregator's docs): vendor
logo/banner, UTM-tracked links, and the static 59-model table.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-20 07:43:20 +07:00
Sergey KozyrenkoandClaude Opus 4.8 2107591166 docs: correct password policy in CLAUDE.md to match implementation
The documented "minimum 12 characters" and "common weak passwords
prohibited" did not match the enforced policy. Both backend
(strongPasswordValidatorString / `stpass`) and frontend (zod schema in
password-change-form.tsx) enforce: 8-100 chars, valid if 16+ chars OR
8-15 chars with a number, lowercase, uppercase, and special char from
!@#$&*. No common-password denylist exists in code.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-20 06:56:03 +07:00
mason5052 5be3a409f2 docs: tighten macOS installer warning guidance 2026-06-19 04:45:28 +07:00
mason5052 f37d7c97ed docs: refine macOS installer warning guidance 2026-06-19 04:45:27 +07:00
mason5052 305e071975 docs: add macOS installer warning guidance 2026-06-19 04:45:27 +07:00
mason5052 3ef8b51f36 docs: address review feedback on install/config guide
- Use the package-path form for the tester utilities
  (go run ./cmd/ctester, go run ./cmd/etester test) instead of shell
  glob / single-file invocations, which are more portable and avoid the
  multi-file compile pitfall.
- Add -verbose to the container etester example so it matches the local
  example.
- Wrap the new README Quick Start pointer across multiple lines; rendered
  Markdown is unchanged.
2026-06-19 04:45:20 +07:00
mason5052 ebfd2bd9e9 docs: add installing and configuring guide for first deployment
Issue #61 asked for a proper guide on how to start using PentAGI. A
first-use guide (How to Use PentAGI After Login) already covers what to
do after login, but the maintainer kept the issue open until an article
about installing and configuring the product is published.

Add examples/guides/installation_configuration.md, a concise ordered
walkthrough that connects the existing detailed README sections into a
single path: choose installer vs manual Docker Compose, set core server
variables (PUBLIC_URL, CORS_ORIGINS, security vars), configure and test
an LLM provider with ctester, configure and test the embedding provider
with etester, optionally add search providers and the Graphiti/Langfuse/
observability stacks, then start and verify the stack and change the
default admin password. It ends with a quick checklist and links forward
to the existing post-login usage guide.

The guide links to the relevant README reference sections rather than
duplicating them. A single pointer link is added at the top of the
README Quick Start section for discoverability.

Docs only. No installer behavior, runtime code, env vars, or schema
changes. Every environment variable named in the guide already exists in
.env.example and backend/pkg/config/config.go.
2026-06-19 04:45:20 +07:00
mason5052 642b75836b docs: add embedding troubleshooting for stalled flows (#322)
Add a troubleshooting subsection to the Embedding Configuration and
Testing section for the common case where a flow starts but then waits
indefinitely with no subtasks progressing. As noted on the issue, this
is frequently caused by a misconfigured or unreachable embedding
provider rather than by the flow itself.

The subsection points users to "docker logs pentagi" as the first
check, to the etester "test" command to validate the embedding provider
and database connection without starting a flow, and to the specific
.env settings to verify (EMBEDDING_PROVIDER, EMBEDDING_MODEL,
EMBEDDING_URL, EMBEDDING_KEY, the LLM-provider fallback, PROXY_URL, and
HTTP_CLIENT_TIMEOUT). Documentation only: no new environment variables,
no provider default changes, and no code or test changes.

Refs #322
2026-06-19 04:45:20 +07:00
mason5052 e9a6769116 docs: note primary image selection uses the simple agent type 2026-06-19 04:45:19 +07:00
mason5052 900cbffc8e docs: refine LLM-backend troubleshooting wording (#309)
Address review feedback on PR #325: capitalize SGLang to match the
project's name and clarify that tool calling and function calling
refer to the same capability.

Refs #309
2026-06-19 04:45:19 +07:00
mason5052 3012ddd342 docs: clarify "primary docker image" error is an LLM backend failure (#309)
Add a troubleshooting subsection to the Docker Image Configuration
section explaining that "failed to select primary docker image via llm
call" (older versions: "failed to get primary docker image") is raised
when PentAGI's first LLM call fails during image selection, not when
Docker or the registry is unhealthy. Points users to PentAGI and LLM
backend logs, provider URL/key/model verification, and tool-call parser
configuration for custom/OpenAI-compatible/vLLM/sglang backends.
2026-06-19 04:45:19 +07:00
mason5052 4cee0ba33c fix: harden CLI argument guardrail against xsstrike -o /dev/null 2026-06-19 04:45:05 +07:00
mason5052 aa1ac7a24a fix: avoid unsupported XSStrike flags in prompts 2026-06-19 04:45:05 +07:00
mason5052 6f93856716 docs: add qwen long-flow troubleshooting 2026-06-19 04:45:05 +07:00
mason5052andClaude Opus 4.8 d5a86ff27b feat: add evidence receipt hash chain prototype (#279)
Disabled-by-default audit feature (EVIDENCE_RECEIPTS_ENABLED): appends a
hash-chained JSONL receipt per finished/failed toolcall under
<DATA_DIR>/flow-<id>/evidence/receipts.jsonl, recording toolcall
provenance plus SHA-256 hashes of args/result (no raw content).

Integration adapted to current main: the original PR built the receipt
from a database.Toolcall returned by ce.db.UpdateToolcall*Result, which
the executor no longer uses after the ToolCallLogProvider (tclp) refactor.
Receipts are now built from the in-scope toolcall data at the tclp log
sites and recorded non-fatally, so a receipt failure is logged and never
fails an otherwise-successful toolcall.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-19 04:41:57 +07:00
Sergey KozyrenkoandClaude Opus 4.8 2a4ff3d656 docs: fix false tool-call attribution in parser troubleshooting (#330)
The "failed to select primary docker image via llm call" symptom was
attributed to tool-call parser failures, but image selection is a plain
text completion (providers.go: prv.Call -> WrapGenerateFromSinglePrompt),
not a tool call. That error is a generic LLM-backend failure of the
`simple` agent type and is already covered in its own README section.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-19 04:32:50 +07:00
mason5052 7635100d02 docs: add tool-call parser troubleshooting for custom LLM backends
Issue #313 reported flows that stall after a few steps when running a
custom OpenAI-compatible backend (LiteLLM in front of llama.cpp serving
qwen3.6-35b via LLM_SERVER_*). The backend returned malformed tool-call
arguments, surfaced as 'Failed to parse tool call arguments as JSON'
HTTP 500s and cascading retries. The maintainer fixed the stall in the
latest build by sanitizing wrong function-call arguments.

Add a troubleshooting subsection under Custom LLM Provider Configuration
that explains the root cause and how to diagnose it:

- Custom OpenAI-compatible backends must return valid tool-call
  (function-call) JSON; llama.cpp, SGLang, and vLLM usually require a
  specific tool-call parser and matching chat template, and not every
  setup produces valid tool calls out of the box.
- Symptoms: 'Failed to parse tool call arguments as JSON', flow stalls,
  looping tool calls, the 'failed to select primary docker image via
  llm call' start-of-flow failure, and unexpected backend HTTP errors.
- Investigation: check PentAGI and backend/proxy logs, validate with the
  ctester utility before a full flow, confirm the parser/chat template
  match the model, and update PentAGI (recent builds sanitize malformed
  function-call arguments).

Docs only. No tool-call parser code, provider runtime, schema, migration,
or config-default changes. Wording frames compatibility as dependent on
the backend's OpenAI-compatible tool-call behavior rather than claiming
every llama.cpp backend is supported.
2026-06-19 04:32:22 +07:00
mason5052 3c6bea3c5d fix: return structured error when zip build fails before streaming
Commit the ZIP response status and headers lazily, on the first byte written, via a small zipStreamWriter. A build failure before any output now returns the normal structured error response instead of a committed 200 with a truncated body; mid-stream failures still abort. Also check the reader Close error in the helper test and cover the pre-stream failure path.
2026-06-19 04:20:28 +07:00
mason5052 f7e2ac6615 fix: stream zip downloads without buffering archive
DownloadResource and DownloadFlowFile built the entire ZIP archive in a bytes.Buffer before sending it, so heap usage scaled with archive size and a few concurrent large-directory downloads could exhaust process memory.

Stream the archive straight to the response writer via a shared streamZipArchive helper; the existing ZipResources/ZipDirectory/ZipRelativePaths helpers already accept an io.Writer. Responses are now chunked (no Content-Length) and memory stays proportional to one file's copy buffer.
2026-06-19 04:20:28 +07:00
mason5052 e8a26c6d2c docs: clarify crawler RFC config sketch and scope_decision
Address Copilot review on PR #350: note that default_backend selects a crawl backend and passive extractors such as jsfinder are not selectable there; model scope_decision as a decision plus reason in both the field list and the JSON example; add an illustrative scope_entries example and clarify when allowed_hosts applies.

Refs #336
2026-06-19 04:12:40 +07:00
mason5052 7af46322ca docs: add headless crawler integration RFC
Add examples/proposals/headless_crawler_integration.md, a docs-only RFC proposing an optional, tool-agnostic crawler / URL discovery capability for PentAGI agents. Candidate backends are katana, crawlergo, rad, and jsfinder, framed as candidates with no mandatory default. The RFC keeps dictionary fuzzing (ffuf/dirsearch) unchanged, defines structured discovery artifacts (URLs, forms, parameters, JavaScript endpoints, status codes, source page, depth, scope decision), and keeps crawler URL discovery separate from the BrowserOS MCP interactive browser backend.

Refs #336
2026-06-19 04:12:39 +07:00
mason5052 5980c02854 docs: add recommendation and requested decision to Kubernetes RFC 2026-06-19 04:12:39 +07:00
mason5052 5bf41e0ea1 docs: fix grammar in Kubernetes RFC open question (#324)
Address review feedback on PR #326: rephrase the executor-model open
question so the final clause reads clearly.

Refs #324
2026-06-19 04:12:39 +07:00
mason5052 8dbf8889e0 docs: add Kubernetes deployment compatibility RFC (#324)
Add examples/proposals/kubernetes_deployment.md, an RFC-style design
surface responding to the Kubernetes deployment request in #324. The
document is docs-only: no Helm charts, manifests, operator, compose,
installer, or environment-variable changes, and it does not claim
Kubernetes is supported today.

It records the current Compose/installer deployment assumptions, maps
each one (secrets/config, volumes, service discovery, ingress/TLS,
health checks, network policies, the Docker-socket flow executor,
observability, image overrides, migrations) to candidate Kubernetes
equivalents, and proposes an incremental, docs-first path with open
questions, security/operational considerations, and a test/validation
strategy. The hardest item -- the Docker-socket worker executor -- is
laid out as candidate options without choosing one, and keeps flow
lifecycle explicit and inspectable per the #268 review lesson.

Refs #324
2026-06-19 04:12:39 +07:00
mason5052 760574677b docs: address review feedback on Vertex AI RFC
- Drop the hard-coded provider count to avoid doc drift as providers are
  added; list the current provider types instead.
- Use the ADC-specific command (gcloud auth application-default login)
  rather than the ambiguous 'gcloud login'.
- Reference the enum-swap migration pattern generically under
  backend/migrations/sql/ instead of a single timestamped filename that
  may be renamed or squashed.
2026-06-19 04:12:39 +07:00
mason5052 16669696b6 docs: add native Google Vertex AI provider RFC
Issue #321 requests a native Vertex AI provider with service-account /
ADC auth, opened after #310 clarified Vertex is not supported today. The
issue carries a full implementation outline and four open questions, and
the author asks for direction on adapter strategy and Gemini-vs-Claude
scope before implementing.

Add examples/proposals/vertex_ai_provider.md, a planning RFC that frames
the work before any code is written:

- Distinguishes the current options (AI Studio gemini, direct Anthropic,
  AWS Bedrock, and the custom OpenAI-compatible LiteLLM proxy workaround)
  from the proposed native vertex provider.
- Recommends a staged approach: v1 Gemini-on-Vertex with ADC /
  service-account auth; Claude-on-Vertex deferred to a maintainer
  decision, noting it likely belongs on the Anthropic adapter (Vertex
  auth/endpoint mode) rather than the Gemini-shaped path because the
  message schema differs.
- Models auth on the existing Bedrock multi-auth precedent (ADC default
  chain plus service-account file), and flags that service-account JSON
  is sensitive and must be file-mounted/secret-managed, never pasted into
  UI or logs.
- Captures config/migration touch points (provider checklist, REST
  Valid() whitelist, PROVIDER_TYPE enum-swap migration) so the eventual
  implementation size is clear, and restates the issue's open questions.

Docs/RFC only. No code, schema, migration, generated, frontend, or
provider runtime files are touched, and no new env vars or types are
added; every VERTEX_* key and type named is labeled as a candidate. No
overlap with the provider files in open PR #328.
2026-06-19 04:12:38 +07:00
mason5052 040c69ff28 docs: add recommendation and requested decision to BrowserOS MCP RFC 2026-06-19 04:12:38 +07:00
mason5052 b6f1e61dae docs: add BrowserOS MCP browser backend RFC (#342) 2026-06-19 04:12:38 +07:00
mason5052 92426b9b98 docs: add v1 recommendation and requested decision to fallback RFC 2026-06-19 04:12:38 +07:00
mason5052 44393b0f06 docs: add tool and model fallback RFC 2026-06-19 04:12:37 +07:00
Sergey KozyrenkoandClaude Opus 4.8 1f81800c37 chore(frontend): remove non-functional commitlint setup
commitlint had no config anywhere (no config file, no husky commit-msg
hook), so its rules were never loaded; the "commit" script also pointed
at an uninstalled binary. Remove @commitlint/cli and
@commitlint/config-conventional, the dead "commit"/"commitlint" scripts,
and the stale commitlint entry in README Development Requirements.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-19 03:39:45 +07:00
Sergey KozyrenkoandClaude Opus 4.8 5523582647 chore(frontend): remove unused dependencies
Confirmed unused via depcheck + manual verification:
- anser, js-cookie, @types/js-cookie — no imports anywhere
- rehype-raw — only referenced in a vite manualChunks regex, never
  imported as a markdown plugin (markdown.tsx uses rehype-highlight/slug
  and remark-gfm); also dropped from that regex
- @graphql-codegen/{client-preset,near-operation-file-preset,typescript}
  — codegen config uses explicit plugins (typescript-operations,
  typed-document-node), not these presets/base plugin

Also drop the dead package.json "eslintConfig" block — it is ignored by
the flat config (eslint.config.mjs) and referenced an uninstalled
storybook plugin.

Verified: graphql:generate reproduces src/graphql/types.ts unchanged,
plus build, lint, 604 tests, and --frozen-lockfile all pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-19 03:34:34 +07:00
Sergey KozyrenkoandClaude Opus 4.8 c3f6a02f34 chore(frontend): remove unused eslint-plugin-jsx-a11y
The plugin was a direct devDependency but never enabled in
eslint.config.mjs (0 active jsx-a11y rules via --print-config). Dropping
it removes dead weight and one stale eslint-9 peer constraint. Lint still
passes.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-19 03:04:53 +07:00
Sergey KozyrenkoandClaude Opus 4.8 49d9687c75 chore(frontend): update dependencies to latest within-range
Bump ~60 minor/patch dependencies (Radix UI group, Tiptap 3.27, Apollo
4.2, vite 8.0.16, vitest 4.1.9, typescript-eslint 8.61, react 19.2.7,
react-router 7.18, graphql-codegen 7.1, etc.).

Majors intentionally held back: eslint 10, graphql 17, and @types/node 25
(kept on 24 to match the pinned Node 24.17.0 runtime).

Verified: build, lint, prettier, and 604 tests pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-19 02:54:57 +07:00
Sergey KozyrenkoandClaude Opus 4.8 9b073e2183 build(frontend): pin Node 24.17.0 and pnpm 11.8.0 across all builds
- add frontend/.nvmrc (24.17.0) as the single source of truth for Node;
  GitHub CI reads it via node-version-file, Dockerfile uses node:24.17.0-slim
- bump packageManager to pnpm@11.8.0; drop "corepack prepare pnpm@latest"
  so the pnpm version derives from packageManager everywhere
- migrate pnpm onlyBuiltDependencies -> allowBuilds in pnpm-workspace.yaml
  (the package.json "pnpm" field is no longer read by pnpm 11)
- add a CI step that fails if the Dockerfile Node tag drifts from .nvmrc

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-19 02:50:39 +07:00
Sergey KozyrenkoandClaude Opus 4.8 11db9c2e0c feat(webui): merge file-manager folder/chevron into one hover toggle
The directory expand/collapse control now shows the folder icon by
default and crossfades to a chevron on hover (motion, reduced-motion
aware); the single element toggles expansion on click. Nesting indent
gains the icon->text gap (22px/level) so a child's icon lines up under
its parent's label, and the header expand-all control moves to the
shared Button. Folder and chevron share the text-blue-400 accent set on
the parent (header chevron picks it up on hover).

Also prunes ~46 restatement/justification comments and a dead
collectAllFilePaths export (plus its tests) to match the house style.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-17 05:45:00 +07:00
Sergey KozyrenkoandClaude Fable 5 b6db0b59ad ci(webui): make all frontend CI checks blocking
Prettier / Lint / Test were `continue-on-error: true` (advisory — failures did not fail CI), the same gap that let type errors pile up. Now Prettier, Lint, Type check and Test all block the lint-and-test job (which runs on every branch push).

Prerequisite: `prettier --write` on 5 pre-existing non-conformant files (pages/login.tsx, lib/report/report-pdf.tsx, 3 *.test.tsx) so the now-blocking Prettier check passes — pure formatting, no logic change. Install stays advisory (setup step); backend checks unchanged.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-16 22:48:05 +07:00
Sergey KozyrenkoandClaude Fable 5 52951ceb43 ci(webui): gate build and CI on TypeScript errors
vite build strips types and never type-checks, and the old build`s bare tsc (solution config, files:[]) checked nothing — so type errors reached main unnoticed (which is how 76 had accumulated). Now they fail fast everywhere.

- build: `tsc -b && vite build` — `pnpm build` (and the Docker image build, which runs `pnpm run build`) fails on any type error before bundling.

- add `typescript` script (`tsc -b`, checks both app + node project configs).

- ci.yml: blocking "Frontend - Type check" step in lint-and-test (runs on every branch push; docker-build only runs on main/tags).

Verified: a type error makes both `pnpm run typescript` and `pnpm build` exit non-zero (vite never runs); removing it restores a clean build.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-16 22:37:18 +07:00
Sergey KozyrenkoandClaude Fable 5 895de4cadc fix(webui): resolve settings-provider type errors — frontend now 0 tsc errors
The provider form had 23 errors rooted in Zod v4: `z.preprocess` gives an `unknown` input type, which @hookform/resolvers v5 surfaces as the form field-values type, mismatching `useForm<output>` and cascading to every Control<FieldValues> site.

- Replace `z.preprocess` with explicit helper schemas (proper input/output types) and use `useForm<FormInput, unknown, FormData>`; make the reusable field components generic `<T extends FieldValues>` (Control<T> + FieldPath<T>).

- Fetch `thinking` on the model-config fragment (regenerated types.ts; backend ModelConfig.thinking exists).

- Validate the provider `type` into the ProviderType enum via `z.nativeEnum(...).parse` at the GraphQL boundary instead of an `as` cast (the form intentionally uses watch() to keep disabled fields in the payload, so its values stay input-typed).

tsc: 23 → 0; the frontend now has zero TypeScript errors. 606 tests pass; eslint + prettier clean.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-16 22:05:09 +07:00
Sergey KozyrenkoandClaude Fable 5 3b6464e710 fix(webui): resolve 53 pre-existing TypeScript errors
Hack-free fixes (no `as any`/`@ts-ignore`/`as unknown as`):

- tsconfig lib es2023 for Array.findLast; tighten DocumentTitle TitleResolver to ApolloTitleComponent (the broad ComponentType was masked by findLast returning any).

- NodeJS.Timeout → ReturnType<typeof setTimeout> in browser code; models import casing (./User → ./user).

- settings prompt/api-token forms: type against the real generated fragment types and the Zod input/output split (useForm<Input, ctx, Output>); generic FormTextareaItem<T>.

- data-table / detail-nav: noUncheckedIndexedAccess guards; React vs DOM KeyboardEvent disambiguation; drop invalid user-event delay option.

tsc: 76 → 23 (the remaining 23 are one settings-provider Zod/RHF cluster). 606 tests pass; eslint + prettier clean.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-16 21:32:21 +07:00
Sergey KozyrenkoandClaude Fable 5 d1bfe368a2 build(webui): drop deprecated baseUrl from tsconfig, rely on path mapping
TypeScript 6.0 deprecated `baseUrl` (removed in 7.0). The `@/*` alias resolves relative to each tsconfig without it, and Vite resolves `@` via its own resolve.alias, so baseUrl was vestigial. Dropping it removes the need for `ignoreDeprecations: "6.0"`, which editor-bundled TypeScript (5.x) flagged as an invalid value (TS5103).

Also drop the dead `@env`/`./env.ts` entry from tsconfig.node.json: the file does not exist and the alias is imported nowhere.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-16 17:02:11 +07:00
Sergey KozyrenkoandClaude Fable 5 962e648fe1 refactor(webui): migrate to Apollo Client v4 typed-document-node codegen
Replace the deprecated typescript-react-apollo codegen plugin (unmaintained for Apollo Client v4) with typed-document-node. All ~105 useXxxQuery/Mutation/Subscription call sites are rewritten to the generic useQuery/useMutation/useSubscription(XxxDocument, ...) form, with skipToken replacing skip + conditional-variables.

graphql-codegen.ts: plugins typescript-operations + typed-document-node; add scalars { Time: string } (was unknown); drop withHooks/apolloReact* options. tsconfig.app/node.json: ignoreDeprecations "6.0" for the baseUrl TS5101 deprecation. Regenerate src/graphql/types.ts.

Behavior-preserving: variables, fetchPolicy, error handling, and subscription onData/refetchQueries are unchanged.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-16 16:07:57 +07:00
Sergey KozyrenkoandClaude Fable 5 8bd6c72f63 fix(knowledge): preserve document content when list query writes empty body
The /knowledges list query fetches documents with `withContent: false` to save bandwidth, writing an empty `content` to the shared normalized KnowledgeDocument cache entity. That clobbered the full body loaded by the detail query, so opening a document by direct URL (or reload) showed an empty editor.

Add a `content` field merge policy so an empty incoming value never blanks out a body already loaded.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-16 16:07:17 +07:00
Sergey KozyrenkoandClaude Fable 5 942fb45c16 feat(knowledge): dedicated renameKnowledgeDocument mutation, lighter list
Rename a knowledge document via a dedicated mutation that rewrites only the
question in cmetadata — no re-embedding, no embedder required — mirroring the
flows renameFlow pattern instead of round-tripping the full document through
updateKnowledgeDocument.

Backend:
- renameKnowledgeDocument(id, question) mutation + resolver (admin/user split;
  ownership enforced at GetUserDocument, like the update pair)
- metadata-only query UpdateKnowledgeDocumentMetadata (no migration)
- unit + edge tests: metadata-only, missing-doc error, non-owner rejection

Frontend:
- renameKnowledge provider method; wire list and detail inline-rename to it
- drop the content "Preview" column and request the list with withContent:false
  so it no longer pulls full document bodies

Verified end to end against a local Docker backend (rename works; content and
embedding preserved) and against the remote backend (graceful failure where the
mutation is not yet deployed).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-15 13:15:57 +07:00
Sergey KozyrenkoandClaude Fable 5 6d9453a5a2 refactor(webui): type away the any's in settings-provider
Replace 13 `any` usages with real shapes: ProviderTest / ProviderTestResults
for the test-mutation payload, Control<FieldValues> for the form control, and
inferred element types in the result maps. Collapse the two duplicated
3-level-nested error-formatting blocks into one recursive formatFormErrors
helper — validation error output is byte-identical (verified against the same
inputs).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-15 00:35:40 +07:00
Sergey KozyrenkoandClaude Fable 5 da63ced002 refactor(webui): silence the React-Compiler incompatible-library lint
react-hooks v6 ships this rule, but it only carries signal once the React
Compiler is enabled; until then it flags every RHF watch() and useReactTable
as unactionable noise (12 hits). Turn it off project-wide and drop the
now-redundant inline disable in use-element-virtual-list.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-15 00:35:32 +07:00
Sergey KozyrenkoandClaude Fable 5 7c90ec4f92 fix(webui): escape the CJK Unicode range in the PDF report regexes
The CJK-detection regexes embedded a literal U+3000 ideographic space inside
their character class, which ESLint flagged as no-irregular-whitespace (error).
Switch the fullwidth ranges to \u escapes ( -〿＀-￯) — identical
match behaviour (verified: Han / U+3000 / fullwidth match, ASCII does not), no
irregular whitespace in source.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-15 00:11:38 +07:00
Sergey KozyrenkoandClaude Fable 5 c382d35a52 refactor(webui): drop the unused virtualizer escape hatch from useWindowVirtualList
No consumer reads the returned `virtualizer` (data-table destructures only the
spacer / measure fields), and exposing the raw instance leaks the abstraction —
the same dead, over-broad return just removed from useElementVirtualList. Drop it.

Also correct a stale doc claim: react-virtual does have an `enabled` option (it
gates the scroll listeners), the hook just doesn't surface it — so the
conditional-mount guidance stands without the false "no enabled option" note.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-14 23:56:24 +07:00
Sergey KozyrenkoandClaude Fable 5 fdb5c7b86e perf(webui): virtualize the DetailNavigationSheet listbox
The sheet rendered every filtered option (1797 on a busy flows list), so the
filter re-render and the DOM weight (~1800 nodes) made filtering jank. Above a
100-item threshold the listbox now virtualizes via a new element-scroll
useElementVirtualList hook (the inner-container analogue of useWindowVirtualList):
only the ~30-node visible window is mounted. Small lists — and JSDOM tests —
keep rendering in full.

Roving focus onto an off-screen option scrolls it into view and focuses it once
its row mounts (pendingFocusId), so arrows/Home/End and open-time focus on the
current item work across the virtualized window. Options carry aria-setsize /
aria-posinset so screen readers still see the full count and position.

Measured live (chrome-devtools, test.pentagi.net, 1797-flow sheet): DOM nodes
~1800 → ~32; typing INP 258ms → ~200ms. The remaining cost is the flow.tsx page
re-render when the controller's filtered list changes (debounce flush) — a
separate concern. Open / End / Home / typing focus all verified; full suite green.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-14 23:21:35 +07:00
Sergey KozyrenkoandClaude Fable 5 92a9e595e0 perf(webui): decouple DetailNavigationSheet search from the page render
Typing in the sheet's search lagged badly (INP ~600ms on a 1797-item list): the
input bound to the controller's searchQuery, whose state lives in the page-level
hook (flow.tsx), so every keystroke re-rendered the whole detail page AND rebuilt
all ~1800 option rows before the caret could echo — characters appeared in batches.

Mirror the input value in local sheet state (instant caret echo, re-renders only
the sheet) and push to the controller in a transition (filtering + prev/next stay
correct; the heavy re-render no longer blocks the keystroke). Memoize the option
rows so a keystroke that only changes the local mirror does not rebuild them.

Measured live (chrome-devtools, test.pentagi.net, 1797-flow sheet): typing INP
606ms -> 258ms; all characters land, focus stays on the input. The residual is the
DOM reconciliation when the filter changes — addressed next by virtualizing the list.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-14 22:09:40 +07:00
Sergey KozyrenkoandClaude Fable 5 4cb25ac469 fix(webui): move DetailNavigationSheet focus to explicit navigation only
Focus was driven off `focusedId` through an effect, so a reconciliation-driven
change (the filter shrinking and re-pinning to the first survivor) also moved
DOM focus, yanking it off the search input mid-type. Two document.activeElement
guards (the second added in 5a7bdca) papered over the timing; the rAF re-check
only ever fired under JSDOM and was dead in real browsers — verified live.

Move focus imperatively only where the user navigates: opening the sheet now
uses Radix's onOpenAutoFocus (preventDefault + focus the current option, with no
rAF race against the focus trap), arrow keys focus synchronously in the key
handler, and render-phase reconciliation only updates the roving tabindex. Both
guards, the effect and the rAF are gone, and the previously-flaky focus-steal
test is deterministic (10/10 isolated).

Verified live (chrome-devtools, test.pentagi.net, 1797-flow sheet): open focuses
the current option, typing keeps focus on the input with no dropped chars, and
arrows / ArrowDown-from-input move focus.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-14 22:08:58 +07:00
Sergey KozyrenkoandClaude Fable 5 345c26eea7 fix(webui): let account settings sections edit independently
The account page tracked a single `editing` section, so opening one editor
unmounted any other open form and silently discarded its unsaved input. Track
an open-section set instead: opening a section no longer closes the others, so
a half-typed draft survives switching between name, email and password.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-14 16:17:41 +07:00
Sergey KozyrenkoandClaude Fable 5 5765b05c19 feat(webui): give PasswordChangeForm horizontal/vertical layouts for the forced screen
The forced password-change screen reused the compact account-card footer, so it
rendered small right-aligned buttons that clashed with the full-width "Sign in"
CTA on the same login page. Add two orthogonal props: layout
('horizontal' default | 'vertical') drives footer direction and button width;
buttonSize ('default' default, mirroring Button) drives size. The forced screen
passes layout="vertical" (full-width stacked buttons, submit on top, matching the
login button language); the account cards pass buttonSize="sm" to stay compact.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-14 16:04:14 +07:00
Sergey KozyrenkoandClaude Fable 5 6000bc8310 refactor(webui): drop redundant isModal/showSkip flags from account forms
isModal (gated the Cancel button) and showSkip (gated the Skip button) were
redundant with the onCancel/onSkip callbacks they always paired with: every
call site that set a flag also passed the matching handler, and none passed a
handler while wanting the button hidden. Render each button from its callback's
presence instead. Removes two props and a name that misdescribed its job
(isModal gated a button, not a modal).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-14 15:35:08 +07:00
Sergey KozyrenkoandClaude Fable 5 1cc7d26987 refactor(webui): migrate remaining route literals to registry, add drift test
The first migration pass missed call sites where the path is nested inside a
helper rather than passed straight to navigate/to: detail-navigation getHref
helpers, mergeHrefWithSearchParams row-open handlers, the knowledge create
redirect, the flow report window.open targets (wiring up the unused
routes.flowReport builder), and the OAuth return_uri. All now build from routes.

Add routes.test.ts: every builder output is asserted to match the app.tsx route
pattern that serves it via matchPath, guarding URL<->pattern sync, plus exact
checks for query encoding and the login return-url guard.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-14 14:20:04 +07:00
Sergey KozyrenkoandClaude Fable 5 6fa9077f21 refactor(webui): migrate main navigation to lib/routes
Step 4 of the route-registry migration: dashboard/flows/templates/knowledges/resources
navigation builds from lib/routes.

- routes.ts gains newKnowledge and newTemplate (sentinel ":id=new" routes)
- main-sidebar nav links + recent-flow link -> routes.* / routes.flow(id)
- app.tsx root and catch-all redirects -> routes.dashboard
- flow/flows/new-flow, knowledge/knowledges, template/templates page navigations ->
  routes.flows / routes.flow(id, { tab }) / routes.newFlow / routes.knowledges /
  routes.newKnowledge / routes.templates / routes.newTemplate

useMatch('/x/*') patterns stay literal — they are route-matching globs, not URLs the
registry builds.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-14 13:53:14 +07:00
Sergey KozyrenkoandClaude Fable 5 dc6b3a9e2c refactor(webui): route auth redirects through lib/routes
Step 3 of the route-registry migration: every /login redirect and post-login landing
fallback builds from lib/routes instead of hardcoded strings.

- protected-route, axios 401/403 interceptor, user-provider (logout, session-expiry,
  /login + public-route checks) -> routes.login(...) / routes.login()
- oauth-result error redirect -> routes.login()
- login-form / public-route / login page post-login fallback -> routes.newFlow

getReturnUrlParam now has a single in-app caller (the routes.login builder) plus the
logout suffix-override; dropped its now-unused imports from axios and protected-route.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-14 13:45:46 +07:00
Sergey KozyrenkoandClaude Fable 5 d71feaf854 refactor(webui): migrate settings provider/prompt page navigations to routes
Step 2 of the route-registry migration: the provider/prompt settings pages build their
navigate() targets from lib/routes instead of hardcoded strings.

- settings-providers: provider(id), newProvider({ id | type }), newProvider()
- settings-provider: routes.settings.providers (x5)
- settings-prompts: routes.settings.prompt(name)
- settings-prompt: routes.settings.prompts (x2)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-14 13:37:39 +07:00
Sergey KozyrenkoandClaude Fable 5 ae45bd7c4f refactor(webui): add a central route registry; migrate the settings shell
Introduce lib/routes.ts as the single source of truth for client route paths, with typed
builders for parameterised routes (flow, provider, prompt, login return-url, ...). First
migration step covers the settings shell we own:

- app.tsx settings index/catch-all redirects -> routes.settings.account
- main-sidebar Settings/Profile links -> routes.settings.root / .account
- settings-layout menu items + the "Back to App" fallback -> routes.*

The rest (settings provider/prompt pages, auth redirects, main nav) migrate in follow-ups.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-14 13:29:32 +07:00
Sergey KozyrenkoandClaude Fable 5 4b4e93c603 fix(webui): land /settings on Account, the first menu item
Account was added as the first settings sidebar item, but the index and catch-all
routes still redirected to /settings/providers, so the gear "Settings" link dropped
the user on the second item. Point both redirects at /settings/account.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-14 12:43:29 +07:00
Sergey KozyrenkoandClaude Fable 5 bc80aac985 fix(webui): derive the account avatar initial by code point
(displayName).charAt(0) returns the first UTF-16 unit, so a non-BMP first character
(emoji, rare CJK) rendered as a lone surrogate (�). Spread to iterate by code point.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-14 12:36:47 +07:00
Sergey KozyrenkoandClaude Fable 5 86c7616efa fix(webui): return "Back to App" to the page the user came from
The settings shell's only exit was a "Back to App" link hardcoded to /flows, so opening
Settings or Profile from anywhere dropped the user at the flows list on the way out.

- the Settings and Profile entry links pass the current path as location.state.from
- SettingsLayout captures it once on entry (surviving sub-tab navigation, which drops
  state) and points "Back to App" there, falling back to /flows
- tests: SettingsLayout honors the origin / falls back / preserves it across sub-tabs;
  MainSidebar's Settings and Profile links carry the origin

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-14 12:06:38 +07:00
Sergey KozyrenkoandClaude Fable 5 9b9a74bec0 refactor(webui): share the API-error → message mapping across account forms
The three account forms duplicated the getApiErrorCode + ERROR_BY_CODE lookup pattern
verbatim, and each carried a dead `AuthRequired` entry that the axios interceptor
already handles (hard redirect) before the form's catch can render it.

- add resolveApiErrorMessage(err, map, fallback) next to the axios error helpers
- email/name/password forms use it and drop the unreachable AuthRequired entry
- unit-test the helper's precedence (mapped code > server msg > fallback)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-14 11:40:39 +07:00
Sergey KozyrenkoandClaude Fable 5 789caf0dfe fix(webui): keep the session on a transient /info failure; update user cache optimistically
A network blip or 5xx on an /info refresh — after an email/name change or on plain
navigation — wrongly cleared local auth and bounced the user to /login, even though the
session cookie was still valid (the axios interceptor already handles real 401/403).

- refreshAuthInfo and the navigation refresh now keep the current session on a transient
  /info failure instead of clearing auth and redirecting to /login
- add patchUser so the email/name forms reflect the change immediately, dropping the
  dependency on a successful /info round-trip for the visible field
- tests: UserProvider keeps the session on transient failure (refresh and navigation
  paths); forms call patchUser with the new value

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-14 11:18:39 +07:00
Sergey KozyrenkoandClaude Fable 5 96f346e6ec test(webui): cover account page OAuth gating and the name-change form
- settings-account: local accounts expose name/email/password; OAuth accounts hide
  the password card and email editing, keep the name editable, and label the provider
  (known label, raw fallback, then generic); renders nothing without a user
- name-change-form (previously untested): seeds the current name, submits the trimmed
  value and refreshes auth, blocks an empty name, maps Users.NotFound to friendly copy

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-14 10:42:58 +07:00
Sergey KozyrenkoandClaude Fable 5 9a5a8b53a5 fix(server): return 404 from name change when the user no longer exists
ChangeNameCurrentUser issued a bare UPDATE and ignored RowsAffected, so a stale
session for a deleted user got 200 — inconsistent with the email/password handlers
(which 404) and leaving the frontend's Users.NotFound mapping unreachable.

- check RowsAffected and return ErrUsersNotFound (404) when no row matched
- document the 404 in the swagger annotation
- add TestChangeNameCurrentUser (success, missing user, invalid name)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-14 10:35:52 +07:00
mason5052 5dad31d90e docs: add recommendation and requested decision to Kubernetes RFC 2026-06-13 23:07:13 -04:00
mason5052 a03c29589d docs: add recommendation and requested decision to BrowserOS MCP RFC 2026-06-13 23:04:56 -04:00
mason5052 673671cd0c docs: add v1 recommendation and requested decision to fallback RFC 2026-06-13 23:03:21 -04:00
mason5052 bd1bb75c2f fix: harden CLI argument guardrail against xsstrike -o /dev/null 2026-06-13 22:58:43 -04:00
mason5052 da039383e2 docs: note primary image selection uses the simple agent type 2026-06-13 22:52:42 -04:00
mason5052 1043084050 docs: clarify crawler RFC config sketch and scope_decision
Address Copilot review on PR #350: note that default_backend selects a crawl backend and passive extractors such as jsfinder are not selectable there; model scope_decision as a decision plus reason in both the field list and the JSON example; add an illustrative scope_entries example and clarify when allowed_hosts applies.

Refs #336
2026-06-13 22:37:48 -04:00
mason5052 364fbd4010 docs: add headless crawler integration RFC
Add examples/proposals/headless_crawler_integration.md, a docs-only RFC proposing an optional, tool-agnostic crawler / URL discovery capability for PentAGI agents. Candidate backends are katana, crawlergo, rad, and jsfinder, framed as candidates with no mandatory default. The RFC keeps dictionary fuzzing (ffuf/dirsearch) unchanged, defines structured discovery artifacts (URLs, forms, parameters, JavaScript endpoints, status codes, source page, depth, scope decision), and keeps crawler URL discovery separate from the BrowserOS MCP interactive browser backend.

Refs #336
2026-06-13 22:33:11 -04:00
Sergey KozyrenkoandClaude Fable 5 c14ba936fb fix(auth): accept mixed-case and long-TLD emails; normalize on change
The vmail validator rejected addresses the frontend's z.string().email() accepts
(uppercase, TLDs longer than 4 chars like .cloud), so users saw a confusing 400.

- relax the vmail regex to allow uppercase and TLDs of 2+ chars
- lowercase + trim the new address in ChangeEmailCurrentUser and in the form schema
  so storage, the duplicate check, and login lookups stay case-stable
- validator + change-email tests for mixed case and long TLDs

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-13 19:26:44 +07:00
Sergey KozyrenkoandClaude Fable 5 06178bf868 fix(server): link OAuth logins to existing accounts by email; harden email change
- authLoginCallback matches users by email alone so an OAuth login links into an
  existing (incl. local) account instead of 500-ing on users_mail_unique
- relink on a create-branch unique-violation race instead of returning 500
- issue the session with the linked account's actual role privileges
- clear the stale OAuth provider link when a user changes their email
- map the email-change unique-violation race to 409 instead of 500
- isUniqueViolation matches Postgres and SQLite case-insensitively
- tests for link/create/blocked/role-inheritance/race, email 409, provider reset
- update auth form test selectors after the form refactor

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-13 19:00:26 +07:00
Sergey KozyrenkoandClaude Opus 4.8 901753e8d1 feat(webui): show the Profile menu shortcut for OAuth users too
The account page is already available to OAuth users, so drop the
local-only gate on the user-menu "Profile" item to match.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-13 03:00:36 +07:00
Sergey KozyrenkoandClaude Opus 4.8 273592ec29 feat(webui): open account page to OAuth users, edit display name, consistent forms
- Keep /settings/account available to OAuth users: drop the redirect and
  the local-only sidebar gate. Show the auth provider (Google/GitHub) on
  the summary badge, render the email read-only, and hide the password
  card for OAuth accounts. Fix the `provide` -> `provider` typo in User.
- Add a "Display name" card + NameChangeForm (PUT /user/name) for all users.
- Make the email/password forms consistent: lead with Current Password,
  unify placeholders ("Enter your ..."), drop the redundant Current Email
  field, and size form buttons to match the "Change" buttons.
- Rename the user-menu item "My Profile" -> "Profile".

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-13 02:56:38 +07:00
Sergey KozyrenkoandClaude Opus 4.8 7d504914b8 feat(server): persist OAuth provider and add self-service name change
- OAuth login callback now stores the provider (google/github) on the
  user record and backfills it for pre-existing OAuth users on login,
  so the UI can show which provider an account is linked to.
- Add PUT /user/name for any authenticated user (including OAuth): a
  NameChange model + ChangeNameCurrentUser handler that lets users edit
  their display name. Placed in a /user group without localUserRequired.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-13 02:56:15 +07:00
Sergey KozyrenkoandClaude Opus 4.8 82b82c5f49 chore(webui): remove dead monaco-terminal component and monaco deps
monaco-terminal.tsx had no importers; drop it together with the now-unused
monaco-editor and @monaco-editor/react dependencies (~3 MB). The component is
preserved on branch feature/frontend-monaco-terminal for later work.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-12 21:44:17 +07:00
Sergey KozyrenkoandClaude Fable 5 5a7bdca4ac fix(webui): re-check focus before stealing it in DetailNavigationSheet
Stabilizes a flaky test ("does not yank focus onto a listbox option when
filteredItems shrinks"): the rAF that moves roving focus now re-checks
document.activeElement before calling focus(), so a focus bounce between
the effect's gate check and the next frame no longer steals focus.

Provisional: the race only reproduces under JSDOM focus simulation (not in
real browsers), so the proper fix likely belongs in the test layer — to be
revisited separately.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-12 17:40:41 +07:00
Sergey KozyrenkoandClaude Fable 5 ed55924873 refactor(webui): drop space-y/space-x for flex gap; fix calendar month offset
Replace the few remaining space-y-*/space-x-* utilities with flex + gap to
match the codebase convention (only the vendored calendar primitive used
them outside this set).

In calendar.tsx the naive space-y→gap conversion shifted the date grid 16px
right: the months flex container holds a zero-width nav wrapper (its prev/
next buttons are absolutely positioned), so gap-4 spaced the (empty) nav from
the month. Drop the gap on months; keep it on month (caption ↔ grid, both
real children).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-12 17:40:21 +07:00
Sergey KozyrenkoandClaude Fable 5 ddb654651e feat(webui): account settings page for email & password
Replace the "My Profile" modal with a dedicated /settings/account page in
the existing settings sidebar (first nav item, gated to local accounts —
OAuth users are redirected). Email and password are edited inline via a
read-view → form pattern with a summary card.

- Extract a reusable InputPassword control built on input-group; use it in
  login and both account forms (consistent focus ring + invalid border).
- Add getApiErrorCode and a per-form code→message map so backend error
  codes surface friendly copy (the prior mapping was dead — msg always won).
- Co-locate form tests next to their source files.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-12 17:40:05 +07:00
Sergey Kozyrenko 182642ba6b Merge pull request #340 from Akalanka1337/user-profile-email-update
Replace Change Password with My Profile (email and password update)
2026-06-11 19:35:53 +07:00
Sergey KozyrenkoandClaude Fable 5 99c8b6786c fix: recover from stale-chunk and DOM-desync SPA crashes
Two crashes seen in production, both reproduced on the live app:

- "Failed to fetch dynamically imported module": after a redeploy rotates the
  hashed chunk filenames, an open tab imports a deleted one. The server answered a
  missing /assets/* with 301 -> index.html (HTML for a JS module -> a MIME
  failure); it now returns 404 + no-store. The client listens for Vite's
  vite:preloadError and reloads once (debounced) to pull the current build. Hashed
  assets are served immutable; index.html and SPA routes no-cache.

- "Failed to execute 'removeChild' ... not a child of this node": an external
  agent (a browser extension or auto-translation) mutates the DOM React owns,
  desyncing reconciliation. A root react-router errorElement catches this
  commit-phase crash and self-heals with a debounced reload, instead of React
  Router's dead default error screen. translate="no" opts the English-only UI out
  of the one trigger it can prevent (browser translation); the errorElement covers
  the rest regardless of source.

Verified by reproducing both on the live old build (missing-chunk 301->HTML;
extension/translation DOM mutation -> the exact removeChild crash) and confirming
the fixed build recovers from each. Adds chunk-reload + RouteErrorBoundary unit
tests and a static-serving integration test.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-11 17:32:34 +07:00
Sergey Kozyrenko 9e1b093f70 Merge branch 'main' into feature/frontend-next 2026-06-10 17:37:15 +07:00
mason5052 1e19b70988 docs: add qwen long-flow troubleshooting 2026-06-09 20:09:55 -04:00
mason5052 1a7012c1f5 docs: add tool and model fallback RFC 2026-06-09 20:08:46 -04:00
mason5052 6146bc6b44 docs: add BrowserOS MCP browser backend RFC (#342) 2026-06-09 20:05:37 -04:00
mason5052 0d40ad8f25 fix: avoid unsupported XSStrike flags in prompts 2026-06-06 19:52:31 -04:00
Akalanka1337 82bca05ac3 feat(webui): replace Change Password with My Profile (email and password updates) 2026-06-05 23:51:36 +05:30
mason5052 41524bd07e fix: return structured error when zip build fails before streaming
Commit the ZIP response status and headers lazily, on the first byte written, via a small zipStreamWriter. A build failure before any output now returns the normal structured error response instead of a committed 200 with a truncated body; mid-stream failures still abort. Also check the reader Close error in the helper test and cover the pre-stream failure path.
2026-06-05 10:16:52 -04:00
mason5052 556692aeb1 fix: stream zip downloads without buffering archive
DownloadResource and DownloadFlowFile built the entire ZIP archive in a bytes.Buffer before sending it, so heap usage scaled with archive size and a few concurrent large-directory downloads could exhaust process memory.

Stream the archive straight to the response writer via a shared streamZipArchive helper; the existing ZipResources/ZipDirectory/ZipRelativePaths helpers already accept an io.Writer. Responses are now chunked (no Content-Length) and memory stays proportional to one file's copy buffer.
2026-06-05 10:04:03 -04:00
Sergey KozyrenkoandClaude Opus 4.8 831f0e213e refactor(frontend): extract DataTable virtualization into a headless hook
Lifts the inline useWindowVirtualizer wiring from a8c3fbc into a reusable
useWindowVirtualList hook plus dedicated VirtualizedTableBody / DataTableRow
/ PaddingRow components, mounted only past the row threshold so
non-virtualized tables pay no window/ResizeObserver listener cost.

Corrects two latent issues from the inline version:
- Scroll anchor moved from the table wrapper (above <thead>) to <tbody>,
  removing a header-height offset in the virtualizer's coordinate math that
  overscan was masking. Overscan dropped 10 -> 5.
- Rows forward the stable virtualizer.measureElement ref instead of a
  per-row arrow recreated each render, so React no longer detaches and
  re-measures every visible row on every render.

Hardening:
- data-index + measure ref bundled into one `measurement` prop so the
  "both or neither" invariant lives in the type, not a comment.
- a11y: virtualized tables expose aria-rowcount and per-row aria-rowindex,
  so assistive tech sees the true total instead of only the ~20 rows in the
  DOM.
- Hook observes only document.body for above-anchor layout shifts; the
  anchor's own resize can't move its top edge, so observing it was dead.

Tests cover threshold gating, the renderSubComponent opt-out, the aria-row
attributes, and that data-index survives the Radix asChild context-menu
wrapper (the live /flows path).

Verified in-browser on /flows (1116 rows): 16 rows in the DOM,
aria-rowcount 1117, correct recycling top -> middle -> bottom, context menu
intact, zero console errors.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-05 13:25:23 +07:00
mason5052 620e699e71 docs: address review feedback on install/config guide
- Use the package-path form for the tester utilities
  (go run ./cmd/ctester, go run ./cmd/etester test) instead of shell
  glob / single-file invocations, which are more portable and avoid the
  multi-file compile pitfall.
- Add -verbose to the container etester example so it matches the local
  example.
- Wrap the new README Quick Start pointer across multiple lines; rendered
  Markdown is unchanged.
2026-06-03 23:06:11 -04:00
mason5052 5c968919ec docs: address review feedback on Vertex AI RFC
- Drop the hard-coded provider count to avoid doc drift as providers are
  added; list the current provider types instead.
- Use the ADC-specific command (gcloud auth application-default login)
  rather than the ambiguous 'gcloud login'.
- Reference the enum-swap migration pattern generically under
  backend/migrations/sql/ instead of a single timestamped filename that
  may be renamed or squashed.
2026-06-03 23:04:50 -04:00
mason5052 bd7c14f854 docs: add native Google Vertex AI provider RFC
Issue #321 requests a native Vertex AI provider with service-account /
ADC auth, opened after #310 clarified Vertex is not supported today. The
issue carries a full implementation outline and four open questions, and
the author asks for direction on adapter strategy and Gemini-vs-Claude
scope before implementing.

Add examples/proposals/vertex_ai_provider.md, a planning RFC that frames
the work before any code is written:

- Distinguishes the current options (AI Studio gemini, direct Anthropic,
  AWS Bedrock, and the custom OpenAI-compatible LiteLLM proxy workaround)
  from the proposed native vertex provider.
- Recommends a staged approach: v1 Gemini-on-Vertex with ADC /
  service-account auth; Claude-on-Vertex deferred to a maintainer
  decision, noting it likely belongs on the Anthropic adapter (Vertex
  auth/endpoint mode) rather than the Gemini-shaped path because the
  message schema differs.
- Models auth on the existing Bedrock multi-auth precedent (ADC default
  chain plus service-account file), and flags that service-account JSON
  is sensitive and must be file-mounted/secret-managed, never pasted into
  UI or logs.
- Captures config/migration touch points (provider checklist, REST
  Valid() whitelist, PROVIDER_TYPE enum-swap migration) so the eventual
  implementation size is clear, and restates the issue's open questions.

Docs/RFC only. No code, schema, migration, generated, frontend, or
provider runtime files are touched, and no new env vars or types are
added; every VERTEX_* key and type named is labeled as a candidate. No
overlap with the provider files in open PR #328.
2026-06-03 23:01:05 -04:00
mason5052 12f3d19021 docs: add tool-call parser troubleshooting for custom LLM backends
Issue #313 reported flows that stall after a few steps when running a
custom OpenAI-compatible backend (LiteLLM in front of llama.cpp serving
qwen3.6-35b via LLM_SERVER_*). The backend returned malformed tool-call
arguments, surfaced as 'Failed to parse tool call arguments as JSON'
HTTP 500s and cascading retries. The maintainer fixed the stall in the
latest build by sanitizing wrong function-call arguments.

Add a troubleshooting subsection under Custom LLM Provider Configuration
that explains the root cause and how to diagnose it:

- Custom OpenAI-compatible backends must return valid tool-call
  (function-call) JSON; llama.cpp, SGLang, and vLLM usually require a
  specific tool-call parser and matching chat template, and not every
  setup produces valid tool calls out of the box.
- Symptoms: 'Failed to parse tool call arguments as JSON', flow stalls,
  looping tool calls, the 'failed to select primary docker image via
  llm call' start-of-flow failure, and unexpected backend HTTP errors.
- Investigation: check PentAGI and backend/proxy logs, validate with the
  ctester utility before a full flow, confirm the parser/chat template
  match the model, and update PentAGI (recent builds sanitize malformed
  function-call arguments).

Docs only. No tool-call parser code, provider runtime, schema, migration,
or config-default changes. Wording frames compatibility as dependent on
the backend's OpenAI-compatible tool-call behavior rather than claiming
every llama.cpp backend is supported.
2026-06-03 22:54:33 -04:00
mason5052 5b957bde25 docs: add installing and configuring guide for first deployment
Issue #61 asked for a proper guide on how to start using PentAGI. A
first-use guide (How to Use PentAGI After Login) already covers what to
do after login, but the maintainer kept the issue open until an article
about installing and configuring the product is published.

Add examples/guides/installation_configuration.md, a concise ordered
walkthrough that connects the existing detailed README sections into a
single path: choose installer vs manual Docker Compose, set core server
variables (PUBLIC_URL, CORS_ORIGINS, security vars), configure and test
an LLM provider with ctester, configure and test the embedding provider
with etester, optionally add search providers and the Graphiti/Langfuse/
observability stacks, then start and verify the stack and change the
default admin password. It ends with a quick checklist and links forward
to the existing post-login usage guide.

The guide links to the relevant README reference sections rather than
duplicating them. A single pointer link is added at the top of the
README Quick Start section for discoverability.

Docs only. No installer behavior, runtime code, env vars, or schema
changes. Every environment variable named in the guide already exists in
.env.example and backend/pkg/config/config.go.
2026-06-03 22:49:52 -04:00
octo-patch 9ca254efa3 feat: upgrade MiniMax default model to M3
- Add MiniMax provider with M3 as the default model (512K context, 128K max output, image input support)
- Keep MiniMax-M2.7 and MiniMax-M2.7-highspeed as alternatives
- Configure agent defaults (simple, primary_agent, assistant, generator, etc.) on M3
- Register MiniMax provider type, env vars (MINIMAX_API_KEY, MINIMAX_SERVER_URL, MINIMAX_PROVIDER)
- Add unit tests covering config loading, models list, prefix behavior, and missing API key
2026-06-03 12:54:50 +08:00
mason5052 250824ae20 docs: fix grammar in Kubernetes RFC open question (#324)
Address review feedback on PR #326: rephrase the executor-model open
question so the final clause reads clearly.

Refs #324
2026-06-01 17:26:06 -04:00
mason5052 7e51806b85 docs: refine LLM-backend troubleshooting wording (#309)
Address review feedback on PR #325: capitalize SGLang to match the
project's name and clarify that tool calling and function calling
refer to the same capability.

Refs #309
2026-06-01 17:25:58 -04:00
mason5052 2b625b31f1 docs: add embedding troubleshooting for stalled flows (#322)
Add a troubleshooting subsection to the Embedding Configuration and
Testing section for the common case where a flow starts but then waits
indefinitely with no subtasks progressing. As noted on the issue, this
is frequently caused by a misconfigured or unreachable embedding
provider rather than by the flow itself.

The subsection points users to "docker logs pentagi" as the first
check, to the etester "test" command to validate the embedding provider
and database connection without starting a flow, and to the specific
.env settings to verify (EMBEDDING_PROVIDER, EMBEDDING_MODEL,
EMBEDDING_URL, EMBEDDING_KEY, the LLM-provider fallback, PROXY_URL, and
HTTP_CLIENT_TIMEOUT). Documentation only: no new environment variables,
no provider default changes, and no code or test changes.

Refs #322
2026-06-01 17:21:40 -04:00
mason5052 6141975338 docs: add Kubernetes deployment compatibility RFC (#324)
Add examples/proposals/kubernetes_deployment.md, an RFC-style design
surface responding to the Kubernetes deployment request in #324. The
document is docs-only: no Helm charts, manifests, operator, compose,
installer, or environment-variable changes, and it does not claim
Kubernetes is supported today.

It records the current Compose/installer deployment assumptions, maps
each one (secrets/config, volumes, service discovery, ingress/TLS,
health checks, network policies, the Docker-socket flow executor,
observability, image overrides, migrations) to candidate Kubernetes
equivalents, and proposes an incremental, docs-first path with open
questions, security/operational considerations, and a test/validation
strategy. The hardest item -- the Docker-socket worker executor -- is
laid out as candidate options without choosing one, and keeps flow
lifecycle explicit and inspectable per the #268 review lesson.

Refs #324
2026-06-01 17:16:17 -04:00
mason5052 6b7738ce55 docs: clarify "primary docker image" error is an LLM backend failure (#309)
Add a troubleshooting subsection to the Docker Image Configuration
section explaining that "failed to select primary docker image via llm
call" (older versions: "failed to get primary docker image") is raised
when PentAGI's first LLM call fails during image selection, not when
Docker or the registry is unhealthy. Points users to PentAGI and LLM
backend logs, provider URL/key/model verification, and tool-call parser
configuration for custom/OpenAI-compatible/vLLM/sglang backends.
2026-06-01 17:04:28 -04:00
Dmitry Ng 879e87c2c2 fix(installer): skip destructive compose ops when compose file is missing
Remove/Purge/FactoryReset failed with "file does not exist" for stacks
that were never extracted (no docker-compose-*.yml). Now such stacks are
skipped instead of aborting the whole operation.

- Add composeFileExists check before destructive compose commands
- Add isDestructiveComposeOperation helper
2026-05-31 15:41:54 +03:00
Dmitry Ng dc83cb6e50 Merge pull request #323 from mrigankad/fix/installer-swallowed-gather-error
fix(installer): propagate swallowed GatherUpdatesInfo errors
2026-05-31 12:49:55 +04:00
Dmitry Ng 4a9d706cfd Merge pull request #320 from mrigankad/fix/issue-312-misleading-image-error
fix(providers): clarify misleading docker image LLM error (#312)
2026-05-31 12:47:35 +04:00
Mriganka 6bea1581f6 fix(installer): propagate swallowed GatherUpdatesInfo errors
Problem:
In the installer processor, post-operation state refresh failures from
checker.GatherUpdatesInfo were silently discarded, so apply/install/
update/remove/purge could report success even when the refresh failed.

Root cause:
Two distinct shadowing/fall-through patterns wrapped the error into a
variable that was never returned:
- In the deferred closures of applyChanges/install/update/purge, the
  inner `if err := GatherUpdatesInfo(ctx); err != nil` shadowed the
  named return `err`, so `err = fmt.Errorf(...)` assigned the shadow and
  the wrap never reached the `sendCompletion(stack, err)` defer.
- In the ProductStackWorker cases of remove/purge, the block-local err
  was wrapped but the case fell through without returning, while every
  sibling check in the same switch returns on error.

Solution:
- Deferred closures: wrap into a `gatherErr` local and assign the named
  return `err`, so the failure propagates to sendCompletion.
- Switch cases: `return` the wrapped error, matching the sibling checks.

Testing:
go build ./cmd/installer/...        -> OK
go vet ./cmd/installer/processor/...  -> OK
go test ./cmd/installer/processor/... -> ok
golangci-lint (ineffassign) on logic.go -> clean
2026-05-31 11:53:15 +05:30
Mriganka 94ec0a0689 fix(providers): clarify misleading docker image LLM error (#312)
Fixes #312

Root cause:
During flow creation the first LLM call selects the primary Docker
image. When the configured LLM backend is unsupported or returns 404,
prv.Call fails, but the wrapped error read "failed to get primary
docker image". Users repeatedly interpreted this as a Docker problem
(see #312, #309, #203) and debugged Docker instead of their LLM
provider configuration.

Solution:
Reword the wrapped error to "failed to select primary docker image
via llm call" so the LLM provider is identified as the failing
component while still mentioning the image selection step.

Testing:
go build ./pkg/providers/ -> OK
2026-05-31 10:09:57 +05:30
Dmitry Ng a112db206b Merge pull request #319 from vxcontrol/feature/next-release
Release 2.1.0: User Resources & Flow Files, Knowledge Base, ToolCall Logging, Assistant Flow Control, and Frontend Modernization
2026-05-29 17:16:53 +04:00
Dmitry Ng 8feb7bf311 feat(tests): enhance knowledge and flowfile tests with containment barriers
Added new test cases to validate containment barriers in the `ResolvePulledStagedTarget` and `ZipRelativePaths` functions, ensuring that paths escaping the designated directories are properly rejected. Updated the `knowledge_test.go` to include scenarios for handling nil embedder and error propagation during document creation, improving overall test coverage and robustness.
2026-05-29 15:42:11 +03:00
Dmitry Ng ce06a0d26a fix(flow): task execution handling with cancellable contexts on subtasks generation stage
Enhanced the flowWorker's task processing by introducing a cancellable context for task execution. This change ensures that tasks can be properly cancelled without reporting false success states. The `runTask` method has been refactored to utilize a new `execTask` method, which centralizes task execution logic and maintains context integrity. This update improves flow control and error handling during task creation and execution.
2026-05-29 00:08:01 +03:00
Dmitry Ng 83c263e98e feat(qwen): enhance agent configurations with thinking control parameters
Updated the Qwen agent configuration to include `extra_body` parameters for thinking control across various models. Added `enable_thinking` and `preserve_thinking` options for reasoning agents, while utility agents have `enable_thinking` set to false. Adjusted the Qwen client initialization to support these new configurations. Updated test report to reflect changes in success rates and latencies.
2026-05-29 00:06:47 +03:00
Dmitry Ng 643ff7d218 feat(providers): Update model configurations for various LLM providers: qwen, kimi, glm, deepseek, gemini 2026-05-28 15:41:17 +03:00
Dmitry Ng 9d68f570a8 Merge pull request #318 from mason5052/codex/issue-310-vertex-ai-config-docs
docs(llm): clarify Vertex AI configuration options
2026-05-28 00:15:15 +04:00
Dmitry Ng 2f827a54ef Merge pull request #307 from mason5052/codex/issue-296-mcp-client-rfc
docs(rfc): propose MCP client integration design
2026-05-28 00:11:02 +04:00
Dmitry Ng e674113745 Merge pull request #317 from mason5052/codex/issue-314-deepseek-v4-models
fix(deepseek): update default model names to DeepSeek V4
2026-05-28 00:09:25 +04:00
Sergey KozyrenkoandClaude Opus 4.7 a8c3fbcf74 feat(frontend): virtualize DataTable rows past 50
Adds an opt-in `isVirtualized` prop on DataTable, wired through
@tanstack/react-virtual's useWindowVirtualizer. Threshold gates short
tables (preserves Find-in-page, screen-reader enumeration). Padding <tr>
sentinels keep native HTML table semantics. Skipped when
`renderSubComponent` is set — expanded rows would need per-row
remeasurement we don't wire here.

Enabled on /flows. Measured with pageSize=All (1116 rows):
  DOM elements:      41,657 → 1,121  (37x less)
  tbody <tr>:         1,116 → 22
  a11y tree size:     ~485 KB → ~80 KB

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-24 10:36:10 +07:00
Sergey KozyrenkoandClaude Opus 4.7 19d53887b7 refactor(frontend): use Unicode script escapes for CJK detection
The old char-range regex missed hiragana, katakana, hangul, halfwidth
katakana and CJK Ext B+ ideographs, so Japanese/Korean reports would
not trigger NotoSansSC registration. Unicode property escapes cover
all CJK scripts and stay correct as Unicode adds new extensions.

Verified with 18 script samples (zh-Hans/Hant, ja kana, ko hangul/jamo,
fullwidth, CJK Ext B) — all pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-24 10:03:12 +07:00
Sergey KozyrenkoandClaude Opus 4.7 02ef55cb30 perf(frontend): lazy-register CJK font in PDF generator
Skips loading NotoSansSC.otf (8.1 MB) for reports without CJK chars.
Measured win on flow #50 download: 22.6 MB → 13.8 MB total traffic.
Adds `u` flag to CJK regexes so emoji surrogate pairs don't trigger
false positives (was matching U+D83D high surrogate on flow #41).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-24 09:55:44 +07:00
Sergey KozyrenkoandClaude Opus 4.7 adddb45158 build(frontend): vendor-chunk charts/pdf/tiptap/monaco
Stabilizes browser cache: changes in dashboard/knowledges/report code
no longer invalidate the heavy vendor libs. Side effect: the catch-all
(react|react-dom|react-router-dom) regex stopped swallowing
@monaco-editor/react and @tiptap/react, so react-vendor drops 469→178 KB.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-24 08:19:28 +07:00
Dmitry Ng ea7b415359 Merge remote-tracking branch 'origin/feature/frontend-next' into feature/next-release 2026-05-23 15:18:05 +03:00
Dmitry Ng 084670dd97 Merge pull request #306 from mason5052/codex/issue-298-flow-concurrency-rfc
docs(rfc): propose persistent flow queue and completion webhooks
2026-05-23 16:06:23 +04:00
Sergey KozyrenkoandClaude Opus 4.7 1ee2a6f7c9 chore(frontend): replace 19 explicit any with precise types
Lint warnings 44 → 25. The remaining 14 `any` warnings sit in
settings-provider.tsx (provider config form + test results dialog,
needs domain knowledge — deferred per scope). The other 11 warnings
are React Compiler "Compilation Skipped" notices, not code issues.

- lib/log.ts: any → unknown (5) — logger accepts arbitrary input
- shared/markdown.tsx: typed the recursive ReactNode walker with a
  `hasChildrenProp` type guard around `isValidElement`; the components
  map now uses react-markdown's `Components` type so `code` / `pre`
  overrides infer their props (5)
- settings-prompt.tsx: `ControllerProps.control: Control<FieldValues>`,
  `field: ControllerRenderProps<…>`, validation result typed against
  `ValidatePromptMutation['validatePrompt']`, dropped a stray
  `as any` on `removeEventListener` options (4)
- settings-prompts.tsx: row sub-component params typed via
  `Row<T>` from @tanstack/react-table (2)
- settings-providers.tsx: provider icon map typed against
  `SVGProps<SVGSVGElement>`, row sub-component via `Row<Provider>`,
  recursive `getFields(obj)` narrowed from `any` to `unknown` with a
  single boundary cast for `Object.entries` (3)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 13:54:41 +07:00
Sergey KozyrenkoandClaude Opus 4.7 c3bd1d30f2 test(frontend): de-flake DetailNavigationSheet typing test via fireEvent.change
Baseline 8/10 fail (80% flake) → 20/20 pass. Root cause was `user.type`
racing the Radix Sheet focus trap, not the `useDebounce` macrotask
theory from the prior investigation: with `defaultOpen=true` Radix sets
`body { pointer-events: none }`, swallowing user-event's internal click,
so keystrokes route to whatever element currently holds focus (the
SheetContent close button) instead of the input. `inputValue` stays
empty and the listbox never narrows.

`fireEvent.change` mirrors the sidestep already used in the
URL-filter AND test in the same file.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 13:36:26 +07:00
Sergey KozyrenkoandClaude Opus 4.7 4396aa774f style(frontend): trim war-story comments in InputSearch
Followed up on the "no war-story comments" rule (memory file added a
few commits ago, then promptly broken in the X-button addition).
Pass through every comment with the test "remove it — does a senior
reading the code for the first time understand less?".

Removed:
- "Same two-cell shape as DataTableFilter, see its docstring" — cross-
  file rationale belongs in commit history.
- "Hint shown over the collapsed trigger. Kbd self-themes…" — Kbd
  configuration detail, not part of this component's contract.
- "Mirror size='sm' button geometry used by HeaderButton" — micro
  implementation detail.
- "Collapsed trigger sits flush… has-[>button]:ml-[-0.45rem] handles
  the analogous adjustment" — CSS quirk story.
- "The trigger is a real <button> — never a <div> with onClick" —
  generic HTML/a11y factoid, not specific to this file.
- "The component is controlled — parent owns searchQuery" — visible
  from the props shape.
- "Belt-and-braces for programmatic clears" — defensive-style war
  language, replaced with one line stating the effect's purpose.
- "Initialise expanded if the parent already has a non-empty query" —
  duplicates `useState(() => searchQuery.trim().length > 0)`.

Kept (in single-line / sub-3-line form):
- `COMMIT_DEBOUNCE_MS` shares timing with DataTableFilter.
- `External → local sync` effect intent.
- `rAF` before focus so motion's transform has started.
- `handleInputBlur` reads `localValue`, not the prop (subtle invariant).
- Auto-collapse effect purpose.
- `inputRef.current?.focus()` in `handleClear` (otherwise auto-collapse
  fires and the field disappears under the user).
- Top-level JSDoc shrunk from 28 lines to 5 — what it does plus the
  two equivalent clear paths.

Behaviour unchanged. 15/15 tests still pass, lint clean. File: 340 → 260
lines (-24%).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 13:10:01 +07:00
Sergey KozyrenkoandClaude Opus 4.7 237179524b feat(frontend): add trailing X clear button to InputSearch (parity with DataTableFilter)
`DataTableFilter` already ships a conditional trailing `<X>` clear
button; `InputSearch` (the collapsible variant used for /knowledges
semantic search and the same shape sitting in flow detail searches)
only offered keyboard Esc to clear. Unify so every search field across
the app has the same shape.

Implementation:
- Extract a shared `handleClear` used by both the new X button and the
  first-Esc branch. The path cancels any pending debounce, emits `''`
  upstream, and explicitly returns focus to the input — this matches
  the Esc-clear path (where focus is already on the input) and
  side-steps the programmatic-clear collapse effect, so the field
  stays open and ready for fresh typing.
- Render the X only while `isExpanded && localValue` so it can never
  appear on a collapsed/empty field. `aria-label` is contextual:
  "Clear search knowledge documents" / "Clear semantic search" / etc.,
  derived from the host page's `ariaLabel`.
- Update the JSDoc to describe both clear entry points.

Tests (input-search.test.tsx, 15 total — 10 baseline + 5 new):
- absent on empty mount
- present on deep-linked non-empty mount
- shows/hides as the user types and clears
- click clears value, emits `''` upstream, keeps focus on input,
  prevents the trigger from re-appearing
- click mid-typing drops any pending debounce — no leaked emit

Browser verified on /knowledges semantic search:
beforeClear { value: 'jwt', url: '?qs=jwt', xPresent: true }
afterClear  { value: '',    url: '',       xPresent: false, focusOnInput: true }

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 13:05:20 +07:00
Sergey KozyrenkoandClaude Opus 4.7 b691e05879 fix(frontend): collapse duplicate GraphQL types from v6 codegen migration
After the `chore(frontend): upgrade graphql-codegen toolchain` upgrade
(8a3d4e9) the generated `src/graphql/types.ts` carried every base type
twice — once as `export enum Foo` (from `typescript`) and once as
`export type Foo = 'a' | 'b'` (from `typescript-operations`). Vite's
dependency scan failed on the duplicate declarations with 29
`Identifier 'X' has already been declared` parse errors, which made
the dev server occasionally die on cold start.

Root cause: this was a stale v5-style config running on v6 plugins.
The v6 migration guide is explicit — `preResolveTypes` has been
removed, and `typescript-operations@6` now emits base types itself,
so the canonical setup is `plugins: ['typescript-operations']` rather
than `['typescript', 'typescript-operations']`. Keeping both meant the
two plugins independently emitted the full type set in different
shapes.

Bisect confirmed the split: `typescript` alone → 1327 lines, no
duplicates; `typescript-operations` alone → 1311 lines, no
duplicates; the pair → 2639 lines with 29 duplicate type names.
With `typescript-react-apollo` also in the mix the regenerated file
ballooned to 8819 lines, half of which was the shadow set.

Fix:
- Drop the `typescript` plugin from the codegen config.
- Drop `preResolveTypes: true` (removed in v6).
- Add `enumType: 'native'` so the call sites that use enum-style
  access (`KnowledgeDocType.Answer`, `AgentConfigType.Adviser`, …)
  keep compiling — without it, v6 defaults to string-literal unions.

Result:
- `src/graphql/types.ts` shrinks 8819 → 7586 lines, zero duplicate
  declarations.
- `KnowledgeDocType`, `AgentConfigType`, etc. remain real TS `enum`s
  so `KnowledgeDocType.Answer`-style access keeps working.
- `pnpm run build` clean, lint clean, 531/531 tests passing.
- Vite dev start no longer prints `[PARSE_ERROR] Identifier X has
  already been declared`. `/knowledges` (the page that exercises
  enum access) loads with 10 rows and zero console errors.

Migration guide:
https://the-guild.dev/graphql/codegen/docs/migration/operations-and-client-preset-from-5-0

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 12:21:36 +07:00
Sergey KozyrenkoandClaude Opus 4.7 a3d19f077a revert(frontend): drop unfounded resolve.dedupe + war-story comment
Reviewing 17451e7: the dedupe was added in reaction to a runtime
`Cannot read properties of null (reading 'useRef')` that I attributed
to dual React copies via pnpm hoist. But I applied two changes at
once — clearing `node_modules/.vite` and adding dedupe — and never
isolated which one actually fixed it.

Empirical re-check just now: production build, dev server, and
the affected page all work with dedupe removed. The real cause was
the stale Vite pre-bundle (`.vite/deps/`), which doesn't auto-rebuild
after `pnpm add` in a running dev server. Cache clear alone fixes it.

That makes the dedupe defensive hygiene at best, and the 7-line
war-story comment alongside it actively misleads — it pins a problem
on a mechanism that wasn't the cause. Removing both keeps the config
honest. QA report updated to record the misdiagnosis as a process
note instead of an architectural rule.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 12:03:49 +07:00
Sergey KozyrenkoandClaude Opus 4.7 2bb2fd5d98 style(frontend): apply prettier formatting on filter test files
Run `pnpm prettier:fix` brought three files into compliance:
- data-table.test.tsx — new race-scenario suite added in the previous
  commit; prettier preferred a slightly different multi-line shape for a
  couple of `render(<FilterHost />)` calls.
- input-search.test.tsx — new file in the previous commit; same minor
  multi-line reshaping for `render(<SearchHost />)`.
- settings-api-tokens.tsx — pre-existing single-line nested ternary that
  predates this branch, now collapsed to one line per prettier.

No behavior change. Format-only.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 08:47:34 +07:00
Sergey KozyrenkoandClaude Opus 4.7 17451e75dd refactor(frontend): migrate filter/search debounce to use-debounce npm
After landing the imperative-timer fix and extracting `useDebouncedCallback`
into our own hook, the use-site count climbed past three and the case for
a single, battle-tested contract beat the case for in-tree code. Drops
both our `useDebouncedValue` and `useDebouncedCallback` and routes every
caller through `use-debounce@10.1.1` (1M+ weekly, ~3KB gzip).

API mapping at each use-site:
- value debounce: `useDebouncedValue(v, ms)` → `const [v] = useDebounce(v, ms)`
- callback debounce: `useDebouncedCallback(fn, ms)` → identical signature,
  same `.cancel()`/`.isPending()` semantics we relied on, plus `.flush()`
  and leading/trailing/maxWait options we now get for free.

Files touched (7 use-sites): data-table.tsx, input-search.tsx,
use-table-state.ts, use-table-query-filter.ts, knowledges-provider.tsx,
use-flow-files-search.ts, use-detail-navigation.ts.

pnpm + Vite gotcha: pnpm hoists into `.pnpm/<name>@<ver>/`, so any
transitive `import React from 'react'` from a third-party package can
resolve to its own physical copy. With one path through our code and
another through use-debounce, the runtime crashed at `useRef` with
"Cannot read properties of null (reading 'useRef')". Added
`resolve.dedupe: ['react', 'react-dom']` in vite.config.ts so the
bundle ships exactly one React.

Tests:
- new input-search.test.tsx (10 tests) covers collapsed/expanded
  presentation, expand-on-click + rAF focus, burst-typing coalesce,
  Esc-clear mid-debounce, two-stage Esc semantics, external-source-wins
  race, Ctrl+F / Cmd+F global hotkey expansion.
- data-table.test.tsx +5 tests: deep-link initial filterValue,
  6-keystroke burst coalesce, unmount-mid-debounce cleanup, two
  independent DataTables on one page (settings/prompts shape),
  back-button-style external clear, three-round type/clear stress.
- full suite: 541/541 passing, lint 0 errors.

Manual smoke via Chrome DevTools MCP on every page that mounts a
filter input — /flows, /templates, /settings/api-tokens,
/settings/prompts (both tables independent), /knowledges (filter
+ semantic search hitting the server through ?qs=). All scenarios
collapse to a single `[{v="", u=""}]` transition; no URL re-emit
after X, no leftover timer after Esc, no cross-table leakage.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 08:28:27 +07:00
Sergey KozyrenkoandClaude Opus 4.7 e451d23aab refactor(frontend): extract debounced filter emit into useDebouncedCallback
The previous iteration moved DataTableFilter / InputSearch off
`useDebouncedValue` and onto an inline `setTimeout` + `pendingTimerRef`
+ `cancelPendingEmit` dance. That fixed all four race scenarios but
left imperative scheduling living inside components — a code smell
flagged in review. After surveying the React 19.2 surface area
(`useDeferredValue` is for *render* priority, not side-effect throttling;
`useTransition` doesn't apply to controlled inputs; `useEffectEvent` is
restricted to handlers called from within Effects) and `use-debounce`'s
API, the right shape is a small, dependency-free hook.

`useDebouncedCallback(fn, delayMs)` returns a stable callable with
`.cancel()` / `.isPending()`. Timer state lives in a closure variable
inside a `useState` lazy initialiser, so:
- the returned identity never changes (safe in effect deps and memoised
  children);
- there are no refs to read during render (no React Compiler complaints);
- `fn` and `delayMs` go through `useLatestRef` so the dispatched call
  always sees the freshest closure — inline arrows in parents are free.

DataTableFilter / InputSearch shrink to one useState + one useRef
(`lastEmittedReference` distinguishes our own router round-trip from a
true external change) + one useEffect (external sync). All four
regression tests added in the previous commit still pass; five new unit
tests pin `useDebouncedCallback` semantics (burst coalescing, cancel,
isPending, latest-closure read, unmount cleanup). Browser repro on
/flows for both X-after-flush and X-before-flush scenarios: a single
transition `v="" u=""`, no resurrection.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 00:48:10 +07:00
Sergey KozyrenkoandClaude Opus 4.7 ba354f3701 refactor(frontend): one outbound timer for filter input emit
Previously DataTableFilter (and InputSearch) layered four cells holding
the same logical value — `localValue` (sync useState), `debouncedValue`
(async useState inside `useDebouncedValue`), `lastEmittedReference`
(ref), and the parent's `query` prop (async round-trip) — and stitched
them together with two opposing useEffect's. The async `debouncedValue`
cell could be read out of phase from any other effect, which leaked
through as four distinct races: X clear after debounce flush (URL/state
snap back ~50–80 ms), X clear *before* debounce flush (pending timer
fires after clear), external `query` change mid-debounce (pending
typed value clobbers external), and tail-end character loss on fast
typing across the round-trip boundary.

Drop the extra storage cell. The debounce is now an imperative
`pendingTimerReference` mutated only by `handleChange`,
`cancelPendingEmit`, and the external-sync effect. All outbound
emission goes through one `emit(next)` function that synchronously
cancels any pending timer before sending. `handleClear` → `emit('')`.
External `query` change → cancel pending + accept. Unmount → cancel.
`onQueryChange` lives behind `useLatestRef` so effect deps stay
stable across parent re-renders.

Four regression tests in data-table.test.tsx pin all four scenarios.
Verified by rolling back the fix temporarily — the X-clear race test
fails with the exact `emitted = ['', 'alpha', '']` from the original
browser repro. With the fix in place all four pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 00:24:09 +07:00
Sergey KozyrenkoandClaude Opus 4.7 4a83b29c3d fix(frontend): kill X-clear race that resurrected the filter query
DataTableFilter / InputSearch listed `onQueryChange` (an inline arrow from
the parent — fresh reference per render) in the emit effect's deps. After
the X-clear handler set `lastEmitted=''` and propagated upstream, the
parent re-rendered and handed back a new handler reference, re-running
the effect while `debouncedValue` was still the pre-clear value
(`useState` inside `useDebouncedValue` hadn't yet been updated by its
trailing `setTimeout`). The effect saw `debouncedValue='alpha' !==
lastEmitted=''` and re-emitted `'alpha'`, snapping URL/state back for
~50–80 ms. JSDOM regression captured `emitted = ['', 'alpha', '']`.

Stash the handler in `useLatestRef` and drop it from deps so the effect
fires only when the observed value actually changes. Same fix in
InputSearch's Esc-clear path. New test in data-table.test.tsx pins the
behavior — fails with the previous code (`['', 'alpha', '']`), passes
now (`['', '']`).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 00:09:07 +07:00
mason5052 5ff63cc4a8 docs(llm): clarify Vertex AI configuration options
Issue #310 asks how to provide a Google Vertex AI API key in .env for
Anthropic Claude. PentAGI currently has no dedicated Vertex AI provider
path in code: backend/pkg/config and backend/cmd/installer do not read
VERTEX_API_KEY, GOOGLE_APPLICATION_CREDENTIALS, or any vertex_ai
variable. The supported routes for Claude today are direct Anthropic
(ANTHROPIC_API_KEY / ANTHROPIC_SERVER_URL) and AWS Bedrock (BEDROCK_*).

Document this explicitly so users do not assume a hidden Vertex AI
configuration path exists:

- README.md: add a NOTE callout inside the Anthropic Provider
  Configuration section listing the supported routes and pointing
  users who need Vertex AI today at the OpenAI-compatible custom LLM
  provider path (LLM_SERVER_URL / LLM_SERVER_KEY / LLM_SERVER_MODEL)
  fronted by a translating gateway, with a caveat that reliability
  depends on the gateway.
- backend/docs/config.md: add a matching Note paragraph under the
  Anthropic section that points at the AWS Bedrock and custom LLM
  provider sections, and states that no VERTEX_API_KEY or
  GOOGLE_APPLICATION_CREDENTIALS variable is wired into provider
  initialization today.

Docs-only change. No runtime Go code, no installer behavior, no
generated files, no new environment variables. All env var names cited
in the new text already exist in the current PentAGI .env.example,
backend/pkg/config, and backend/cmd/installer.
2026-05-22 12:50:19 -04:00
mason5052 24176c2805 fix(deepseek): explicitly disable thinking mode for non-thinking Flash roles
DeepSeek V4 thinking mode defaults to enabled on both deepseek-v4-flash
and deepseek-v4-pro; non-thinking behavior requires an explicit toggle.
Per official docs, in thinking mode temperature/top_p/presence_penalty/
frequency_penalty are ignored, so the existing Flash role sampling knobs
would have been silently no-ops without the toggle.

Add extra_body.thinking.type=disabled to the five non-thinking Flash
roles so deepseek-v4-flash actually runs in non-thinking mode and
honors the role's temperature/top_p settings:

- simple, simple_json, adviser, searcher, enricher

Pro roles (primary_agent, assistant, generator, refiner, reflector,
coder, installer, pentester) intentionally keep thinking enabled (the
V4 default) for reasoning, tool-use, and security analysis.

PentAGI provider config already supports extra_body as a first-class
yaml field on AgentConfig and forwards it through openai.WithExtraBody,
which the vxcontrol langchaingo fork serializes at the top level of the
Chat Completions request - the same pattern Kimi uses for tool_choice.
No code, schema, or LiteLLM prefix changes required.

Touches:
- backend/pkg/providers/deepseek/config.yml (embedded production config)
- examples/configs/deepseek.provider.yml (user-facing example)

No change to role-to-model mapping, model metadata, pricing, README
wording, LiteLLM prefix, unrelated providers, lifecycle, queues, or
installer flow.
2026-05-22 12:26:28 -04:00
mason5052 67bf76514b docs(deepseek): align V4 model metadata with official pricing and context
- Update model descriptions to reflect V4 1M context window (up to 384K output)
  instead of legacy 128K wording in models.yml and README.
- Split Flash and Pro pricing per official DeepSeek API docs:
  - deepseek-v4-flash: input 0.14 / output 0.28 / cache_hit 0.0028 per 1M tokens
  - deepseek-v4-pro:   input 0.435 / output 0.87 / cache_hit 0.003625 per 1M tokens
- Apply per-role price split across all 13 role configs in both the embedded
  config.yml and the user-facing examples/configs/deepseek.provider.yml.
- Replace stale "cache pricing is 10% of input cost" claim in the README,
  which no longer holds for either V4 model.
- No change to LiteLLM prefix behavior, role-to-model mapping, lifecycle,
  queues, GraphQL schema, migrations, frontend, or installer flow.
2026-05-22 12:04:14 -04:00
mason5052 20b0633521 docs(deepseek): address Copilot review feedback
- README: align supported-models intro with the local convention used
  by every other provider section ("Models marked with `*` are used
  in default configuration"), so the asterisk on each model ID has a
  near-by explanation.
- Installer help (`LLMFormDeepSeekHelp`): swap the legacy
  "DeepSeek-Chat" / "DeepSeek-Reasoner" bullets in "Default PentAGI
  Models" for the current `deepseek-v4-flash` / `deepseek-v4-pro`
  defaults so the wizard guidance matches the bundled config.

No code, schema, or LiteLLM prefix behavior changes.
2026-05-22 11:41:09 -04:00
Sergey KozyrenkoandClaude Opus 4.7 606eb7bf1f style(frontend): trim JSDoc fluff on DataTable empty-state additions
The JSDoc blocks added in afb9b63 mostly paraphrased the 12 lines of
code below them. Reviewing line-by-line:

- "two axes" / "filter active vs no filter" / per-state copy — code
  reads identically and is right next to the comment.
- "kept inline because tightly coupled to effectiveQuery" — every
  helper in this file is inline, that's the existing convention.
- "colSpan={columns.length} parent" — the one call site is 10 lines
  below in the same file.
- "for callers that have not migrated yet" — `empty?:` being optional
  already says this.
- "so existing tests stay green" — the test itself documents the
  contract; deleting the fallback fails it loudly.

Kept the one piece TypeScript can't express: a single-line hint that
`entityName` wants the plural lowercase form so the generated copy
reads naturally mid-sentence. That shows up in IDE autocomplete and
saves a "Flows" → "No Flows match" first-try mistake.

No behaviour change. 28/28 DataTable tests pass, 0 ESLint errors.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 20:57:53 +07:00
Sergey KozyrenkoandClaude Opus 4.7 afb9b637ef feat(frontend): contextual DataTable empty state via shadcn <Empty>
Resolves QA report observation O9. Every list page used to render the
bare "No results." label when its DataTable had no rows — both for a
truly empty dataset and when a filter narrowed the result set to zero.
The Resources page already had a better pattern (shadcn <Empty> block
with a filter-aware copy that cited the query), so propagate it to the
shared DataTable.

API
- New optional `empty?: { entityName?: string }` prop on `DataTable`.
- When `entityName` is provided, the body cell renders an `<Empty>`
  block:
    filter active → Search icon + "No matches" + "No <entity> match
    <code>{query}</code>. Try a different query."
    no filter      → Inbox icon + "No <entity> yet"
  and the pagination footer mirrors the entity name ("No <entity>"
  instead of "No results").
- When `entityName` is omitted, the existing bare "No results." cell
  and "No results" footer are kept verbatim — preserves backward-compat
  for call sites that have not migrated and for the existing test that
  asserts the legacy copy.

Per-page wiring
Plural lowercase names match how a screen reader reads them mid-
sentence:
  flows                  → "flows"
  templates              → "templates"
  knowledges             → "knowledge documents"
  /settings/providers    → "providers"
  /settings/api-tokens   → "API tokens"
  /settings/prompts ×2   → "agent prompts" / "tool prompts"

Tests
- Existing `'No results.'` assertion stays valid: it renders a
  DataTable without the `empty` prop, exercising the legacy fallback
  path.
- Added 3 new cases under `DataTable — empty results`:
    1. legacy fallback when `empty.entityName` is omitted
    2. data-empty "No <entity> yet" when no filter is active
    3. filter-empty "No <entity> match <query>. Try a different
       query." with the query cited verbatim

Verified
- 0 ESLint errors, 44 pre-existing warnings.
- 511/511 vitest pass in sequential mode and when the affected files
  run isolated. A pre-existing concurrency flake in
  `detail-navigation-sheet.test.tsx` (`typing narrows the listbox
  immediately when searchDebounceMs=0`) occasionally surfaces under
  vitest's default `--file-parallelism` — unrelated to this change,
  passes deterministically with `--no-file-parallelism` and when the
  file is run in isolation.
- Browser sweep across 7 tables (`/flows`, `/templates`,
  `/knowledges`, `/settings/{providers,api-tokens,prompts(×2)}`) all
  render the new copy with `?q=ZZZZZZ`.

References
- shadcn `Empty` component (already vendored in
  `components/ui/empty.tsx`)
- shadcn.io `tables-empty` block FAQ (best-practice: distinguish
  filter-empty vs data-empty via `hasActiveFilters` boolean, ground
  the empty cell in a Lucide icon, surface a "next-step" hint).
- Existing precedent in `pages/resources/resources.tsx` —
  `No resources match <code>{q}</code>. Try a different query.`

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 18:31:30 +07:00
Sergey KozyrenkoandClaude Opus 4.7 25e19e5be8 revert(frontend): keep provider clone URL as ?id= (revert part of 04702c3)
Reverts the O10 part of commit 04702c3. The original change renamed
the provider clone URL parameter from `?id=` to `?clone=`. On second
look the rename solved no real problem:

- No security issue: PentAGI is a single-tenant local admin tool, so
  there is no cross-tenant info leak from a shared URL.
- No bug: the form behaviour was identical before and after.
- No UX impact: the URL is generated by the "Clone" action, not typed
  by users; the bare `?id=` is also explicit enough in context
  (settings-provider.tsx gates it on `isNew`, so the meaning is
  "source provider to clone from").

What the rename did cost: it broke backward compatibility with any
bookmarks/links saved in `?id=` form. Restore `?id=` to remove the
needless churn.

The rest of commit 04702c3 (O7 dialog case, O8 "API Tokens" unify,
O11 button label + JSDoc, O12 italic placeholder) addressed real
inconsistencies and stays in place.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 18:02:27 +07:00
Sergey KozyrenkoandClaude Opus 4.7 04702c3648 fix(frontend): UX consistency sweep — dialog case, page titles, clone URL
Resolves QA report observations O7, O8, O10, O11, O12.

O7 — Confirm dialog title case
The Resources page rendered "Delete Directory" / "Delete Resource" in
Title Case while every other delete confirm (template, knowledge,
token) used Sentence case ("Delete template", "Delete token"). Aligned
the resources copy to "Delete directory" / "Delete resource".

O8 — /settings/api-tokens identity mismatch
Three names referred to the same page:
  - sidebar link / h1: "PentAGI API"
  - tab title (route registry): "API tokens"
  - menuItems entry: "PentAGI API"
Unified everything to "API Tokens". Also removed the now-redundant
api-tokens special case in settings-layout's SettingsHeader (it always
returned the same value the menuItems lookup would have produced).

O10 — Provider Clone URL parameter
`/settings/providers/new?id=5` collided semantically with the rest of
the codebase, where `?id=` usually means "this is the record being
edited". Renamed to `?clone=5` so the intent is explicit when the URL
is shared or shows up in logs. Updated the reader in
settings-provider.tsx (`formQueryParams.id` → `formQueryParams.clone`)
to match.

O11 — "Create Provider" button accessibility
The button is a DropdownMenuTrigger that opens a provider-type chooser
before navigating to /new — not a submit button. Sighted users get
this from `<ChevronDown />` and Radix's `aria-haspopup="menu"`, but
the bare visible text "Create Provider" reads as a confirmation
action to screen readers. Added `aria-label="Create provider — choose
type"` and a block comment explaining the pattern so future
maintainers don't try to "fix" the dropdown into a direct submit.

O12 — `(unnamed)` placeholder rendering
Tokens with empty name rendered as literal `(unnamed)` with
text-muted-foreground only. Added `font-normal italic` so the
placeholder reads as missing data rather than a real name (the column
otherwise uses font-medium).

Verified: 0 ESLint errors, 508/508 tests pass.
Browser regression sweep across 9 pages (/dashboard, /flows,
/templates, /knowledges, /resources, /flows/:id, /settings/{providers,
api-tokens,prompts}) still returns 0 icon-only buttons without an
accessible name.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 17:52:16 +07:00
Dmitry Ng db88ef5eaa Merge pull request #305 from mason5052/codex/issue-187-graphiti-limitations-docs
docs(graphiti): note beta status and OpenAI-only provider limitation
2026-05-22 01:12:43 +04:00
Dmitry Ng 8ea8173619 Merge pull request #304 from mason5052/codex/issue-193-flow-file-upload-docs
docs(flows): document flow-scoped Files tab, sources, and current limits
2026-05-22 01:11:38 +04:00
Dmitry Ng ff35909f52 Merge pull request #303 from mason5052/codex/issue-280-ollama-tool-support-validation
fix: clarify Ollama models without tool support
2026-05-22 01:08:52 +04:00
Dmitry Ng 27073687df Merge pull request #301 from mason5052/codex/issue-300-custom-prompts
fix: apply custom prompts to new sessions
2026-05-22 01:00:24 +04:00
Dmitry Ng 19b63c5b45 Merge branch 'feature/next-release' into codex/issue-300-custom-prompts
Signed-off-by: Dmitry Ng <19asdek91@gmail.com>
2026-05-22 00:59:33 +04:00
mason5052 3113ff3aa3 fix(deepseek): update default model names to DeepSeek V4
The DeepSeek provider config still defaulted to the legacy
`deepseek-chat` and `deepseek-reasoner` model names, which the
upstream DeepSeek API has announced for deprecation on 2026-07-24.
A first-run install therefore breaks once the legacy names are
removed.

Swap the defaults to the current DeepSeek V4 family:

- non-thinking roles use `deepseek-v4-flash`
- reasoning-heavy roles use `deepseek-v4-pro`

The change is limited to the embedded `config.yml` / `models.yml`
inside `backend/pkg/providers/deepseek`, the matching example at
`examples/configs/deepseek.provider.yml`, the `DeepSeekAgentModel`
fallback constant in `deepseek.go`, and three doc references
(README.md, backend/docs/config.md, backend/docs/llms_how_to.md)
plus one installer help string in
`backend/cmd/installer/wizard/locale/locale.go`. LiteLLM prefix
behavior is untouched.
2026-05-21 15:44:30 -04:00
Sergey KozyrenkoandClaude Opus 4.7 3346387cee fix(frontend): valid prompt-id guard + form-field a11y attrs
Resolves QA report BUG #16 and BUG #17.

BUG #16 — /settings/prompts/<invalid> tab title fallback
formatPromptId() blindly capitalized whatever the URL passed in, so a
nonexistent id like /settings/prompts/99999 produced the tab title
"99999 — PentAGI" (and an "Edit Prompt" header with a literal "99999"
in the error message). Valid prompt ids are camelCase identifiers
(e.g. "agentSelector"). Reject anything that does not match
/^[a-z][a-zA-Z]*$/ and fall back to a generic "Prompt", so the title
becomes "Prompt — PentAGI" for invalid ids; valid ids keep their
existing "Agent Selector — PentAGI" rendering.

BUG #17 — Chrome DevTools "form field needs id/name" + label-for
Two separate issues on /flows and /flows/🆔

1) Four hidden <input type="file"> elements driven programmatically
   by use-resources-upload / use-flow-files-upload / flow-form lacked
   `name`. Added descriptive names (`resource-upload`, `flow-file-upload`,
   `flow-form-attachment`) plus `aria-hidden="true"` and `tabIndex={-1}`
   — these inputs are never user-focused (the button triggers .click()
   via a ref), so excluding them from the accessibility tree is correct.

2) <FormControl><Switch/></FormControl> + <FormLabel> for the "Use Agents"
   field on the assistant flow form was rendered without a wrapping
   <FormItem>, so useFormField() read the default empty context and
   formItemId became "undefined-form-item". Chrome then flagged "label
   for=undefined-form-item" as an orphan. Wrapped the cluster in
   <FormItem className="flex flex-row items-center gap-0"> so useId()
   generates a real id and the label binds to the Switch trigger
   button correctly.

Verified: 0 ESLint errors, 508/508 tests pass.
On /flows the page now has 0 form fields without id/name.
On /flows/:id the only remaining unlabeled fields are third-party
internals we do not own (xterm.js helper textarea, Radix Switch
primitive checkbox, react-textarea-autosize ghost) — Chrome's count
dropped accordingly.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 20:37:59 +07:00
Sergey KozyrenkoandClaude Opus 4.7 f41f012e67 refactor(frontend): unify row-action a11y pattern to aria-label
Page-level row-action triggers were split between two conventions:
- 4 pages used <span className="sr-only">Open menu</span> inside <Button>
- 3 pages (touched in commit 9eee2b4) followed the same pattern for consistency

Project has no i18n pipeline that benefits from sr-only text-node
translation, and the rest of the codebase already uses aria-label for
icon-only buttons (pagination, forms, theme tabs, toggles). Unify all
6 page-level row-action triggers to aria-label="Open menu":

- pages/flows/flows.tsx
- pages/knowledges/knowledges.tsx
- pages/templates/templates.tsx
- pages/settings/settings-providers.tsx
- pages/settings/settings-prompts.tsx (×2 — agent + tool tables)
- pages/settings/settings-api-tokens.tsx

shadcn UI library components (sheet, dialog, sidebar, breadcrumb) keep
their sr-only spans untouched — that is upstream shadcn convention and
not in scope here.

Verified: 0 ESLint errors, 508/508 tests pass, browser sweep across
6 list pages confirms aria-label="Open menu" rendered correctly and
no icon-only buttons remain without an accessible name.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 18:24:42 +07:00
Sergey KozyrenkoandClaude Opus 4.7 9eee2b48a1 fix(frontend): add aria-labels to icon-only buttons
Resolves QA report BUG #12, #13, #14, #15, #18 — icon-only buttons
across forms, sidebar, DataTable, and detail pages lacked accessible
names. Applied handler-based naming convention so the label matches
the prop / handler / state attribute, not the visual icon:

- type="submit" + isSubmitting → "Submit" / "Submitting…"
- onCancel + isCanceling → "Cancel" / "Cancelling…"
- onToggleFavorite + isFavorite → "Toggle favorite" + aria-pressed
- setTheme(value) + value → "<Value> theme"
- Pagination via table.firstPage()/etc → "First/Previous/Next/Last page"
- Row actions DropdownMenuTrigger → "Open menu" via existing sr-only convention

Verified: 0 ESLint errors, 508/508 tests pass, regression sweep across
9 pages (/dashboard, /flows, /templates, /knowledges, /resources,
/flows/:id, /settings/{providers,api-tokens,prompts}) returned 0
icon-only buttons without accessible name.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 18:15:03 +07:00
Sergey KozyrenkoandClaude Opus 4.7 de14bacb59 style(frontend): widen page indicator slot so "Page 79 of 79" fits
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 00:19:29 +07:00
Sergey KozyrenkoandClaude Opus 4.7 385704dee4 fix(frontend): stop pagination URL loop on back-nav and clamp
The clamping effect compared the URL to a `safePageIndex` derived from the
internal mirror. After popstate the URL refreshes one render before the
mirror catches up; after a page-size change the mirror refreshes one
render before the URL — so each side echoed the stale source back over
the fresh one, oscillating `/flows` ↔ `/flows?page=2` indefinitely.

Now clamping only fires when both URL and mirror agree out-of-range, and
goes through a new `setPage(idx, { replace: true })` opt-in so a typed
`?page=999` no longer leaves a history entry the next back-press would
re-trigger.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 00:16:41 +07:00
Sergey KozyrenkoandClaude Opus 4.7 6704116936 fix(frontend): prevent detail-navigation sheet items from overflowing
Radix ScrollArea wraps children in a display:table viewport that grows
to intrinsic content, so renderItem rows with white-space:nowrap text
pushed each option past the sheet's right edge. Swap to plain
overflow-y-auto and add min-w-0 to the flex chain so truncate finally
takes effect on long flow / template / knowledge titles.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 23:07:37 +07:00
Sergey KozyrenkoandClaude Opus 4.7 e97b29b31f refactor(frontend): purge WHAT-only comments across the codebase
Strip section banners, "Helper function to X" labels above self-describing
identifiers, "GraphQL query/mutation/subscription" markers, and the
copy-pasted `// Create debounced function` / `// Filter by search` blocks
that lined every flow feature. Where a comment hid a non-obvious reason
(history blocker pattern, watch() vs getValues(), CJK font fallbacks),
rewrite it as a WHY comment instead of dropping it.

Net diff: -571/+78 across 57 files. Lint clean (pre-existing `any`
warnings unchanged), `tsc` errors unchanged, 506/506 tests still pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 22:42:45 +07:00
Sergey KozyrenkoandClaude Opus 4.7 1903e8fc0f fix(frontend): tag apollo titles with a Symbol marker so prod detects them
Terser strips the inner function-expression name in `apolloTitle()` during
the production build, leaving an anonymous `function({params})` whose
`fn.name === ''`. The old PascalCase heuristic in `DocumentTitle` then
misclassified the component as a `(params) => string` resolver, called it
with raw `match.params`, and crashed `variables({flowId})` with
"Cannot destructure property 'flowId' of undefined" on every /flows/:id
view in production.

Attach an explicit `Symbol.for('pentagi.apolloTitle')` marker via
`Object.assign` in the factory and expose `isApolloTitle()` as the only
public guard. Symbol-keyed properties survive Terser regardless of
`mangle.properties` settings, and `Symbol.for` keeps the marker stable
across accidental double-bundles (workers, SSR boundaries). The
`document-title` consumer now imports the guard, not the symbol, so the
marker stays an implementation detail of the apollo-title module.

Cover the regression with a dedicated `apollo-title.test.tsx` that
simulates name stripping via `Object.defineProperty(fn, 'name', { value: '' })`
and asserts the guard still recognizes the component.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 21:31:46 +07:00
Sergey KozyrenkoandClaude Opus 4.7 95c4fb5970 fix(frontend): default shadcn Button to type="button"
HTML's default `type` for a `<button>` inside a `<form>` is `submit`,
so every Button without an explicit `type` silently posted the parent
form on click — repro on knowledge detail: clicking the
`DetailNavigationButtons` Prev/Position/Next cluster (or the Anonymize
button) fired the form's submit handler and kicked off an
`updateKnowledge` mutation that 502'd. Mirrors the existing convention
in `InputGroupButton`. `asChild` still defers to the consumer's
element; the one genuine submit caller (`FormSubmitButton`) is
explicit. Audit confirms no other Button uses default-submit
intentionally.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 18:41:42 +07:00
Sergey KozyrenkoandClaude Opus 4.7 5a26d800ee feat(frontend): in-sheet search + focus-steal fix in detail navigation
`useDetailNavigation` now owns a controllable local search (debounced,
ANDed with the URL `?q=` filter) and `DetailNavigationSheet` surfaces it
as a header input by default (`hasSearch={true}`). Sheet auto-focus no
longer steals focus from the search input when `filteredItems` shrinks
on a debounce flush — gate the option-focus effect on `document.activeElement`
so typing past the boundary keeps the caret in place. ArrowDown from the
input synchronously promotes focus into the listbox.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 18:38:49 +07:00
Sergey KozyrenkoandClaude Opus 4.7 4888568a7e refactor(frontend): drop dead storage plumbing from filter readers
Now that `useTableState` no longer touches storage for filter values, the
adjacent read-only API has dead optionality:

- `useTableQueryFilterReader` accepted a `storageKey` that was already
  documented as "ignored here — only for API symmetry with the mutate
  variant." With the symmetry gone (the mutate variant no longer takes
  one), keep the reader pure-URL and drop the prop entirely.
- `useDetailNavigation` used to compute that storage key via
  `usePageStorageKeys` just to pass it into the reader. The whole
  `parentPath` override existed solely to feed that computation. Drop
  `parentPath`, the `ParentPath` template-literal type, and the
  `usePageStorageKeys` import — no caller passes `parentPath`, so the
  cleanup is API-compatible.
- `useResourcesSearch` JSDoc still claimed a "localStorage fallback";
  reword to describe the current URL-only behavior so the comment stops
  contradicting the code.

Manually verified `/knowledges?q=Jinja` → click a row → the detail page
shows `1/11` navigation, Next steps through siblings, and `?q=Jinja`
stays in the URL — the headless controller still reads the live filter
through the reader.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 15:15:03 +07:00
Sergey KozyrenkoandClaude Opus 4.7 f8c2876cdf fix(frontend): stop restoring table filter from storage
The previous `useTableState` mirrored `?q=` into per-page localStorage
and replayed it back into the URL on mount when the URL came in clean.
The intent was "fresh tab resumes the prior search," but in practice
the storage→URL replay leaked the user's most recent filter into
unrelated visits: navigating away from a filtered `/flows?q=` and
returning via the sidebar would silently land on the same filter, often
with an empty result set the user had no reason to expect.

Filter is an ad-hoc query, not a preference. Real preferences (sorting,
column visibility, page size, search columns) still persist via
`lib/table-state` — only `filter` is dropped from the storage roundtrip:

- Remove the storage→URL restore effect.
- Remove the URL→storage write effect for `filter`.
- Drop the `skipRestore` option (no restore left to suppress) and the
  `storageKey` override that only existed to scope the restore.
- Drop the conditional `skipRestore` plumbing on `/knowledges` — the
  page no longer needs to defend against a stale `?q=` being replayed
  on top of a fresh `?qs=` link.
- Rewrite the "storage roundtrip" test block as
  "filter is URL-only": assert the storage entry is ignored on mount,
  the URL still wins when both are set, and typed filter never lands
  in storage.

Manually verified in the browser: `/flows?q=IDOR` → navigate away →
return to `/flows` shows the unfiltered table; sorting a column still
persists across reloads (`table_4_/flows` keeps the `sorting` field).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 14:51:24 +07:00
Sergey KozyrenkoandClaude Opus 4.7 84fcdc2b28 refactor(frontend): use shared formatDate for table cells, drop dup tooltips
The Flows, Providers, and API tokens pages each defined a local
`formatDateTime`/`formatFullDateTime` pair (~16 lines × 3 files) doing
essentially the same trimming-by-recency job as `formatDate` from
`@/lib/utils/format`, and each wrapped the cell in a Tooltip that
repeated the same text more verbosely.

After the previous date-format unification commit (1806956), the
trimmed cell already conveys enough context for every recency band:
- today → HH:mm:ss
- this year → HH:mm, d MMM
- older → HH:mm, d MMM yyyy

So the Tooltip+full-timestamp pair no longer adds information for the
date columns. Replace the three local copies with a direct
`formatDate(new Date(dateString))` call and drop the Tooltip wrapper
where it only mirrors the cell.

The Tooltip on the Terminals column in flows.tsx is kept — it expands
the list of terminals with per-row connection status and is not a
duplicate.

Net delta: -115 / +10 lines.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 14:41:45 +07:00
Sergey KozyrenkoandClaude Opus 4.7 6af1ee4dc1 style(frontend): drop Search adornment, swap Columns toggle for icon button
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 14:20:21 +07:00
Sergey KozyrenkoandClaude Opus 4.7 18069565d9 fix(frontend): address QA findings (P0–P3, excluding password policy)
- providers/flow-provider: map "no rows in result set" to a friendly
  "Flow not found" toast with a stable id so repeated sibling-query
  errors no longer stack raw SQL into the UI
- components/ui/sidebar: skip the global Ctrl+B shortcut when focus is
  in an input, textarea, select, or contenteditable — was hijacking the
  Tiptap Bold shortcut in the markdown editor
- components/ui/sidebar: mark the mobile drawer with group + data-state
  "expanded" so `group-data-[state=...]` selectors collapse correctly
  and flow id badges stop rendering twice in the drawer
- pages/templates/template: add aria-label + title to the icon-only Save
  button and mark the icon aria-hidden
- pages/settings/settings-api-tokens: render the date-picker label with
  date-fns format "d MMM yyyy" to match the table's date format
- pages/settings/settings-providers: drop the fixed Name column width so
  the Type column stays visible on narrow viewports; Badge truncates
  cleanly with whitespace-nowrap and shrink-0 on the provider icon
- components/shared/confirmation-dialog: derive the title from
  `\${confirmText} \${itemType}` so dialogs surface "Delete template"
  instead of a generic "Confirm Action", and use the verb in the
  description for consistency

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 13:41:20 +07:00
Sergey Kozyrenko 1debdd9fdf fix 2026-05-20 01:25:18 +07:00
Sergey KozyrenkoandClaude Opus 4.7 ed066603c2 style(frontend): drop redundant Search icon, stretch Flags column header
- DataTableFilter no longer renders a leading `<Search>` addon. With
  `InputSearch` now living in the same page header as the trigger for
  semantic search, two magnifier icons next to each other read as
  visual clutter — the placeholder text alone already cues the input's
  purpose. Drops the unused `Search` import too.
- The "Flags" column header span gets `w-full` so its
  `justify-end` actually pushes the label flush against the right edge
  of the cell. Without the explicit width it collapsed to content
  size and the alignment had no axis to act on.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 20:45:10 +07:00
Sergey KozyrenkoandClaude Opus 4.7 5f7b683974 fix(frontend): keep InputSearch typing responsive via local-state mirror
Typing fast into the knowledges header search dropped characters: each
keystroke went straight into the parent's `onSearchChange`, which on
this page funnels through `setSearchParams` → router re-render → the
controlled `searchQuery` prop snapped back through React. When the
round-trip outran the user's fingers, the input's visible value rolled
back and chars between commits were lost ("find" → "fn").

Mirrored the `DataTableFilter` pattern: hold a `localValue` state that
keystrokes update synchronously, debounce the commit upstream
(`useDebouncedValue`, 150 ms — same constant as the table filter so
both inputs on this page feel uniform), and reconcile external resets
(Esc, programmatic URL wipe, back button) via a `lastEmittedReference`
guard that ignores our own round-trips.

Blur and Escape now also read `localValue` instead of `searchQuery` so
keystrokes pending in the debounce window aren't treated as "nothing
typed yet". Escape additionally fast-paths an empty commit upstream so
the clear hits the parent without waiting for the debounce.

Measurements (chrome-devtools, 19-keystroke burst): pre-fix typing
dropped characters, post-fix avg keystroke 2.07 ms, p95 6 ms, 0
keystrokes over the 16 ms 60-fps budget. Server `searchKnowledge`
still fires exactly once per typing pause.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 18:43:09 +07:00
Sergey KozyrenkoandClaude Opus 4.7 747c988556 style(frontend): tweak Kbd tooltip palette, drop redundant Plus sizing
- Kbd inside tooltip-content now uses the `accent` token family
  (`bg-accent/20`, `text-accent-foreground`, dark `bg-accent/50`) for
  better legibility against the popover background. The previous
  `bg-background/20` chips read as thin film on dark tooltips.
- The empty-state "New Knowledge" button on the knowledges page passes
  `<Plus />` without an explicit `size-4` — the Button variant already
  sizes its icon slot, the override was duplicating defaults.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 18:27:43 +07:00
Sergey KozyrenkoandClaude Opus 4.7 8ed62a24e8 fix(frontend): emit shadcn v4 data-slot attrs on Tooltip primitives
Children like Kbd target tooltip surfaces via
\`[[data-slot=tooltip-content]_&]:bg-background/20\` selectors so the
chips can re-tone themselves for the dark popover background. Our
TooltipContent was missing that attribute (the file shipped from a
pre-v4 cut of shadcn), so the override never matched and Kbd kept its
muted page-surface styling — invisible on the tooltip.

Set \`data-slot\` on every Tooltip primitive (provider / root /
trigger / content) to match the v4 contract. Verified in DevTools:
Kbd inside tooltip-content now computes the inverted background and
foreground colors.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 18:18:25 +07:00
Sergey KozyrenkoandClaude Opus 4.7 992eb8b198 refactor(frontend): swap InputSearch tooltip text for shadcn Kbd chips
shadcn ships the canonical Kbd-inside-Tooltip pattern (per the
upstream kbd-tooltip demo and our existing components/ui/kbd.tsx).
The Kbd component already self-themes for tooltip-content surfaces
via `[[data-slot=tooltip-content]_&]` overrides, so swapping the
plain "(⌘ K)" suffix for `<KbdGroup><Kbd>⌘</Kbd><Kbd>K</Kbd></KbdGroup>`
matches the rest of the app and renders proper keycap chips against
the tooltip background.

Verified the accessibility-description path: Radix still surfaces the
flattened "Semantic search... ⌘ K" string to screen readers (we saw
it in the a11y snapshot), so the keyboard hint stays announced.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 18:11:13 +07:00
Sergey KozyrenkoandClaude Opus 4.7 e2cd75720e feat(frontend): show placeholder + hotkey tooltip on InputSearch trigger
The collapsed trigger is just a magnifier icon — there's no visible
hint about what it does or which key reveals it. Added a tooltip that
combines the `placeholder` with the platform-appropriate hotkey glyph
(⌘ on Apple, Ctrl elsewhere) using the existing `isMac()` helper. When
`hotkey` is `null` the suffix drops and the tooltip shows just the
placeholder.

Tooltip wraps only the trigger button: once the input is expanded the
caret is in it and a hovering tooltip would obscure the very thing the
user is typing into.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 18:04:32 +07:00
Sergey KozyrenkoandClaude Opus 4.7 dd786d4c9d fix(frontend): restore InputSearch blur-collapse for empty value
The original sofy-front version collapsed the control whenever focus
left an empty input. When the duplicate blur+effect pair was folded
into a single effect during the port, that behaviour silently went
with it — opening the trigger without typing and then clicking
elsewhere left the box expanded forever, because `searchQuery` never
changed and the effect never re-ran.

Re-added a dedicated `onBlur` handler that collapses on focus loss
when the value is empty. The effect stays as the safety net for the
programmatic-clear case (parent wipes `?qs=` from the URL while focus
is elsewhere) — different trigger, different path, neither path can
cover the other.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 18:00:40 +07:00
Sergey KozyrenkoandClaude Opus 4.7 5a7b2e882e style(frontend): align InputSearch sizing with size='sm' button geometry
`HeaderButton` defaults to `size='sm'` (h-8 px-3 rounded-md text-xs)
and pages mount InputSearch right next to it. The component previously
shipped with h-7 / icon-xs (28 px) so the icon-only trigger sat a
notch shorter than its sibling action — visible in the knowledges
header.

Bumped the group to h-8, the trigger to size='icon-sm', and pinned
the inner input to h-8 (it inherits `Input`'s default h-9 otherwise,
which pokes 4 px past the bordered group). Dropped the duplicate
negative margins on the button — the addon's
`has-[>button]:ml-[-0.45rem]` already handles flush-left alignment
when expanded; only the collapsed state needs the explicit `-mx-1.5`
to claw back the addon's default padding around the lone icon.

Verified: trigger 32×32, group 32 px, input 32 px, all matching the
neighbouring `HeaderButton` baseline.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 17:55:54 +07:00
Sergey KozyrenkoandClaude Opus 4.7 31a7f34c0f feat(frontend): add collapsible InputSearch, wire it to ?qs= on knowledges
New `components/ui/input-search.tsx`: a controlled, collapsible search
control that idles as just a `<Search>` icon button and expands into a
text input with a motion-driven width animation. Adapted from the
sofy-front version with:

- Trigger is a real `<button>` (via `InputGroupButton`) instead of a
  `<div onClick>` — keyboard reachable, screen-reader announced, and
  avoids the invalid-HTML nesting that putting an `<input>` inside a
  `<button>` would create.
- Configurable Mod+`hotkey` (default `'f'`, `null` to disable). The
  knowledges page uses `'k'` so it doesn't fight the browser's own
  Ctrl+F find-in-page.
- Escape clears the value on the first press, blurs + collapses on the
  second — matches native search-input muscle memory.
- Single collapse effect on `searchQuery` change instead of the
  duplicate blur+effect pair.
- `aria-label` prop wired to both the trigger button and the input.

The knowledges header now mounts this control bound to `?qs=` via
`useSearchParams`. The provider already debounces the URL value before
hitting `searchKnowledge`, so the input commits keystrokes immediately
(instant UI feedback) while the server roundtrip waits for the 400 ms
debounce. URL writes use `replace` to avoid history-stack churn.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 17:40:11 +07:00
Sergey KozyrenkoandClaude Opus 4.7 4430cfc329 fix(frontend): suppress ?q= storage restore when ?qs= is present
When `/knowledges` is opened via a `?qs=…` link, `useTableState`'s
mount-time restore was injecting the previous session's `?q=` from
storage on top of it — so a clean semantic-search URL silently became
`?qs=foo&q=python` and the user got a narrowed result set they didn't
ask for.

Added `skipRestore` to `useTableState` (defaults to `false`, captured
via a ref at mount so a later toggle doesn't replay a restore the user
has worked past). `knowledges.tsx` passes `searchParams.has('qs')` so
the restore is skipped exactly when the parameter is part of the
landing URL.

Mirror-to-storage on subsequent filter changes is unaffected — a
client filter the user actually types still persists to storage for
the next session.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 13:16:25 +07:00
Sergey KozyrenkoandClaude Opus 4.7 2a4417505a feat(frontend): wire knowledges provider to searchKnowledge via ?qs=
Knowledges list previously sourced everything from `knowledgeDocuments`.
When `?qs=` is present the provider now switches to `searchKnowledge`
(debounced 400ms, capped at 100 results) and feeds the resulting subset
through the same public `knowledges` array — so DataTable, the existing
`?q=` client filter, and DetailNavigation continue to walk it without
any consumer-side change.

Subscription cache merge in `lib/apollo.ts` only covers the
`knowledgeDocuments` root field; in search mode CRUD events trigger a
`refetchQueries(['searchKnowledge'])` via `useLatestRef` so the relevance
ordering stays consistent without freezing the boolean at mount.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 12:48:55 +07:00
Sergey KozyrenkoandClaude Opus 4.7 a55f7bd6eb feat(frontend): add Copy Token ID action to api-tokens row dropdown
Mirrors the entry already present in the right-click context menu so
both menus expose the same set of actions (Edit / Copy Token ID /
Delete) — the dropdown was previously missing the copy shortcut.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 11:35:48 +07:00
Sergey KozyrenkoandClaude Opus 4.7 d08295610a fix(frontend): suppress touch text-selection on rows with a context menu
Long-press on iOS/Android starts native text selection before Radix
ContextMenu reacts, so the row appears highlighted from the top of the
table down to the finger. Apply `user-select: none` and disable the iOS
callout on those rows only, and only on coarse pointers — desktop users
keep the ability to select cell text with the mouse.

Pattern matches the workaround discussed in radix-ui/primitives#930.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 11:35:39 +07:00
Sergey KozyrenkoandClaude Opus 4.7 85a7ee281f fix(frontend): keep table row highlighted while context menu or dropdown is open
Hover relies on the cursor staying over the <tr>, but Radix portals the
overlay so the row dims as soon as the menu opens. Match the same
background via `data-[state=open]` (ContextMenuTrigger forwards
`data-state="open"` onto the row through `asChild`) and
`has-[[data-state=open]]` (covers any Dropdown/Popover triggered from a
cell). Switch the selection prop to a conditional spread so the prior
`data-state={false}` no longer wins over Radix Slot's merged props.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 10:44:03 +07:00
Sergey KozyrenkoandClaude Opus 4.7 f369b411ed refactor(frontend): centralize document <title> in a single registry
Single source of truth for every route's tab title. All title knowledge —
static strings, params-derived resolvers, and Apollo-cache-driven reactive
components — now lives in src/lib/route-titles/, and app.tsx imports only
the `routeTitles` object. The router file no longer pulls Apollo hooks
or formatters; it just spreads handles onto routes.

Handle API collapsed from two keys to one. Following the canonical
`useMatches` example from React Router docs, `handle.title` is now a
single field that accepts three forms:

  • `string` — static, known at build time
  • `(params) => string` — synchronous resolver from URL params
  • `ComponentType<{ params }>` — reactive (e.g. Apollo cache subscription)

DocumentTitle distinguishes resolver vs component by the PascalCase
convention (component names start with an uppercase letter), so the
choice is implicit at the call site — no `titleComponent` field, no
discriminated union, no marker property.

Boilerplate consolidation:
- 4 near-clone resource-title components (Flow/Knowledge/Provider/
  Template) collapse into 4 declarative `apolloTitle({ useQuery,
  variables, select })` calls in the registry. The factory owns the
  `fetchPolicy: 'cache-only'` plumbing, skip semantics, and component
  naming.
- renderTitle/APP_NAME/RouteParams were duplicated between
  document-title.tsx and resource-titles.tsx — now imported from one
  render-title.tsx.
- formatPromptId moves into the route-titles module since the prompt
  detail page and the route handle are its only consumers.

References to React docs added to document-title.tsx: only one <title>
should be rendered from React at a time (multiple → undefined browser/
SEO behavior). The convention is now enforceable from one place.

All 482 unit tests pass; lint, tsc, prettier clean. Verified in the
browser across every route — static (Dashboard, Flows, Resources, …),
/new variants (New flow, New provider, …), params resolver
(/settings/prompts/agentSelector → "Agent Selector"), and Apollo
reactive (/flows/491 → "Flow #491 — Login Beta Program"), including
sibling navigation between detail routes which previously motivated
moving DocumentTitle into the shell.

Net diff: -171 / +66 across the touched files plus the new registry.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 09:39:25 +07:00
Sergey KozyrenkoandClaude Opus 4.7 73bb0e6446 fix(frontend): toast + redirect when knowledge document not found
Match the redirect pattern used on the flow page: instead of rendering
a dedicated "not found" card with a manual back button, show a toast
and replace the route with /knowledges so the user lands on the list
the same way other resources behave.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 09:39:25 +07:00
Sergey KozyrenkoandClaude Opus 4.7 f2fb222807 refactor(frontend): collapse PageTitle into DocumentTitle via route handles
Single mechanism for the document <title>. Every route now declares its
title in the react-router handle:

  • handle: { title: 'Dashboard' } — static listing pages
  • handle: { title: (params) => formatPromptId(params.promptId) } —
    params-derived (e.g. /settings/prompts/:promptId)
  • handle: { titleComponent: TemplateTitle } — Apollo cache-driven,
    reactive to cache updates after the page mounts

A single <DocumentTitle/> in RootLayout walks useMatches() and picks
the deepest match. PageTitle is gone — 13 call sites across 13 page
components migrated to handle, the component deleted.

Other improvements:
- Split document-title.tsx so the shell-only <DocumentTitle/> has zero
  graphql imports — the resource title components (FlowTitle,
  KnowledgeTitle, ProviderTitle, TemplateTitle) live in
  resource-titles.tsx. This lets the unit tests render DocumentTitle
  without dragging the codegenerated graphql/types.ts through Vite.
- String(p.id) === providerId replaces sloppy == in ProviderTitle.
- matches.findLast(...) replaces the imperative for-loop.
- Extracted formatPromptId into lib/utils/format-prompt-id.ts so the
  prompt detail page and the route handle resolver share one formatter.

7 unit tests added for DocumentTitle covering: static title, derived
title from params, deepest-match-wins, titleComponent rendering,
titleComponent precedence over static title, empty-string fallback,
and no-handle fallback.

19 test files / 482 tests pass; lint + tsc clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 09:39:25 +07:00
Sergey KozyrenkoandClaude Opus 4.7 3a67daaad8 refactor(frontend): drive document <title> from route handles
Move <title> ownership out of detail-page components into the app
shell. The four detail routes — templates/:templateId,
knowledges/:knowledgeId, settings/providers/:providerId,
flows/:flowId — now expose a titleComponent via react-router
handle. A new <DocumentTitle/> in RootLayout walks useMatches()
deepest-first and renders the matched title component. Each one
subscribes to its resource via Apollo with fetchPolicy:
'cache-only', so it reacts to the destination page's own fetch
without issuing a duplicate request.

Fixes the root cause behind bbf943e's sticky workaround: navigation
between sibling documents (DetailNavigation prev/next) tore down
the page-level state that PageTitle held, flashing a generic
fallback during data fetch. The shell-level <DocumentTitle/>
survives the remount, so the title resolves from cache before the
new page has finished mounting.

- Add src/components/shared/document-title.tsx with DocumentTitle
  plus FlowTitle / KnowledgeTitle / ProviderTitle / TemplateTitle.
- Wire <DocumentTitle/> into RootLayout and attach
  handle={{ titleComponent: ... }} on the four detail routes.
- Remove <PageTitle> calls and now-redundant <> wrappers from the
  four page components.
- Drop the sticky setState-during-render hack from PageTitle —
  listing pages that still use it never flickered, so the simple
  passthrough is enough.

Lint + tsc clean, all 475 tests pass. Listing routes (Dashboard,
Flows, Templates, Knowledges, etc.) keep using PageTitle and can
migrate route-by-route without coordination.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 09:39:25 +07:00
Sergey KozyrenkoandClaude Opus 4.7 765d743b21 refactor(frontend): inline API token forms on RHF + zod
Replace the two ad-hoc useState form objects (createFormData /
editFormData) in settings-api-tokens.tsx with parent-level useForm
hooks per inline row, each backed by a zod schema. Controller in
each DataTable cell re-subscribes to the parent form state on
remount, so subscription-driven row remounts no longer drop user
input — same root cause that 04c6825 fixed, but solved at the
architectural level instead of controlling each Input manually.

- tokenNameSchema (trim + max 255), createTokenFormSchema with
  required expiresAt via refine, editTokenFormSchema with status.
- <Input>, <Select> and <Calendar> cells rendered through
  <Controller>; RHF owns the values, not React state in the parent.
- CreateRowActions / EditRowActions subcomponents own the
  useFormState({ control }).isValid subscription so the Save button
  re-renders only the small action subtree on keystrokes instead of
  the whole table.
- Ad-hoc required/trim checks dropped from handlers; the schema +
  isValid gate handle them. Submit still applies trim() || null
  because the GraphQL mutation treats null as "no name."

All 18 test files / 475 tests pass; lint + tsc clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 09:39:24 +07:00
Sergey KozyrenkoandClaude Opus 4.7 9955da1243 style(frontend): prettier + replace Columns text button with icon
Manual formatting pass plus a UI tweak that turns the DataTable
"Columns" trigger into an icon-only ColumnsSettings button to match the
other toolbar controls' compact look. The button keeps its accessible
name via aria-label="Columns" so screen readers and
data-table.test.tsx (`getByRole('button', { name: /Columns/ })`) still
find it. Other touched files are pure prettier reformatting.

All 18 test files / 475 tests pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 09:39:24 +07:00
Sergey KozyrenkoandClaude Opus 4.7 0db486837a fix(frontend): give /new routes dedicated tab titles and add sticky fallback
The /providers/new, /knowledges/new and /templates/new routes shared the
generic fallback used during data loading on their respective detail
pages, so the browser tab read "Provider — PentAGI", "Knowledge —
PentAGI" or "Template — PentAGI" while the user was clearly creating a
new entity. /flows/new already did this correctly ("New flow — PentAGI")
and serves as the reference.

Each detail page already exposes an `isNew` flag derived from the route
param, so the fix is a one-line branch in each PageTitle call site:

  /settings/providers/new → "New provider — PentAGI"
  /knowledges/new         → "New knowledge — PentAGI"
  /templates/new          → "New template — PentAGI"

Verified in chrome-devtools MCP — all three tabs now show the new
titles.

While here, give PageTitle a sticky fallback: once a non-empty title is
rendered, briefly empty children (e.g. a data refetch on the same
route) keep showing the previous value instead of flashing the generic
"Provider/Knowledge/Template — PentAGI" fallback. This helps in-route
loading transitions; it intentionally does not survive route remounts
(navigating Prev/Next between sibling documents tears down the Template
component and the local state with it). A complete fix for the inter-
route flicker requires app-level state or an optimistic Apollo cache
read on mount and is out of scope here.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 09:39:24 +07:00
Sergey KozyrenkoandClaude Opus 4.7 b7ed0689a9 perf(frontend): drop Dashboard period-switch INP from 434ms to 134ms
The Analytics tab on /dashboard renders 4 Recharts plus a Flow
Execution Details list with 130+ Collapsible rows. Switching the period
(Week/Month/Quarter) re-rendered everything synchronously: the
pointerdown→paint interaction had INP=434ms (Google "Needs Improvement"
zone), with processing duration alone accounting for 403ms.

Four small changes, no new dependencies:

  1. useMemo on usageChartData / toolcallsChartData / flowsChartData so
     Recharts receives stable references when only an unrelated piece
     of parent state changes (e.g. tooltip hover state).
  2. useDeferredValue(executionStats) so a period switch can repaint
     the charts first and reconcile the long list as a low-priority
     follow-up. While the deferred value is stale we dim the list to
     60% opacity, matching the existing dashboard.tsx convention.
  3. content-visibility: auto + contain-intrinsic-size on every
     FlowExecutionItem. Off-screen rows skip layout and paint entirely
     — this is the cheapest possible virtualization, with no deps,
     measurement, or scroll math.
  4. React.memo on FlowExecutionItem and TaskExecutionItem so parent
     re-renders don't traverse the entire 130-row tree.

Measured via chrome-devtools MCP performance trace:

  Before:  INP 434ms — input 1ms / processing 403ms / present 29ms
  After:   INP 134ms — input 1ms / processing 112ms / present 21ms

CLS stays at 0.00.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 09:39:24 +07:00
Sergey KozyrenkoandClaude Opus 4.7 1a8b04aa0d fix(frontend): persist API token name through subscription refetches
The inline create/edit row in the API tokens table used uncontrolled
<Input ref={…} defaultValue="…" /> and read the value back from the ref
inside the submit handler. When the apiTokens subscription fired during
the user's interaction, DataTable would reorder rows and the input would
re-mount with defaultValue="" (or the original name), discarding what
the user just typed. The mutation then sent name: null and the freshly
created token appeared as "(unnamed)".

Move both create and edit name inputs to controlled state, drop the
two refs, and read the value from form state at submit time so it
survives any number of re-mounts. While here, give each input a stable
useId() for id, an explicit name="token-name", and autoComplete="off"
to silence the "A form field element should have an id or name
attribute" Chrome DevTools issue that this form was triggering.

Verified via chrome-devtools MCP: creating a token named "qa-pr1-verify"
now stores and displays the name correctly across the
useApiTokenCreatedSubscription refetch.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 09:39:24 +07:00
Sergey KozyrenkoandClaude Opus 4.7 73c6652dbf perf(frontend): useOptimistic for flow rename and favorite toggle
Two long-running mutations now flip the UI on the urgent track and
reconcile against the server in the background, so the user no longer
sees the latency between a confirming click and the network round-trip.

pages/flows/flow.tsx — inline rename
- New optimistic title state seeded from `flow.title` and updated via
  `setOptimisticFlowTitle(next)` at the start of the save handler.
- Mutation runs inside `startTransition(async () => …)` so React keeps
  the optimistic title visible while awaiting the rename. On success
  the Apollo cache update lands and useOptimistic falls back to the
  fresh `actualFlowTitle`; on failure the toast surfaces and the value
  rolls back to the cached title automatically.

providers/favorites-provider.tsx — toggle favorite
- `useOptimistic` over the favorite-ids array with an `add`/`remove`
  action reducer. addFavoriteFlow and removeFavoriteFlow wrap their
  Apollo mutations in `startTransition` and call
  `applyOptimisticFavorite` first, so the sidebar's Favorite Flows
  list and the row's star both flip instantly.
- Subscription-driven cache refresh still arrives a moment later and
  becomes the new `actualFavoriteFlowIds`; React's transition exits
  without a visible flicker because the optimistic value already
  matches what the cache now holds.

Verified: build, lint (0/44 baseline), 475/475 tests, browser smoke —
clicking the favorite star on /flows immediately moves the row into
"Favorite Flows" in the sidebar and back, no console errors.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 09:39:23 +07:00
Sergey KozyrenkoandClaude Opus 4.7 1eb3ae1389 refactor(frontend): make FormSubmitButton fully accept Button's API
Reworks the FormSubmitButton so it slots into every Button use-case
in the codebase, not just the simplest text-only submits:

- Adds an `icon` prop. While the form is idle the icon renders to the
  left of `children`; while submitting it is swapped for the spinner
  in place, so the button keeps its layout. Plain text buttons stay
  the same — the spinner is prepended only during submit.
- Adds an optional `loading` prop. When provided it wins over
  `formState.isSubmitting`, which unlocks two real cases we
  previously had to skip: submits attached via the HTML `form="…"`
  attribute that live outside the FormProvider tree, and submits
  whose pending state is the union of several mutation flags.
- Reads `useFormContext()` defensively — it returns null outside
  a FormProvider, so the component degrades to "controlled by
  `loading` prop only" instead of throwing. That keeps the API
  honest for both in-tree and out-of-tree submits.

All other Button props (variant, size, className, onClick,
aria-label, form, …) pass through unchanged because the type
extends `React.ComponentProps<typeof Button>`.

Applied to two more previously-skipped sites:
- settings-provider.tsx Save button (form="provider-form",
  loading=isLoading union, Save icon, dynamic label).
- settings-prompt.tsx system and human Save buttons (same shape).

resources-mkdir-dialog now passes FolderPlus via the new `icon`
prop instead of putting it inside children, so the dialog's submit
spinner replaces the folder icon in place during submit.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 09:39:23 +07:00
Sergey KozyrenkoandClaude Opus 4.7 e15839bab1 feat(frontend): add FormSubmitButton and apply it to three forms
New shared component src/components/ui/form-submit-button.tsx. It is
the react-hook-form-flavoured analogue of React 19's useFormStatus:
the button subscribes to the nearest FormProvider via useFormContext
and reads formState.isSubmitting / isValid / isSubmitted itself, so
the surrounding form no longer has to thread loading flags down.
Shows a Loader2 spinner while submitting and disables itself once
the form is dirty-and-invalid (opt out with requireValid={false}).

Applied to the three forms where the submit is a plain
<Button type="submit"> living inside a <Form {...form}> wrapper:

- login-form.tsx — also dropped the manual isSubmitting toggles
  inside the form handler (RHF already tracks that through
  form.handleSubmit). Kept the OAuth-flow useState because the
  provider login does not go through form.handleSubmit; combined
  the two states on the OAuth buttons so they also disable while
  the form is submitting.
- password-change-form.tsx — dropped the manual isSubmitting state
  entirely; the only submit goes through form.handleSubmit. Cancel
  and Skip buttons stay as plain Buttons.
- resources-mkdir-dialog.tsx — replaced the submit button; kept the
  isCreating flag because Cancel and the Input still need to react
  to the mutation in flight.

Five other forms intentionally kept their current submit:
- knowledge-form.tsx uses our HeaderButton (responsive icon/label)
  with its own Spinner, not a plain Button.
- flow-form.tsx and templates/template.tsx use InputGroupButton
  (icon-only, sits inside an InputGroupAddon).
- settings-prompt.tsx and settings-provider.tsx attach their submit
  to the form via the HTML form="…" attribute, so the button is
  outside the FormProvider tree — useFormContext would throw.
  These also drive disabled state from multiple mutation flags
  (create/update/delete/validate) that aren't reducible to a single
  isSubmitting.

Verified: pnpm run build, lint (0/44 baseline unchanged), 475/475 tests.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 09:39:23 +07:00
Sergey KozyrenkoandClaude Opus 4.7 338d39c10c fix(frontend): use first letter instead of calendar icons on mobile period switcher
Three nearly-identical calendar icons (CalendarDays / Calendar /
CalendarRange) didn't convey Week vs Month vs Quarter clearly on a
375 px viewport — the differences between the glyphs are too subtle
at 16 px. Swapped them for the first letter of each label (W / M / Q)
with the same compact `size-7` button shape; full label stays on
sm+ as before.

Kept aria-label on the trigger and aria-hidden on the letter span so
screen readers still announce the full word.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 09:39:23 +07:00
Sergey KozyrenkoandClaude Opus 4.7 96e91d2a2a fix(frontend): make mobile period triggers compact icon buttons
The mobile period switcher swap landed in 28c98a8 but kept the
text-button paddings (px-3), so each "icon-only" trigger was still
~36 px wide and the group looked stretched on a 375 px viewport.

Added \`aspect-square px-0\` to each TabsTrigger (with the desktop
overrides reset above the \`sm\` breakpoint) so the buttons collapse
to a 1:1 ratio on mobile — three tight squares matching shadcn's
icon-button proportions — while desktop keeps the original
horizontal padding.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 09:39:23 +07:00
Sergey KozyrenkoandClaude Opus 4.7 e02da42f39 feat(frontend): collapse Dashboard period switcher to icons on mobile
On screens narrower than the `sm` breakpoint (640 px) the
Week / Month / Quarter triggers were forcing the period switcher to
crowd the Analytics / Overview tabs into the next line. Replaced
the labels with lucide calendar icons (CalendarDays / Calendar /
CalendarRange) that swap in below `sm` while the full text comes
back above it.

Accessibility preserved — each TabsTrigger keeps an explicit
aria-label and the icons are aria-hidden so screen readers still
announce "Week" / "Month" / "Quarter" instead of duplicate icon
descriptions.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 09:39:23 +07:00
Sergey KozyrenkoandClaude Opus 4.7 58d01e0a67 perf(frontend): defer heavy Dashboard tab switches via useTransition
Both tab groups on /dashboard trigger expensive re-renders:
- Analytics ↔ Overview swaps the entire content subtree (Analytics
  alone pulls in a ~386 kB chunk with four Recharts views).
- Week / Month / Quarter invalidates the analytics query and
  re-paints every chart with the new dataset.

Wrapped both setState calls in startTransition so the trigger
buttons update on the urgent track while the heavy work commits as
low-priority. React will discard intermediate frames if the user
clicks again before the previous transition finishes.

Surfaces the combined isPending state via a subtle opacity-60 dim
plus aria-busy on the content region — gives users feedback that
the heavier render is in flight without a spinner flash.

Verified: build, lint (0/44 baseline), 475/475 tests, browser smoke
on /dashboard with no console errors after switching periods.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 09:39:22 +07:00
Sergey KozyrenkoandClaude Opus 4.7 dea9e38107 refactor(frontend): unify the whole codebase on function declarations
Brings every top-level React component and hook outside of
src/components/{ui,shared} (those were already migrated in 9d5daf7)
in line with the shadcn/ui new-york-v4 canonical style:

- features/* (flows, knowledges, resources, authentication, …)
- pages/* (dashboard, flows, knowledges, settings, templates, login,
  oauth-result, resources)
- providers/* (all eleven context providers + their useXxx hooks)
- components/icons/* (every SVG icon + provider-icon, flow-status-*)
- components/layouts/* and components/routes/*
- hooks/* (use-* hooks in their own files)
- Calendar UI component (missed in the earlier pass — also dropped
  the redundant `displayName = 'Calendar'` and the empty
  `CalendarProps = DayPickerProps` alias)

Net diff is +50 lines (1842 ins / 1792 del — the lines that were
removed are the `const X = (…) =>` declarations and the matching
closing `;`, plus a handful of explicit `React.FC<…>` type
annotations that no longer add anything; the lines added are the
`function X(…) {`/`}` envelopes).

What we deliberately did NOT touch:
- Inner components/hooks defined inside other functions — keep their
  arrow form so the local-scope intent stays visible.
- React.memo / React.lazy wrappers — `const X = memo(InnerX)` and
  `const X = lazy(() => …)` aren't components themselves.
- Render-callback props (renderFlowItem, renderItem, …).
- Plain utilities, helpers, factories, REST/GraphQL builders and
  every file under lib/, models/, schemas/, types/, graphql/types.ts.
- The few callback-ref-composing components (autocomplete, textarea,
  markdown-editor) keep their explicit `ref?: Ref<CustomShape>`
  because ComponentProps can't express their custom imperative shape.

Bonus cleanup along the way: removed the now-unused
`import * as React` from settings-prompt.tsx (was only there for the
deleted `React.FC` typing).

Verified: pnpm run build, lint (0 errors / 44 warnings unchanged
baseline) and 475/475 vitest tests.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 09:39:22 +07:00
Sergey KozyrenkoandClaude Opus 4.7 39adab6f8c chore(frontend): drop redundant displayName outside components/ui
Removes two leftover `X.displayName = 'X'` lines that just duplicated
the function's own name:
- src/components/shared/terminal/terminal.tsx
- src/components/shared/monaco-terminal.tsx

Two other displayName usages in the wider codebase are kept on
purpose:
- markdown.tsx — factory creates an inner `Renderer` and stamps it
  `Highlighted(${ComponentName})` so each instance shows up
  distinctly in React DevTools.
- file-manager-row.tsx — the function is named `FileManagerRowImpl`
  and re-exported through React.memo as `FileManagerRow`; the
  displayName carries the public name across the memo wrapper.

The five `.displayName` mentions in src/pages/settings/settings-prompt*
are property reads (`promptInfo.displayName`, `row.original.displayName`)
on domain data, not component metadata — untouched.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 09:39:22 +07:00
Sergey KozyrenkoandClaude Opus 4.7 99f8485ae0 refactor(frontend): adopt shadcn/ui new-york-v4 component style
Brings all 32 components in src/components/{ui,shared} in line with
the current shadcn/ui new-york-v4 canon (cross-checked against the
upstream registry tooltip / button / input / dialog sources). Net
diff is -637 lines of boilerplate.

Four shape changes per component:
1. function declaration instead of `const X = (...) =>`. Slightly
   cleaner stack traces and Function.name is set automatically.
2. React.ComponentProps<typeof X> (or React.ComponentProps<"button">
   for native elements) instead of
   React.ComponentPropsWithoutRef<typeof X> & { ref?: React.Ref<...> }.
   In React 19 ref is already part of ComponentProps; the explicit
   intersection was leftover noise.
3. `ref` is no longer destructured — it flows through `{...props}`
   spread into the underlying primitive. Exceptions kept verbatim:
   textarea.tsx (custom TextareaRef shape with useImperativeHandle),
   autocomplete.tsx (callback-ref composition in AutocompleteInput
   and AutocompleteContent), markdown-editor.tsx (MarkdownEditorHandle
   with useImperativeHandle).
4. displayName removed everywhere — Function.name covers React DevTools
   now that there is no forwardRef wrapper to hide it.

Verified: pnpm run build, lint (0 errors / 44 warnings unchanged
baseline) and 475/475 vitest tests.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 09:39:22 +07:00
Sergey KozyrenkoandClaude Opus 4.7 b5b3cbe99b feat(frontend): per-route document titles via React 19 metadata
Adds a tiny <PageTitle> wrapper around React 19's native <title>
element (which React hoists into <head> automatically) and uses it
from every page-level route. Browser tabs, history, and shareable
URLs now reflect the actual page instead of the static "PentAGI"
that index.html ships.

- Static titles for list and form pages (Dashboard, Flows, New flow,
  Flow report, Templates, Knowledges, Resources, Providers, Prompts,
  API tokens, Login, OAuth).
- Dynamic titles for detail pages — flow title + id, knowledge
  question, template name, provider name, prompt display name — with
  graceful fallbacks while data is still loading.
- Added to every render branch (loading / error / empty / main) so
  the tab title stays correct even before data lands.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 09:39:22 +07:00
Sergey KozyrenkoandClaude Opus 4.7 53c140dd70 refactor(frontend): drop React.forwardRef for ref-as-prop (React 19)
Migrates all 32 components in src/components/{ui,shared} from
React.forwardRef<RefT, PropsT> to plain functional components that
take `ref?: React.Ref<RefT>` as a regular prop. React 19 treats ref
like any other prop, so the forwardRef wrapper is no longer needed
and only added boilerplate + an extra type parameter.

Highlights:
- All 32 files keep their displayName so React DevTools and Radix
  Slot composition still surface readable component names.
- Custom-shape refs (TextareaRef in textarea.tsx and
  MarkdownEditorHandle in markdown-editor.tsx) plus the callback-ref
  composition inside autocomplete.tsx are preserved verbatim — only
  the wrapper changes.
- sidebar.tsx contained 22 forwardRef wrappers in one file; all
  converted in the same pass.
- No behaviour, classes, attributes or imports of `import * as React`
  are touched. pnpm run lint:fix afterwards reformatted the auto-added
  blank lines so we are back to 0 errors / 44 warnings (baseline).

Verified: pnpm run build, lint, and 475/475 vitest tests.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 09:39:21 +07:00
Sergey KozyrenkoandClaude Opus 4.7 de39cf1065 perf(frontend): defer DataTable filter pipeline via useDeferredValue
Wraps the composite globalFilter ({ columns, query }) in
React.useDeferredValue before handing it to TanStack's state. The
filter input itself stays urgent (already debounced to 300 ms), so
keystrokes still feel instant; what becomes low-priority is the
heavy getFilteredRowModel() recomputation that runs over the full
dataset — ≈353 flows, 180 knowledge documents, ~50 templates and
API tokens. On those screens React can now drop intermediate filter
states when the user is still typing, instead of committing each
debounce tick on the urgent track.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 09:39:21 +07:00
Sergey KozyrenkoandClaude Opus 4.7 450e374166 style(frontend): apply prettier formatting fixes
- detail-navigation-buttons.tsx: wrap long cn() call across lines
- knowledge-header.tsx: alphabetize lucide-react named imports
- flow.tsx: reorder Tailwind classes per prettier-plugin-tailwindcss
  canonical order

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 09:39:21 +07:00
Sergey KozyrenkoandClaude Opus 4.7 827fd46c81 chore(frontend): silence 5 long-standing lint errors with targeted disables
Drops pnpm run lint from 5 errors to 0 (warnings unchanged at 44).
Each disable is the smallest local suppression with a one-line reason
on the same comment, so the next reader sees why the rule was muted:

- src/components/ui/textarea.tsx (line 79): the effect intentionally
  syncs the internal auto-size trigger with the controlled value prop
  every time the parent changes it.
- src/features/flows/files/use-flow-container-files.ts (line 107): the
  effect calls an async fetcher (fetchListing) whose setState runs
  after await — not synchronously inside the effect body; pathsKey is
  intentionally used in place of the paths array reference.
- src/pages/settings/settings-prompt.tsx (line 344): the useMemo
  branches on data.settingsPrompts which the react-compiler can't
  statically prove stable.
- src/providers/resources-provider.tsx (line 70): intentional
  mount-time loading flag for the REST hydration path.
- src/providers/user-provider.tsx (line 144): refreshAuthInfo's
  setState runs after an async /auth/info fetch, not synchronously.

Build, 475/475 vitest tests, and runtime smoke (dashboard, flows,
knowledges, settings/providers) all pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 09:39:21 +07:00
Sergey KozyrenkoandClaude Opus 4.7 b713d6d004 chore(frontend): update remaining deps to latest within caret ranges
Runs pnpm update + bumps prettier-plugin-tailwindcss 0.7.4 → 0.8.0
(the 0.8 release is the one that pairs with Tailwind v4).

After this commit, pnpm outdated only reports three deliberately
pinned packages: eslint / @eslint/js (held on 9.x while
eslint-plugin-react still targets eslint ^9) and @types/node (held on
24.x to match the Node 24.12 runtime; npm latest is 25.x for Node 25).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 09:39:21 +07:00
Sergey KozyrenkoandClaude Opus 4.7 bd6f3b1c43 chore(frontend): align @types/node with node 24.12
Bumps @types/node 22.19.19 → 24.12.4 to match the actual Node 24.12
runtime the project is built and run on. The latest published tag is
25.x (for the not-yet-released Node 25 line); we deliberately stay on
24.x.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 09:39:21 +07:00
Sergey KozyrenkoandClaude Opus 4.7 5ac904d740 chore(frontend): upgrade commitlint to v21
Bumps @commitlint/cli and @commitlint/config-conventional from 20.5.3
to 21.0.1. Dev-only — affects the commit-message hook, not the app.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 09:39:20 +07:00
Sergey KozyrenkoandClaude Opus 4.7 41d5277216 chore(frontend): upgrade typescript to v6
Bumps typescript 5.9.3 → 6.0.3.

Adds compilerOptions.ignoreDeprecations = "6.0" to tsconfig.json so the
existing baseUrl/paths setup keeps working — TS 6 has flagged baseUrl
as deprecated (it will be removed in 7.0). The vite-tsconfig-paths
plugin still consumes the paths mapping; nothing else in the codebase
needed changes.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 09:39:20 +07:00
Sergey KozyrenkoandClaude Opus 4.7 f7e61b4fe5 chore(frontend): upgrade eslint-plugin-perfectionist to v5 (eslint kept on v9)
Bumps eslint-plugin-perfectionist 4.15.1 → 5.9.0.

eslint and @eslint/js are intentionally kept on 9.39.4 (the latest
9.x): eslint 10 changes the rule context API
(contextOrFilename.getFilename is gone) and eslint-plugin-react still
ships only versions targeting eslint ^9 — the v10 upgrade currently
crashes the lint run with "Error while loading rule
'react/display-name'". Once eslint-plugin-react publishes a v10-aware
release we can finish this bump.

perfectionist v5 already supports the eslint ^8.45 || ^9 || ^10 peer
range, so it ships cleanly today and gives us its v5 rule changes
without dragging eslint along.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 09:39:20 +07:00
Sergey KozyrenkoandClaude Opus 4.7 1fa879839e chore(frontend): upgrade vite to v8
Bumps vite 7.3.3 → 8.0.13 and vite-tsconfig-paths 5.1.4 → 6.1.1.

Vite 8 ships rolldown (the Rust bundler that replaced rollup) and that
required two fixes:

1. build.rollupOptions.output.manualChunks: rolldown no longer accepts
   the { chunkName: [packages] } static object form, so it is now an
   (id) => string callback that matches paths under node_modules.

2. src/components/ui/resizable.tsx: switched from the namespace import
   `import * as ResizablePrimitive` to named `{ Group, Panel, Separator }`
   from react-resizable-panels. The v4 release of that library renamed
   PanelGroup → Group and PanelResizeHandle → Separator; rollup's
   loose tree-shaking happened to keep the old names working at
   build-time, but rolldown enforces the export list and the page
   failed at runtime with "Element type is invalid". Public wrapper
   exports (ResizableHandle, ResizablePanel, ResizablePanelGroup) are
   unchanged so the rest of the app keeps working.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 09:39:20 +07:00
Sergey KozyrenkoandClaude Opus 4.7 8a3d4e951d chore(frontend): upgrade graphql-codegen toolchain
Bumps the codegen stack: cli 6→7, client-preset 5→6, typescript 5→6,
typescript-operations 5→6 (typescript-react-apollo and
near-operation-file-preset only moved within their minor range).

Configures typescript-react-apollo to emit Apollo v4-compatible imports
via apolloReactCommonImportFrom / apolloReactHooksImportFrom set to
@apollo/client/react, so re-running pnpm run graphql:generate now
produces ApolloReactCommon / ApolloReactHooks namespaces from the v4
subpath instead of the v3 single-entry import.

src/graphql/types.ts is fully regenerated under the new config.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 09:39:20 +07:00
Sergey KozyrenkoandClaude Opus 4.7 b6d9983563 chore(frontend): upgrade @apollo/client to v4
Bumps @apollo/client from 3.14.1 to 4.1.9.

Apollo v4 moved React-only exports to the @apollo/client/react
subpath. Updated the three import sites that consume them:
- ApolloProvider in app.tsx
- useApolloClient in providers/resources-provider.tsx
- the Apollo namespace import in graphql/types.ts (covers useQuery,
  useMutation, useSubscription, useLazyQuery, useSuspenseQuery,
  skipToken, *HookOptions, *QueryResult)

Everything else (gql, ApolloClient, ApolloLink, createHttpLink,
InMemoryCache, Observable, split, NetworkStatus, getMainDefinition,
onError, GraphQLWsLink) keeps its existing import path in v4.

Build output shrunk from 223 kB to 191 kB for the apollo-client chunk.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 09:39:20 +07:00
Sergey KozyrenkoandClaude Opus 4.7 de18fe2c31 chore(frontend): upgrade zod to v4 with hookform/resolvers v5
Bumps zod 3.25.76 → 4.4.3 and @hookform/resolvers 3.10.0 → 5.2.2
(the resolvers v5 requires zod v4).

zod is used in 25 source files (schemas, form validators, table state
parsers). Build passes without changes — the project relies on the
shared subset of the v3/v4 API (z.object/z.string/z.number/z.enum,
z.infer, .min/.max/.optional, refinements). Runtime form validation
keeps disabling submit until required fields are filled.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 09:39:19 +07:00
Sergey KozyrenkoandClaude Opus 4.7 6d227e1d7d chore(frontend): upgrade react-resizable-panels to v4
Bumps react-resizable-panels from 3.0.6 to 4.11.1. The wrapper in
src/components/ui/resizable.tsx only re-exports PanelGroup, Panel and
PanelResizeHandle; their props remain compatible across the major.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 09:39:19 +07:00
Sergey KozyrenkoandClaude Opus 4.7 45e509ff48 chore(frontend): upgrade react-day-picker to v10
Bumps react-day-picker from 9.14.0 to 10.0.1. The Calendar wrapper in
src/components/ui/calendar.tsx uses the v9 classNames keys
(button_next/previous, day_button, range_*, week, weekday, weekdays)
and the components.Chevron API; all of these are preserved in v10.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 09:39:19 +07:00
Sergey KozyrenkoandClaude Opus 4.7 6c8e4ea35a chore(frontend): upgrade marked to v18
Bumps marked from 17.0.6 to 18.0.3. Used only in
src/lib/report/report-pdf.tsx for PDF generation via marked.lexer();
that API is compatible across the major.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 09:39:19 +07:00
Sergey KozyrenkoandClaude Opus 4.7 f655ad872d chore(frontend): upgrade lucide-react to 1.x
Bumps lucide-react from 0.553.0 to 1.16.0. The 0.x → 1.x jump is a
versioning policy change, not a breaking API change — all icon imports
keep working as before.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 09:39:19 +07:00
Sergey KozyrenkoandClaude Opus 4.7 8c346275d9 chore(frontend): bump react to 19.2.6 and align @types
Pin React/React-DOM to 19.2.6 and @types/react* to 19.2.0 in
package.json — lockfile already resolved the latest 19.x; this just
makes the minimum explicit so future installs don't regress.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 09:39:18 +07:00
Dmitry Ng 39f122467d feat(config): add new embedding and rename database connection pool settings
- Introduced `EMBEDDING_MAX_TEXT_BYTES` to limit the maximum byte size of text sent to the embedding model.
- Renamed database connection pool settings: `DATABASE_MAX_OPEN_CONNS`, `DATABASE_MAX_IDLE_CONNS`, and `DATABASE_VECTOR_MAX_CONNS` for improved PostgreSQL connection management.
- Updated relevant documentation to reflect these new configuration options and their usage.
- Adjusted various components to utilize the new settings for enhanced performance and resource management.
2026-05-18 18:26:52 +03:00
Dmitry Ng 2ce863ec1a feat(toolcall): implement ToolCall logging functionality
- Added ToolCallLogProvider interface with methods for logging tool calls, updating success and failure statuses.
- Introduced proxyToolCallLogProvider to handle ToolCall logging operations.
- Updated flow execution components to integrate ToolCall logging, including flow workers and controllers.
- Enhanced GraphQL schema to support ToolCall logs, including queries and subscriptions for real-time updates.
- Updated documentation to reflect the new ToolCall logging features and their usage.
2026-05-18 11:21:56 +03:00
Dmitry Ng 077ddce476 feat(database): enhance PostgreSQL connection pooling and configuration
- Introduced shared connection pooling for PostgreSQL using `*sql.DB` for sqlc and GORM, optimizing resource usage.
- Added new environment variables: `DB_MAX_OPEN_CONNS`, `DB_MAX_IDLE_CONNS`, and `DB_VECTOR_MAX_CONNS` for configurable connection limits.
- Updated documentation to reflect new connection pooling strategy and provide operational commands for monitoring.
- Implemented shared `pgxpool` for pgvector stores to reduce connection overhead and improve performance.
- Adjusted various components to utilize the new connection pooling setup, ensuring efficient database interactions.
2026-05-18 11:13:43 +03:00
Dmitry Ng f970922ea5 Merge remote-tracking branch 'origin/feature/frontend-next' into feature/next-release 2026-05-16 22:54:28 +03:00
Dmitry Ng 1bb7f8a9a0 feat(flow): add WaitTaskCompletion method and associated tools for assistant
- Introduced WaitTaskCompletion method in FlowWorker interface to block until the current task completes or the context expires.
- Implemented signalTaskComplete to manage task completion signaling across goroutines.
- Added waitFlowCompletion tool to handle waiting for task completion with configurable timeout.
- Updated assistant provider to include wait functionality for flow completion.
- Enhanced templates and tool registry to support new wait functionality.
2026-05-16 22:52:51 +03:00
Dmitry Ng 548c54c761 fix(controller): remove close(aw.input) to prevent nil channel deadlock on assistant finish 2026-05-16 22:51:07 +03:00
Dmitry Ng 888f7e2a4f fix(subscriptions): drop events for slow/disconnected subscribers after 5s timeout 2026-05-16 22:49:49 +03:00
Sergey KozyrenkoandClaude Opus 4.7 31803630d3 feat(frontend): add Anonymize action to knowledge document form
Gated behind the `anonymize.call` privilege from `useUser()`; runs the
current `content` through the `anonymizeText` GraphQL mutation and writes
the result back. Desktop renders the button before Save; mobile collapses
it into the first item of the actions dropdown (the dropdown now appears
for new documents too when the privilege is present).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-17 02:31:47 +07:00
Sergey KozyrenkoandClaude Opus 4.7 35e077fd8b fix(frontend): always refetch knowledgeDocuments on provider remount
The Apollo client's global nextFetchPolicy is 'cache-first', so returning
to /knowledges via SPA navigation would serve potentially stale cache.
Subscriptions are now scoped to /knowledges* and detach on other pages,
so changes from AI agents during flow runs would be missed until a full
reload. Override nextFetchPolicy to keep cache-and-network for this query.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 23:26:44 +07:00
Sergey KozyrenkoandClaude Opus 4.7 258b677c01 fix(frontend): scope KnowledgesProvider to /knowledges routes
KnowledgesProvider sat in RootLayout, so knowledgeDocuments (with full
content) and its 3 subscriptions fired on every authenticated page —
a ~2.1 MB payload on /flows, /dashboard, etc. All consumers of
useKnowledges live under /knowledges*, so wrap those routes in a
dedicated layout.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 22:45:48 +07:00
Sergey KozyrenkoandClaude Opus 4.7 cc6b525f57 fix(frontend): cap DataTable filter input at 200 chars
A paste of multi-KB content into the filter would land in the URL
verbatim (`?q=` plus the raw blob), which exceeds the practical
reverse-proxy limit (~2–4 KB) and breaks the share-link experience.
The user-facing entry point is a single `<input>`, so a DOM-level
`maxLength` is sufficient — it truncates both typing and paste before
the value ever reaches React state, the URL, or localStorage. 200 chars
is well above any realistic search term while leaving plenty of
headroom for non-ASCII expansion under percent-encoding.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 21:41:42 +07:00
Sergey KozyrenkoandClaude Opus 4.7 022e8f3df0 refactor(frontend): unify table URL state under useTableState
The split `useTableQueryFilter` + `usePagination` pair had a latent batching
race: react-router v6 feeds every functional `setSearchParams(updater)`
queued in a single React tick the same pre-batch snapshot, so a `setFilter`
+ `setPage` issued from the same event handler (e.g. a debounced filter
commit landing alongside a paging click) would collapse — the second
write erased the first and `q` disappeared from the URL. The earlier
window.location workaround papered over the symptom for the typical case
but didn't remove the underlying possibility.

Replace both hooks with `useTableState`, which owns filter + pageIndex +
storage roundtrip together and routes every URL write through a single
microtask-coalesced `update(patch)`. When multiple `update` calls fire in
the same tick — `setFilter` and `setPage`, two synchronous handlers, an
effect and a click — they merge into one navigation rather than racing.
Replace conflicts resolve in favour of push, so intentional history
entries (paging) survive coalescence with replace-only updates (filter
typing). The `MemoryRouter` fallback (latest snapshot via ref) is kept
only as a defensive read; the coalescence itself makes it redundant.

A regression test (`two top-level updaters firing in the same tick keep
both params`) locks this in: the previous behaviour failed it, the new
implementation passes it without touching `window.location`.

Read-only siblings stay on `useTableQueryFilterReader` — detail pages
don't write the URL, so no race surface to remove. `usePagination`
deleted entirely; its callers migrated to `useTableState`.

474/474 tests pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 21:26:14 +07:00
Sergey KozyrenkoandClaude Opus 4.7 019ddcb1a7 fix(frontend): preserve URL params across batched setSearchParams updates
When a debounced filter commit and a paging button click land in the same
React tick, react-router v6 feeds the functional updater of every queued
`setSearchParams` call the same pre-batch snapshot. The second write
overwrites the first instead of stacking, so `setFilter('foo')` followed
by `setPage(5)` collapses to `?page=6` and `q` is lost. The QA pass
caught this on /flows: clicking >> right after typing in the filter
silently dropped `?q=` from the share-able URL.

Build the next `URLSearchParams` from `window.location.search` instead,
since that's the freshest source of truth under BrowserRouter and
sidesteps react-router's batching entirely. Fall back to the latest
react-router snapshot (stashed in a render-synced ref) under
MemoryRouter, which the hook tests use — `MemoryRouter` doesn't sync
its in-memory history to `window.location`.

478/478 existing tests still pass; the browser repro that previously
produced `?page=6` now correctly produces `?q=bypass&page=6`.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 20:48:06 +07:00
Sergey Kozyrenko cd0fff34f3 fix 2026-05-16 20:30:38 +07:00
Sergey KozyrenkoandClaude Opus 4.7 ca32c199e8 refactor(frontend): compose DataTable storageKey via usePageStorageKeys
Hard-coding the full `table_4_/settings/prompts:agents` / `:tools` keys in
the page duplicated the route prefix that `usePageStorageKeys` already
computes — if the prefix ever bumps (e.g. `table_4_` → `table_5_` on a
storage migration), every call site silently goes stale. Read the route
base from the hook instead and only own the per-table suffix in the page.
Updated the `storageKey` JSDoc on DataTable to document this composition
pattern.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 20:28:15 +07:00
Sergey KozyrenkoandClaude Opus 4.7 de695ec1c5 docs(frontend): DataTable QA scenarios and findings
Capture the QA pass we did against the multi-column search rollout:
INP baselines per page, the four bugs we hit (two fixed in the
follow-up commit, two left as backlog), the negative results from
the adversarial input pass (XSS / SQLi / regex meta / unicode /
prototype pollution via localStorage), and the regression scenarios
(S1–S11) so the next round of changes has a concrete checklist
instead of "run it and see if it feels OK".

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 20:22:32 +07:00
Sergey KozyrenkoandClaude Opus 4.7 1d81974fa3 fix(frontend): unique DataTable input id and per-instance storageKey
Two issues uncovered by the QA pass over /settings/prompts, where one page
mounts two DataTable instances:

1. Both inputs shared a hard-coded `id="data-table-search"` and
   `name="search"`. `document.getElementById` only ever found the first
   one, screen readers couldn't disambiguate the two filter inputs, and
   any test selector keyed on the id silently picked the wrong field.
   Switch to `useId()` so the id and name are per-instance, non-empty,
   and stable across renders.

2. Both tables persisted sorting / column visibility / search-column
   narrowing into the same `table_4_/settings/prompts` slot. The last
   writer won the race; on reload the loser inherited the winner's
   state. Add a `storageKey?: string` prop to DataTable (mirroring the
   existing `useTableQueryFilter` API) and pass `…:agents` / `…:tools`
   for the two tables on /settings/prompts so they get distinct slots.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 20:22:15 +07:00
Sergey KozyrenkoandClaude Opus 4.7 f12b469199 feat(frontend): extend Settings/Prompts search across both tables
For both the Agent Prompts and Tool Prompts tables, mark every accessor
column with `meta.searchable: true` (name + status fields) and drop the
explicit `filterColumn="displayName"`. Typing "Custom" now surfaces
every prompt currently overridden — a much more useful starting point
than scanning the column visually. Added `columnMenuLabel` overrides
where the underlying accessorKey wasn't human-readable on its own.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 17:27:10 +07:00
Sergey KozyrenkoandClaude Opus 4.7 eedc6ece41 feat(frontend): extend Settings/API Tokens search to id and status
Mark `name`, `tokenId`, and `status` with `meta.searchable: true` and
drop the explicit `filterColumn="name"`. The bigger wins are tokenId
(operators often paste a fragment from logs or a request header to find
the owning token) and status (typing "revoked" surfaces every revoked
token without scrolling). Date columns stay excluded.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 17:25:03 +07:00
Sergey KozyrenkoandClaude Opus 4.7 3a61d601e0 feat(frontend): extend Settings/Providers search to name and type
Mark `name` and `type` with `meta.searchable: true` and drop the
explicit `filterColumn="name"` so users can also narrow by provider
type — typing "anthropic" surfaces every provider of that type without
having to remember its display name. Updated the placeholder to match
the broader scope.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 17:23:31 +07:00
Sergey KozyrenkoandClaude Opus 4.7 8bdc10a41f feat(frontend): extend Templates search to title and text
Mark both accessor columns with `meta.searchable: true` and drop the
explicit `filterColumn="title"` so the picker offers both fields and
OR-matches across them. Searching the body text is the bigger win —
template titles are short, so the previous single-column behaviour
missed templates that referenced the same topic in their body.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 17:22:02 +07:00
Sergey KozyrenkoandClaude Opus 4.7 b740c4769e feat(frontend): extend Knowledges search to type, question, and preview
Mark `docType`, `question`, and `content` with `meta.searchable: true` so
the multi-column picker offers all three as candidates and OR-matches
across them. Drop the explicit `filterColumn="question"` so the
zero-config path (search across all `meta.searchable` columns) takes
over. The `Flags` column has no accessor and would need a custom string
extractor to participate — skipped for now.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 17:20:37 +07:00
Sergey KozyrenkoandClaude Opus 4.7 fd0edebf83 feat(frontend): extend Flows search to provider and terminals
Switch the `provider` and `terminals` columns from `accessorKey` to
`accessorFn` so the global filter receives plain strings — the provider
name and the joined list of terminal images — instead of the raw object
or array, which the predicate would just stringify to `[object Object]`.
The cell renderers keep reading `row.original` directly, so the visible
output is unchanged.

Dates stay excluded: substring matching against formatted timestamps
gives unpredictable hits (e.g. typing "3" suddenly matches every row
whose ISO contains 03) and date filtering belongs in a range picker.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 17:18:54 +07:00
Sergey KozyrenkoandClaude Opus 4.7 63d059834f perf(frontend): debounce DataTable filter input commits
Typing into the Flows search felt sluggish — Chrome reported INP 271 ms with input delay 253 ms, meaning every keystroke had to wait for the previous keystroke's render to complete before the event handler could even run. The chain on every keypress was: `setSearchParams` → react-router rerenders the whole route subtree → TanStack re-derives the global filter → 91 rows × 3 predicate calls → reconcile ~70 cells (Tooltip + Badge + ProviderIcon). At ~250 ms per cycle a fast typist queues several keystrokes behind a running render, so the input appeared to lag visibly.

Split the input value from the upstream commit: `DataTableFilter` now owns a local string state that updates synchronously on every keystroke, while a 150 ms debounce mirrors the value into `onQueryChange`. The router / TanStack cascade now fires once per typing pause instead of once per keystroke, and the input never has to wait its turn behind an in-flight reconciliation. After the change Chrome reports INP 43 ms with input delay 2 ms — typing feels instant.

Externally visible behaviour is unchanged: the X button clears immediately (no debounce on explicit clears), and external `query` resets (back button, programmatic clear) sync down through a guarded effect that ignores the value we just emitted ourselves. Vitest tests that previously asserted against the synchronous commit now wait for the debounced row-model update via `findBy*` / `waitFor`.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 16:50:20 +07:00
Sergey KozyrenkoandClaude Opus 4.7 38bc1deda9 refactor(frontend): inline getColumnId into data-table.tsx
`getColumnId` only has one consumer — `lib/` is for utilities shared across the codebase, not for a single-call helper. Move it next to `columnPickerLabel` as a module-level function inside `data-table.tsx`.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 16:18:42 +07:00
Sergey KozyrenkoandClaude Opus 4.7 847c873f01 refactor(frontend): composite globalFilter for DataTable multi-column search
The previous implementation drove `searchColumns` narrowing through a regenerated `columns` array with per-column `enableGlobalFilter`. It worked, but every selection change spawned a fresh set of `ColumnDef` objects via spread, invalidating TanStack's column-instance cache and conflicting with the upstream "memoise columns" guidance. The column-id resolver was also duplicated across two memos.

Replace it with TanStack's canonical mechanism for dynamic filters: pack the query and the active column set into a single `state.globalFilter` value of shape `{ columns, query }`, and consult both fields from a custom `globalFilterFn`. Any change to the query or to the active column set produces a new object reference, which is exactly what TanStack watches to re-run the filter pipeline — no imperative `setGlobalFilter` pokes, no closure-only narrowing that silently goes stale, and the parent's `ColumnDef` references reach `useReactTable` untouched so the column cache stays warm. The id resolver moves into a single `getColumnId` helper in `lib/column-utils.ts`.

A regression test exercises the exact sequence that exposed the bug fixed in d4c1b13 (type a query that matches via one column, then uncheck that column — the row must disappear without retyping). A second test pre-seeds `localStorage.searchColumns` with an id that the current columns no longer expose and asserts the new rebase effect prunes it on mount.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 16:13:16 +07:00
Sergey KozyrenkoandClaude Opus 4.7 d4c1b1342e fix(frontend): refilter DataTable when search columns change
The first implementation routed the active-column set through TanStack's
`getColumnCanGlobalFilter` predicate and tried to nudge the pipeline with
`table.setGlobalFilter((current) => current)`. TanStack treats that as a
no-op because the resolved value equals the current state, so the filter
pipeline never re-ran after the user narrowed the picker — the table kept
matching against the previous column set.

Bake the active set into per-column `enableGlobalFilter` via a memoised
`tanstackColumns` instead. TanStack sees a new columns reference whenever
the user's selection changes and refilters automatically, which is the
standard mechanism for this kind of dynamic filter and verified end-to-end
in the browser on the Flows list.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 15:15:11 +07:00
Sergey KozyrenkoandClaude Opus 4.7 8ccc2db3cb feat(frontend): enable multi-column search on Flows list
Mark `id`, `title`, and `status` as `meta.searchable: true` so the DataTable picks them up as candidates for the new global-filter search, and drop the explicit `filterColumn="title"` prop so users can search by uuid prefix or by typing a status keyword (e.g. "running"). `provider` and `terminals` stay excluded — both are non-string values that would only emit `[object Object]` matches.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 14:58:03 +07:00
Sergey KozyrenkoandClaude Opus 4.7 939b3cf763 feat(frontend): multi-column search in DataTable
The single-column `filterColumn` prop forced every page to pick one searchable field, which is awkward when a row has several useful text fields (e.g. flows have both `title` and the original `task`). Switch the engine to TanStack's `globalFilter` so the input can match across an OR-set of columns, and add a "Search in" dropdown next to "Columns" that lets the user narrow that set at runtime.

Opt-in stays explicit: `filterColumn: string` keeps the legacy single-column behaviour (no picker), `string[]` activates the picker on the listed columns, and an undefined prop falls back to columns marked with `meta.searchable: true`. The chosen subset persists alongside other table preferences in `table_4_<path>`.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 14:54:30 +07:00
Sergey Kozyrenko 3cc677712b fix: pnpm lock 2026-05-16 13:36:20 +07:00
Dmitry Ng c5a7df7438 feat(toolcalls): implement toolcall management features via REST API
- Added a new SQL migration to insert toolcall privileges into the privileges table.
- Introduced the `ToolcallService` for managing toolcall data, including retrieval of toolcalls and flow-specific toolcalls.
- Implemented API endpoints for fetching toolcalls and toolcall details, with appropriate permission checks.
- Enhanced Swagger documentation to include new toolcall endpoints and their specifications.
- Created a new model for toolcalls, defining their structure and validation rules.
- Added error handling for invalid toolcall requests and not found scenarios.
2026-05-16 13:24:29 +07:00
Dmitry Ng ec9d8eb129 feat(docker): add new provider configurations for Qwen 3.6 35B models
- Included two new provider YAML files for Qwen 3.6 35B models: `vllm-qwen3.6-35b-a3b-fp8-no-think.provider.yml` and `vllm-qwen3.6-35b-a3b-fp8.provider.yml`.
- Updated Dockerfile to copy the new configuration files into the appropriate directory.
2026-05-16 13:24:29 +07:00
Sergey KozyrenkoandClaude Opus 4.7 7dae4be61d refactor(frontend): headless controller for DetailNavigation
Detail pages duplicated DetailNavigationToolbar's internal navigation
state (prev/next, sheet open, position label) because mobile chrome lives
inside a DropdownMenuItem and could not reuse the toolbar component.
Promote useDetailNavigation to return a full DetailNavigationController,
have the leaf components (Buttons / Sheet / Toolbar) read from it, and
drop the ~40 LOC mobile mirror block on each of three pages.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 13:11:35 +07:00
Sergey KozyrenkoandClaude Opus 4.7 8dbee4fb64 style(frontend): use Badge for sheet header counters
Plain spans with `text-muted-foreground text-sm tabular-nums` rendered as
loose text floating in the header — visually weak and easy to miss. Wrap
each counter in a `<Badge variant="secondary">` so it reads as a discrete
pill (matches the rest of the design language, e.g. doc-type badges in
the knowledges list).

Touches three locations that all share the icon + title + counter
header pattern:
- `pages/templates/template.tsx`: Preset-templates mobile Sheet header
- `pages/templates/template.tsx`: Preset-templates desktop aside header
- `components/shared/detail-navigation/detail-navigation-sheet.tsx`:
  detail-navigation sheet header (Flows / Templates / Knowledges count)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 10:50:39 +07:00
Sergey KozyrenkoandClaude Opus 4.7 8fc8f63a75 refactor(frontend): unify Preset-templates panel with DetailNavigationSheet
The Preset-templates side panel on `/templates/:id` now mirrors the
header + scrollable body structure of `<DetailNavigationSheet>`, so the
two Sheet surfaces on this page (preset picker and Templates list) look
and behave the same: bordered header row with icon + title + total
counter on the right, scrollable body below.

- Mobile `<Sheet>` and desktop `<aside>` share an identical header
  (`border-b p-4` with `FileText`, "Preset templates", and a
  `tabular-nums` counter). The mobile variant uses `<SheetTitle>` so
  screen readers announce it; the desktop variant uses an `<h3>` styled
  to match. The previous `sr-only` SheetTitle is gone.
- Body switches from `<ScrollArea flex-1>` to a plain
  `<div className="min-w-0 flex-1 overflow-y-auto">`. Radix `ScrollArea`'s
  Viewport wraps children in a `display: table` div whose width grows to
  intrinsic content size, defeating `w-full min-w-0` on the inner card
  flex rows — the chevron buttons were rendering off-screen on a 390px
  viewport because of it. Plain `overflow-y-auto` respects the parent
  width and the chevrons land inside the Sheet.
- Each preset Card and its inner flex row pick up `w-full min-w-0`,
  the title `<span>` picks up `min-w-0`, so the
  `flex-1 min-w-0` title button actually shrinks and `truncate` kicks in
  on long preset names. Asides also gain `gap-2` between cards so they
  read as discrete items instead of a single bordered run.
- Drop the now-unused `ScrollArea` import.
- `components/ui/scroll-area.tsx`: collapse the `<Viewport>` JSX onto
  one line and replace `h-full w-full` with `size-full` — a prettier
  cleanup that landed alongside the rewrite.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 10:39:46 +07:00
Sergey KozyrenkoandClaude Opus 4.7 c2d368654b refactor(frontend): unify Preset-templates panel with DetailNavigationSheet
Both Sheets on the template detail page now follow the same skeleton:

  SheetContent (flex flex-col gap-0 p-0)
    SheetHeader (border-b p-4)
      SheetTitle (flex items-center gap-2 pr-8 text-base)
        <icon> <label> <counter on ml-auto>
    ScrollArea (flex-1)
      <list>

This mirrors `components/shared/detail-navigation/detail-navigation-sheet.tsx`,
so the navigation sheet (Templates 1/8 selector) and the Preset-templates
side panel look and behave the same way on every viewport — same width
cap (`max-w-sm`), same bordered header, same scroll behaviour via Radix
`ScrollArea` instead of plain `overflow-y-auto`.

The desktop `<aside>` variant gets the same skeleton too — wrapped in a
`flex flex-col` so the header strip stays pinned while the preset list
scrolls in the `ScrollArea` below. The pinned header swaps the muted
`<h3>` for the same icon + label + counter line as the mobile sheet, so
the platforms read the same.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 09:40:33 +07:00
Sergey KozyrenkoandClaude Opus 4.7 35adf05ab9 refactor(frontend): visible Preset-templates title per platform
Split the panel heading so each form factor gets the title styled for
its container:

- Mobile (`<Sheet>`): use a visible `<SheetTitle>` (no more `sr-only`)
  in the sheet's own area, styled at `text-base` to match other Radix
  dialog headers in the app.
- Desktop (inline `<aside>`): keep the existing muted `<h3>` outside
  the scroll area so it stays pinned while the preset list scrolls.

Lift the title out of `asideContent` so it isn't rendered twice on
desktop; trim the wrapper's `p-4` to `px-4 pb-4` since the title
provides the top spacing in both layouts. Drop `p-2` on `SheetContent`
in favour of `p-0` so the new title can own its own padding.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 21:01:44 +07:00
Sergey KozyrenkoandClaude Opus 4.7 a6f386c5d7 fix(frontend): satisfy Radix dialog a11y requirements on sheets
Radix DialogContent (which `SheetContent` extends) warns when neither a
DialogTitle nor an explicit opt-out is provided, and again when no
Description / `aria-describedby={undefined}` is set. Two places hit
this:

- `pages/templates/template.tsx` preset-templates panel: the visible
  `<h3>` lives inside `asideContent` and is reused by the desktop
  non-Sheet variant, so add an `sr-only` `<SheetTitle>` inside
  `<SheetContent>` for screen readers. Pair it with an explicit
  `aria-describedby={undefined}` — the panel is a flat list of presets
  with no descriptive sub-text, so opting out is honest.

- `components/shared/detail-navigation/detail-navigation-sheet.tsx`:
  already had a `<SheetTitle>` (Flows / Templates / Knowledges), but the
  Description warning was still firing. Add the same
  `aria-describedby={undefined}` opt-out on `<SheetContent>` — the
  listbox of items is self-describing.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 20:42:42 +07:00
Sergey KozyrenkoandClaude Opus 4.7 c196e55d5d feat(frontend): mobile-friendly headers across detail and list pages
Roll the truncate-chain + mobile-navigation pattern introduced for the
/flows/:id page out to every other detail and list page so a long title
never pushes the action buttons off-screen on a ~390px viewport.

Detail pages
- `templates/template.tsx` and `features/knowledges/knowledge-header.tsx`
  now mirror `pages/flows/flow.tsx`: left container becomes
  `flex min-w-0 flex-1` with `shrink-0` on the SidebarTrigger/Separator,
  Breadcrumb/BreadcrumbList/BreadcrumbItem get the `min-w-0` /
  `flex-nowrap` chain, BreadcrumbPage gets `truncate`, the right action
  area becomes `flex shrink-0`. InlineEditInput in both pages now uses
  `w-64 min-w-0 max-w-full flex-1` so the rename input shrinks with the
  parent instead of forcing it to ≥256px.
- On `isMobile`, the DetailNavigationToolbar is hidden and re-surfaced
  inside the existing actions dropdown as a single row matching
  `pages/flows/flow.tsx` (icon + label + Prev/Position/Next button
  group with shared borders; middle button doubles as the sheet
  trigger). DetailNavigationSheet is mounted separately, controlled by
  `isMobileNavSheetOpen` state.

List pages
- `pages/flows/flows.tsx`, `pages/knowledges/knowledges.tsx`,
  `pages/templates/templates.tsx`, `pages/resources/resources.tsx`,
  and `pages/flows/new-flow.tsx` get the same header truncate chain
  preventively — most page titles are short, but the structure stays
  consistent across pages and protects against future longer labels.
- `pages/templates/templates.tsx` Title cell gains `max-w-[380px]
  truncate` (matched to the existing Text-cell cap) so a long template
  title can't blow up the row.
- Settings pages (`settings-providers.tsx`, `settings-api-tokens.tsx`)
  don't render a breadcrumb header — their `SettingsLayout` already
  shows the sidebar trigger — but their inline header rows still leaked
  on narrow screens. Add `min-w-0 flex-1 truncate` to the description
  text and `shrink-0` to the Create button so the right-edge CTA stays
  visible while the left text degrades gracefully.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 19:21:25 +07:00
Sergey KozyrenkoandClaude Opus 4.7 7a2f882cea feat(frontend): mobile-friendly flow detail header and unified picker
Make the /flows/:id page usable on a 390px viewport and replace the two
parallel template/attachment dropdowns with one trigger that works the
same way on every screen.

Header
- Breadcrumb chain (`flex min-w-0 flex-1` on the left container, `flex
  shrink-0` on the right one, `min-w-0 flex-nowrap` on BreadcrumbList,
  `min-w-0 gap-2` on BreadcrumbItem, `truncate` on BreadcrumbPage) so the
  flow title can shrink past its intrinsic width instead of pushing the
  action buttons off-screen.
- InlineEditInput: `w-64 min-w-0 max-w-full flex-1` — keeps the 256px
  default on desktop but lets the rename input collapse to whatever space
  is left on narrow viewports.
- On `isMobile`, the desktop DetailNavigationToolbar and the favorite Star
  button are hidden and re-surfaced inside the Flow-actions dropdown:
  a single row matching the theme-menu pattern in `main-sidebar.tsx`
  (icon + label + Prev/Position/Next button group sharing borders), plus
  a separate "Add/Remove favorites" item. The position button doubles as
  the sheet trigger, so the mobile navigation has the same affordances as
  the desktop toolbar.

Flow form
- Templates and Resources (formerly "Attachments") share one Ellipsis
  trigger placed next to the Send button on every viewport — the two
  separate FileText/Paperclip dropdowns are gone.
- Inside the dropdown, Radix `<Tabs>` switches between picker panels
  rendered above the tab strip; the strip lives at the bottom so it
  lands next to the trigger. The dropdown opens upward (`side="top"`
  with `align="end"`) and has a fixed `w-72` so it stays inside the
  viewport on phone-width screens.
- Tab switch is deferred one tick (`setTimeout(..., 0)`) before
  mutating `pickerTab`. Radix DropdownMenuItem listens to `pointerup`
  directly, so a synchronous swap let the pointerup that ended the tab
  click land on the freshly mounted "Upload files" item in the Resources
  panel and fired its `onSelect`.
- Send button gets `shrink-0`; combined trigger picks up `ml-auto` so
  Send/trigger stay glued to the right edge without two `ml-auto` items
  fighting over leftover space.

Detail navigation primitives
- Expose `DetailNavigationSheet` and `useNavigation` from the package
  index so a page can compose its own mobile UI without re-implementing
  the filtered-subset / Prev-Next algorithm.
- `DetailNavigationSheet`: add `pr-8` to `SheetTitle` so the trailing
  total counter (e.g. "311") stops sitting underneath the absolutely
  positioned close button on the right edge.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 19:03:26 +07:00
Sergey Kozyrenko 829271e7e4 refactor(frontend): inline useControllable into autocomplete.tsx
The hook had exactly one consumer (components/ui/autocomplete.tsx) and
was a tiny ~20-line Radix-style controlled/uncontrolled state mirror.
Move it inline as a private helper next to the component that uses it,
so a future reader doesn't have to chase a one-call hook through hooks/.
useLatestRef stays in @/hooks/ — it's genuinely cross-cutting.
2026-05-15 12:41:56 +07:00
Sergey Kozyrenko e041b11cef refactor(frontend): move table-filter into detail-navigation/ as text-filter
The createTextMatcher helper has only one production consumer
(detail-navigation/use-navigation.ts) and the original 'table-filter'
name implied a tie to <DataTable>'s column filter that the codebase
never actually wired (DataTable still uses TanStack's built-in
'includesString'). Move the file into detail-navigation/ as a private
text-filter module so the matcher lives next to its only caller and the
name reflects what it does (text matching) rather than aspirational
table-filter alignment.

If the table column filter is ever switched to use createTextMatcher
for diacritic folding, the import would simply move back up — but
that's a separate behaviour change, not a naming concern.
2026-05-15 12:34:42 +07:00
Sergey Kozyrenko 33dba9dbf4 refactor(frontend): inline cycleColumnSort into data-table.tsx
Move the lone cycleColumnSort function from lib/table-sort.ts straight
into components/ui/data-table.tsx — it was a one-consumer helper used
only by DataTableColumnHeader, so co-locating it removes the
cross-folder hop without changing behaviour. Exported alongside
DataTableColumnHeader for parity with the shadcn convention and so a
future custom header can reuse the cycle. The four unit tests move
into data-table.test.tsx as a sibling describe block; lib/table-sort
is gone.
2026-05-15 12:22:32 +07:00
Sergey Kozyrenko 7a6d50a1c1 refactor(frontend): relocate report module to lib/report/ folder
Move features/report/ → lib/report/ — the module is mostly pure
utilities (generateReport, generateFileName, copyToClipboard,
downloadTextFile) plus an internally lazy-loaded React-pdf component,
not a feature with its own domain/provider/queries. lib/ is the
honest home; the folder grouping addresses the original audit
complaint of a 658-line .tsx loose in lib/. Consumers swap
'@/features/report' for '@/lib/report'.
2026-05-15 12:06:55 +07:00
Sergey Kozyrenko 31c894ee65 refactor(frontend): move report module from lib/ to features/report/
The PDF generator (~658 lines, lazy-loaded) and its public-API wrapper
report.ts are functionally one module. They now live together in
features/report/ instead of being scattered in lib/, which was a poor
home for a 658-line React-pdf component anyway. The lazy-import path
inside report.ts stays relative (./report-pdf), and the four consumers
(flow.tsx, flow-files.tsx, flow-report.tsx, resources.tsx) just swap
'@/lib/report' for '@/features/report'.

Note: copyToClipboard and downloadTextFile come along for the ride —
they're generic helpers used in non-report contexts too. Splitting them
out cleanly into lib/ would be worth a follow-up if you want stricter
domain boundaries.
2026-05-15 11:52:02 +07:00
Sergey Kozyrenko f46de8d374 refactor(frontend): consolidate inline-edit module and drop the rename framing
Group inline-rename-input.tsx and use-inline-edit-title.ts into a new
components/shared/inline-edit/ folder, the same pattern we applied to
detail-navigation, overwrite, and unsaved-changes. Rename to drop the
misleading "rename" framing — the API has nothing rename-specific
(autoFocus, busy, defaultValue, onCancel, onSave) and the same component
is used for quick-create and inline-edit flows too:
  InlineRenameInput → InlineEditInput
  useInlineEditTitle → useInlineEdit
  INLINE_RENAME_MAX_LENGTH → inlined as default `maxLength = 200`
2026-05-15 11:41:52 +07:00
Sergey Kozyrenko c75335eac9 refactor(frontend): inline DataTableColumnHeader into data-table.tsx
Fold the standalone SortableColumnHeader into components/ui/data-table.tsx
and rename it to DataTableColumnHeader (the canonical name from
ui.shadcn.com/docs/components/data-table). The two pieces only ever
shipped together — every consumer paired SortableColumnHeader with
DataTable inside the TanStack column definition. Keeping data-table as
a single file matches the convention already used elsewhere in
components/ui/. Also rename the prop label → title to match the upstream
shadcn signature; touches 20 JSX usages across 5 list pages.
2026-05-15 10:46:46 +07:00
Sergey Kozyrenko d8e84d0df7 refactor(frontend): rename useOverwriteAction to useOverwrite
Inside `components/shared/overwrite/` the folder name already supplies
context, so the `-action` suffix is redundant — same principle that
turned overwrite-confirm-dialog into overwrite-dialog. Rename file
use-overwrite-action.ts → use-overwrite.ts, export useOverwriteAction
→ useOverwrite, and the internal UseOverwriteAction* prop/result types
to match. The shape lines up with the project's verb-noun action-hook
convention (useResourcesCopy, useResourcesMove).
2026-05-15 10:09:48 +07:00
Sergey Kozyrenko 90eba577b2 refactor(frontend): drop verbose suffixes from overwrite module names
Within `components/shared/overwrite/` the folder name already supplies
context, so the file/component names don't need to repeat it. Rename
overwrite-confirm-dialog → overwrite-dialog and overwrite-cta-buttons →
overwrite-buttons (and matching exports OverwriteConfirmDialog →
OverwriteDialog, OverwriteCtaButtons → OverwriteButtons) so the module
matches the file-and-export naming convention used by detail-navigation.
2026-05-15 10:03:49 +07:00
Sergey Kozyrenko 4d2e4ff5bf refactor(frontend): consolidate overwrite and unsaved-changes into module folders
Group the overwrite trio (OverwriteConfirmDialog, OverwriteCtaButtons,
useOverwriteAction) into components/shared/overwrite/ — they cross-import
the OverwriteConflict type and 12 consumers always pull from the same
logical module. Same pattern for the unsaved-changes pair: move the
dialog from components/shared/ and the UI-agnostic guard hook from
hooks/ into components/shared/unsaved-changes/. Each folder ships an
index.ts so consumers reach the module through one import path.
2026-05-15 09:50:08 +07:00
Sergey Kozyrenko ef0dbcf0e2 refactor(frontend): consolidate detail-navigation into a single module folder
Move the Prev/Position/Next toolbar and its supporting hooks from scattered
locations under components/shared/ and hooks/ into a single
components/shared/detail-navigation/ folder. Rename ListNavigation* →
DetailNavigation* (toolbar/buttons/sheet) so the names reflect what they
actually do — sibling navigation between detail pages, not navigation
within a list. The internal algorithmic hook drops its now-redundant
prefix (useFilteredListNavigation → useNavigation, computeListNavigation →
computeNavigation), and useDetailNavigation moves alongside the toolbar
since it's the public composition layer that produces toolbarProps.
2026-05-15 09:33:12 +07:00
Sergey KozyrenkoandClaude Opus 4.7 21d61b37ee perf(frontend): lazy-load @react-pdf/renderer and drop dead html2pdf.js
- @react-pdf/renderer (~1.5 MB) moved to an async chunk. lib/report.ts
  used to statically re-export PDF helpers from ./report-pdf, which
  pulled the entire PDF library into every page that imports
  lib/report (flow.tsx, flow-report.tsx). The re-exports are now
  async wrappers using `await import('./report-pdf')`, so the
  library loads only when the user actually triggers a PDF export.
  Initial JS for /flows/:id/report drops from ~2.0 MB to ~500 KB.
- Drop html2pdf.js: zero imports anywhere in the source, but it was
  declared as a dependency and reserved a (now-empty) manual chunk in
  vite.config.ts. Removing it also drops 22 transitive packages from
  the lockfile.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 08:38:07 +07:00
Sergey KozyrenkoandClaude Opus 4.7 420944946e style(frontend): apply prettier formatting
Whitespace, line wrapping and Tailwind class ordering only — no code
changes. Brings 11 files in line with the prettier + tailwindcss
plugin config.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 06:55:28 +07:00
Sergey KozyrenkoandClaude Opus 4.7 abe45e33c9 chore(frontend): rename Cyrillic clipboard.ts and remove dead code
- src/lib/сlipboard.ts → clipboard.ts: the filename used a Cyrillic 'с'
  (U+0441) instead of Latin 'c', which made the path silently
  unmatchable by anyone typing the import with a Latin letter. Update
  the 4 importers in features/flows.
- Delete unreachable settings-mcp-server(s).tsx (~1.3k lines): no
  routes registered in app.tsx and nothing imports them. Remove the
  matching dead branches and commented menu entry from
  settings-layout.tsx.
- Drop unused dev deps simple-git-hooks and lint-staged: no config in
  the repo, not used by CI or Docker, hooks were never wired up. Also
  remove simple-git-hooks from pnpm.onlyBuiltDependencies.
- Drop unused tsconfig path aliases: @/ui/*, @env (env.ts doesn't even
  exist), and @pkg. Only @/* remains.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 06:53:53 +07:00
Dmitry Ng 161afb8b59 fix(cast,providers): replace invalid tool call JSON arguments with empty object
When an LLM emits a truncated or malformed arguments field (e.g. "{") instead of valid JSON, downstream consumers such as LiteLLM reject the entire request with a 400 Bad Request, causing the chain to degrade into an infinite retry loop.

- SanitizeToolCallArguments now falls back to "{}" after control-char escaping if the result is still not valid JSON, fixing already-stored chains on restore
- callWithRetries logs a warning and substitutes "{}" at the moment the bad arguments arrive from the LLM, preventing them from ever reaching the database
- Added test cases for truncated JSON, partial objects, and empty strings
2026-05-15 01:03:04 +03:00
Sergey KozyrenkoandClaude Opus 4.7 692d91cffa fix(frontend): sync URL on pageSize change, label knowledge columns
- DataTable: route handlePageSizeChange through handlePaginationChange so
  onPageChange fires when picking "All" on a high page drops pageIndex to 0.
  Without this, the URL kept a stale ?page=N while the display correctly
  clamped to "Page 1 of 1".
- DataTable: reconcile effect in controlled mode now compares
  externalPageIndex (the URL source of truth) against safePageIndex instead
  of the internal mirror, which can drop to 0 via handlePageSizeChange and
  hide the URL mismatch from the previous comparison.
- knowledges: add meta.columnMenuLabel to docType and question columns so
  the Columns dropdown reads "Type" / "Question" — same labels as the
  table headers — aligning with the Flags/Preview entries.
- data-table.test: cover both pathways — out-of-range controlled pageIndex
  on mount, and pageSize=All from page 2.
- vitest.setup: polyfill hasPointerCapture / setPointerCapture /
  releasePointerCapture so Radix Select interactions don't crash in jsdom.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 00:46:17 +07:00
Sergey KozyrenkoandClaude Opus 4.7 a8a7431613 fix(frontend): clamp page index, sync settings filters, harden inline rename
- DataTable: derive a clamped `safePageIndex` from URL + `pageCount`; use it
  for display + reconcile URL via effect when raw differs. Fixes "Page 999
  of 31" and "Showing 9981–307 of 307" when a hand-typed URL, a filter
  narrowing the dataset, or a pageSize=All bump leaves the URL out of range.
- DataTable: only persist `pageSize` to storage when it differs from
  `initialPageSize` so a fresh mount no longer seeds `{ pageSize: 10 }` via
  StrictMode dev double-invoke.
- useTableQueryFilter: storage replay no longer drops `?page=` — that flag
  belongs to user-driven `setFilter`, not to restoration of prior state.
  Out-of-range pages after replay are now handled by the clamp above.
- Settings/Providers + Settings/API tokens: pass `filterValue` / `onFilterChange`
  from `useTableQueryFilter` so the filter input is URL- and storage-synced,
  matching the pattern used by flows, knowledges, templates, resources.
- InlineRenameInput: export `INLINE_RENAME_MAX_LENGTH = 200` and apply it as
  the native `maxLength` attribute. UX guard against paste-bombs that would
  break truncation; `defaultValue` is untouched so existing long records
  remain editable.
- knowledges: render a "Flags" header for the badges column instead of `null`,
  aligning with `meta.columnMenuLabel` and other column headers.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 23:48:15 +07:00
Sergey KozyrenkoandCursor 5319d1cb65 feat(frontend): unify list tables with URL sync, navigation, and Vitest
- Add table-state, url-params, table-filter, view-options-storage utilities
- Add hooks: pagination, table query filter, filtered list/detail navigation, inline title edit, page storage keys
- Add shared list navigation toolbar/sheet/buttons, sortable headers, inline rename input
- Refactor DataTable; integrate flows/knowledges/templates/resources/settings pages
- Remove adaptive column visibility and legacy table-storage
- Configure Vitest with tests for hooks, lib, and components

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-14 21:36:14 +07:00
Dmitry Ng 403a84b0a6 feat(toolcalls): implement toolcall management features via REST API
- Added a new SQL migration to insert toolcall privileges into the privileges table.
- Introduced the `ToolcallService` for managing toolcall data, including retrieval of toolcalls and flow-specific toolcalls.
- Implemented API endpoints for fetching toolcalls and toolcall details, with appropriate permission checks.
- Enhanced Swagger documentation to include new toolcall endpoints and their specifications.
- Created a new model for toolcalls, defining their structure and validation rules.
- Added error handling for invalid toolcall requests and not found scenarios.
2026-05-14 14:12:37 +03:00
Dmitry Ng bff332b647 feat(docker): add new provider configurations for Qwen 3.6 35B models
- Included two new provider YAML files for Qwen 3.6 35B models: `vllm-qwen3.6-35b-a3b-fp8-no-think.provider.yml` and `vllm-qwen3.6-35b-a3b-fp8.provider.yml`.
- Updated Dockerfile to copy the new configuration files into the appropriate directory.
2026-05-14 14:11:27 +03:00
Sergey KozyrenkoandCursor fff79b3979 feat(knowledges): inline rename and delete actions in knowledge header and list
Adds an actions dropdown to the knowledge detail header with inline
rename (double-click or "Rename") and delete with a confirmation dialog.
The form keeps any unsaved edits when an external rename refreshes the
cache (`keepDirtyValues` + reactive `values`), and `onBeforeNavigateAway`
suppresses the unsaved-changes guard right after a successful delete.

The knowledges listing gets the same: a "Rename" item in the row
dropdown and context menu opens an in-row editor, and clicking the row
no longer navigates while a rename is in progress.

Drops the redundant `knowledgeName` prop that was threaded through
`KnowledgeForm`/`KnowledgeLayout`/`KnowledgeHeader` — the header now owns
the title and computes it locally from `knowledge.question`.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-13 20:52:51 +07:00
Sergey KozyrenkoandCursor bce4d79069 feat(templates): inline rename and delete actions in template header and list
Adds an actions dropdown to the template detail header with inline rename
(double-click or "Rename") and delete with a confirmation dialog. The
listing learns the same: a "Rename" item in the row dropdown and context
menu opens an in-row editor, and clicking the row no longer navigates while
a rename is in progress.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-13 20:52:42 +07:00
Sergey KozyrenkoandCursor 465ea406f4 feat(flows): inline rename and finish/delete actions in flow header
Brings the flow detail page in line with the actions row already available
on the listing: double-click or pick "Rename" from the new actions menu to
edit the title in place, "Finish" to gracefully stop a running flow, and
"Delete" with a confirmation dialog. The listing keeps a `PencilLine`
icon for "Rename" so the action looks consistent across surfaces.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-13 20:52:35 +07:00
Sergey KozyrenkoandCursor b97a0c10a5 feat(header): collapse page header buttons to icons on mobile
Add `HeaderButton` component that renders icon + label on >=768px and
collapses to an icon-only square on narrower viewports, with the
`aria-label` auto-derived from the label so the mobile state stays
accessible. Apply it to the action buttons in Flows, Flow, Knowledges,
Templates, Resources and the Knowledge save button so mobile page
headers stop overflowing.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-13 14:18:59 +07:00
Dmitry Ng 2f4da118e0 feat(anonymization): implement anonymizeText mutation and associated service
- Added a new SQL migration to insert the 'anonymize.call' privilege into the privileges table.
- Introduced the `anonymizeText` mutation in the GraphQL schema, allowing users to anonymize sensitive text.
- Implemented the `AnonymizerService` to handle text anonymization requests via a REST API endpoint.
- Updated the GraphQL resolver to integrate the new mutation and ensure proper permission checks.
- Enhanced documentation with Swagger and OpenAPI specifications for the new endpoint.
- Added error handling for invalid requests and unavailable anonymizer configurations.
2026-05-12 21:47:40 +03:00
Dmitry Ng fbf917a18a fix(aslog, msglog): remove message length truncation logic
Eliminate the message length truncation from both `putMsg` methods in `aslog.go` and `msglog.go`. This change simplifies the message handling process by allowing messages to be processed without arbitrary length restrictions.
2026-05-12 21:37:16 +03:00
Dmitry Ng 0f0a7bd2d0 fix(database/knowledge): replace SimilaritySearch with direct SQLC vector queries
- Fix empty ID bug: langchaingo SimilaritySearch discarded document UUIDs; new SearchKnowledgeDocuments/SearchUserKnowledgeDocuments return them directly
- Remove unsafe fmt.Sprintf SQL filter interpolation, use parameterised queries
- Exclude memory documents from search results at SQL level
- Add FlowID support to passesSearchFilter
- Convert all $N positional params to sqlc.arg(name) across knowledge queries
- Update tests: replace TestBuildSearchFilters with TestPassesSearchFilter, add TestSearchDocuments and TestSearchUserDocuments
2026-05-12 20:47:46 +03:00
Sergey KozyrenkoandCursor ad3b5062e1 fix(autocomplete): keep cmdk a11y attributes in sync with popover state
cmdk renders a sr-only `<label cmdk-label for={cmdkUseId}>` inside
`<Command>` and points its `for` at a useId it generates for *its own*
input. Our visible input gets its id from `FormControl`'s Radix Slot
instead, so the two ids never line up and Chrome flags "Incorrect use
of `<label for=FORM_ELEMENT>`". Re-point the `for` at the real input id
in a `useLayoutEffect` so the HTML-level association is valid — cmdk
already wires `aria-labelledby` to the same element through Slot, so
screen-reader behaviour is unchanged.

cmdk also hard-codes `aria-expanded={true}` on its combobox input, so
the attribute lies whenever the popover is closed (after Enter,
Escape, outside-click). Pass `aria-expanded={open}` on the inner
`<Input>` — Radix Slot merges child props over slot props for
non-handler attributes, so our value wins and keeps the ARIA state in
sync with the actual popover state.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 23:11:05 +07:00
Sergey KozyrenkoandCursor ba63992e88 feat(autocomplete): substring filter and code-language suggestions
Default the autocomplete filter to a case-insensitive substring match
instead of cmdk's fuzzy `command-score`: in plain autocomplete usage,
returning items whose characters merely appear in order is surprising.
Consumers can still opt back into fuzzy matching via the `filter` prop.

Extract `useControllable` into `@/hooks/use-controllable` (now backed by
`useLatestRef`) so other components can reuse Radix-style controllable
state without redefining it inline.

Replace the plain `<Input>` in the knowledge form's "Code language"
field with `<Autocomplete>` surfacing a curated list of 30 common
languages, while still accepting any free-text value the backend may
expect.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 23:10:45 +07:00
Sergey KozyrenkoandCursor 8da0312e9d feat(knowledge): allow docType edit, partial UPDATE, and field-clear on save
Backend now accepts `docType` on `UpdateKnowledgeDocumentInput`, so the
edit form was reworked end-to-end:

- Form schema mirrors REST length limits (content 65536, question 2048,
  description 1000, codeLang 100) — GraphQL itself doesn't enforce them.
- `docType` is editable on existing docs, not just on create. Switching
  it clears stale subtype values (`answerType`/`guideType`/`codeLang`)
  through `setValue` in the Select's `onValueChange`, not via effect, so
  freshly loaded documents keep their persisted subtype on first render.
- UPDATE is now a partial payload built from RHF's `dirtyFields`:
  untouched optional fields are omitted, cleared fields go out as `""`
  so the backend wipes them (previously `'' → undefined` silently
  swallowed clears, leaving stale values on the server).
- `KnowledgesProvider` drops the duplicate `Knowledge` interface and
  uses the GraphQL fragment directly; no more hand-rolled field mapping.
- Both submit paths (form button and "Save & Leave" dialog) parse
  values through `formSchema.safeParse` so trim/normalisation is
  identical regardless of code path.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 11:36:11 +07:00
Sergey KozyrenkoandCursor 616b864b17 style: prettier reformat in unrelated utilities
No behavior change.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 09:49:22 +07:00
Sergey KozyrenkoandCursor 8b1cf00ba1 refactor(knowledge): split page into form, layout, header and field components
Extract the previously monolithic knowledge page into focused modules under
features/knowledges/ to match the resources/flows convention:

- knowledge-form: schema, helpers and RHF wiring
- knowledge-form-layout: desktop split / mobile stacked layouts
- knowledge-form-controls: meta fields and content (markdown) field
- knowledge-header / knowledge-layout: shared header and loading/not-found shell

Promote the unsaved-changes machinery to reusable primitives
(use-unsaved-changes-guard hook + unsaved-changes-dialog) so other forms
can adopt the same flow.

Tighten markdown-editor for knowledge content authoring: disable
transformPastedText (a leading "- " or "1. " no longer silently turns a
plain paste into a list/blockquote) and reserve the editor's bounding box
during tiptap initialization to avoid layout jumps on mount.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 09:49:22 +07:00
Sergey KozyrenkoandCursor 4a1f5ba527 fix(markdown-editor): keep RHF clean and undo stack empty on mount
On the knowledge edit page the Save button was enabled immediately
after load — and the toolbar's Undo button along with it — even though
the user had not edited anything. Two distinct mount-time noises were
leaking into RHF and the UndoRedo plugin.

1. tiptap-markdown re-serializes the initial content during view
   construction (whitespace around fenced code blocks, hard-break
   markers, etc.) and fires onUpdate with the normalized markdown.
   Forwarding this echo to field.onChange flips RHF's isDirty.
   Defer onUpdate forwarding via isInitializedRef set inside onCreate
   and use the editor's own serialized markdown as the echo baseline.

2. Construction-time transactions from trailingNode and the mount-time
   setContent land in the UndoRedo plugin's event stack. PM's
   history() uses a singleton PluginKey, so state.reconfigure({plugins})
   carries the old state over; reset the stack by rebuilding the entire
   EditorState instead, then dispatch an empty addToHistory:false
   transaction to wake tiptap-react's subscription so the toolbar
   re-renders. Only reset on initial mount and on external value sync
   so user edits are not erased.

Also dedupe knowledge.tsx Create/Update payload projection into a
shared formValuesToBasePayload helper and rename its parameter from
v to values per code-style conventions.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 09:49:21 +07:00
Dmitry Ng ca1dfa138c feat(knowledge): enhance document update functionality with docType handling
- Introduced a new `docType` field in the `UpdateKnowledgeDocumentInput` to manage document type changes.
- Updated the `doUpdate` method to clear subtype fields (GuideType, AnswerType, CodeLang) when the document type changes.
- Added comprehensive tests for various document type transitions to ensure correct behavior and state preservation.
- Updated GraphQL schema and generated models to accommodate the new `docType` field.
2026-05-11 10:29:13 +03:00
Sergey KozyrenkoandCursor 4675cf8e15 feat(autocomplete): add free-text autocomplete primitive, wire to container path input
Build a small Autocomplete family on top of cmdk and Radix Popover so the
Pull dialog's container path field gets fuzzy-filtered suggestions from
paths the user has already touched (cached files, current listing,
ancestors), while still letting them type arbitrary paths. Renders inline
(no portal) to survive Radix Dialog's body scroll-lock, and delegates the
DOM input to the project Input component via Radix Slot (asChild) so cmdk
keeps the value sync and combobox ARIA without duplicating styles.

A single useCommandState selector returning a primitive hasActiveMatch
boolean keeps the per-keystroke re-render count down to one.

Drive-by: pluralize the "Upload file" dropdown item in FlowForm to "Upload
files" to match the input's multiple attribute.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-09 23:05:59 +07:00
Sergey KozyrenkoandCursor d97b355ce2 feat(file-manager): expand/collapse all toggle in header
Adds a chevron toggle next to the "Name" header that flips every
directory in the full tree (filter-independent). Uses the existing
overrides map via a new `setExpansion(paths, isExpanded)` bulk helper
on `useFileManagerExpansion`, so a single gesture wins over the
auto-expand-on-search behavior. Skeleton header stays in lock-step.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-09 21:25:42 +07:00
Sergey KozyrenkoandCursor 5fa3d65fe3 refactor(file-manager): replace mutating addAllToSet/removeAllFromSet with pure addAll/removeAll
The old helpers mutated the Set passed in, but the type signature
(`Set<string>`) did not communicate that — only the JSDoc did. Every
existing caller already cloned `prev` before calling, so the migration
to pure `(prev, paths) => new Set` variants is zero-cost and removes a
foot-gun. `toggleSubtreeOnSet` and `computeRowClickSelection` now
compose the pure helpers directly instead of clone-then-mutate.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-09 20:52:15 +07:00
Sergey KozyrenkoandCursor 08fe658925 docs(knowledge): explain skipNextBlockRef cycle in KnowledgeForm
Document the ref-based loop between performSave, onSaveFromDialog, and
useUnsavedChangesGuard so a cold reader can answer "why is the ref
declared after performSave?" without re-tracing the whole component.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-09 20:49:37 +07:00
Sergey KozyrenkoandCursor 4055a981cb test(file-manager): pin compareSizes behavior with directories across folders-first toggle
Lock in the contract that directories collapse to size 0 in compareSizes.
Invisible while folders-first is on, but user-visible (and easy to regress)
once the Resources page lets the user disable that partition.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-09 20:49:05 +07:00
Sergey KozyrenkoandCursor 7125834e7e refactor(frontend): data-router migration, FileManager sorting, shared utilities
App shell:
- Switch from BrowserRouter+Routes to createBrowserRouter so pages can use
  data-router-only APIs (useBlocker). Route definitions live at module scope.

FileManager:
- Sortable headers (name/size/modified) with three-state cycle, optional
  per-column sortability, controlled / uncontrolled+localStorage modes via
  the new useFileManagerSorting hook.
- isFoldersFirst toggle and recursive sortFileManagerTree pure reducer.
- formatModifiedAbsolute alongside the relative formatter; hosts switch via
  the new Resources "Relative dates" toggle.
- Mirror hover highlight while a row's context/dropdown menu is open so the
  user knows which row the menu belongs to.
- Guard row pointerdown so a touch long-press no longer stacks the row menu
  on top of the empty-area menu.

Knowledge edit page:
- Decompose into focused subcomponents (header, intro, meta fields, content,
  desktop/mobile body, leave dialog).
- Targeted useWatch on docType so the markdown editor no longer re-renders
  meta fields on every keystroke.
- New useUnsavedChangesGuard hook encapsulates useBlocker, beforeunload and
  the "Save & Leave" dialog; supports skipNextBlock for post-save navigation.

MarkdownEditor:
- Suppress echo updates from tiptap-markdown's re-serializer so RHF's
  isDirty flag stays accurate.

Shared utilities:
- lib/local-storage.ts (zod-validated getStorageItem/setStorageItem) used by
  both table-storage.ts and the new file-manager-storage.ts.
- lib/table-sort.ts#cycleColumnSort shared between Knowledges and Templates.
- hooks/use-latest-ref.ts replaces five useRef+useEffect pairs in FileManager.

DataTable:
- Filter input upgraded to InputGroup with search icon and clear button.
- Extract DataTableFilter subcomponent to drop the inline IIFE.

Resources page:
- Per-page persisted view options (folders-first, relative dates, optional
  size/modified columns) extracted into a typed ResourcesViewOptions shape
  with a centralized defaultViewOptions and a single loadViewOptions reader.
- Promote upload / new-folder buttons to the page header.

Misc:
- Replace MoreHorizontal / MoreVertical icons with Ellipsis for visual
  consistency.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-09 20:36:54 +07:00
mason5052 5af902872a docs(rfc): address Copilot review feedback on MCP client RFC
- Reword PR #268 references to talk about review feedback rather
  than the PR being rejected.
- Clarify host.docker.internal availability: not universally provided
  by the core compose stack; Docker Desktop typically resolves it,
  while Linux/operator-managed compose stacks may need an explicit
  extra_hosts: host.docker.internal:host-gateway entry or another
  controlled endpoint.
- Make the safe initial Burp example unambiguously read-only: drop
  start_active_scan from the illustrative allowlist and call out
  that active capabilities belong to a later, explicitly gated
  milestone with scope and approval controls.
- Rephrase the awkward 'PentAGI must not be inferred...' sentence
  for clarity.

Signed-off-by: mason5052 <ehehwnwjs5052@gmail.com>
2026-05-08 16:09:01 -04:00
mason5052 ba8a687cb6 docs(rfc): propose MCP client integration design
Signed-off-by: mason5052 <ehehwnwjs5052@gmail.com>
2026-05-08 15:55:23 -04:00
Dmitry Ng ba0cee43c8 fix(router): add new frontend routes for resources and knowledges to preserve route in the browser
- Introduced "/resources" and "/knowledges" routes to the frontendRoutes array in the router configuration, expanding the application's routing capabilities.
2026-05-08 20:46:47 +03:00
Dmitry Ng a9aeb81e4e refactor(resources): update MoveResourceRequest to allow empty destination
- Removed the requirement for the "destination" field in MoveResourceRequest, allowing it to be an empty string, which signifies moving to the root directory.
- Updated related documentation in swagger.json, swagger.yaml, and docs.go to reflect the new behavior.
- Adjusted the MoveResource function to handle cases where the destination is empty, ensuring proper path sanitization and resource movement semantics.
- Enhanced test cases to cover scenarios involving moving resources to the root directory and handling conflicts appropriately.
2026-05-08 20:24:39 +03:00
Dmitry Ng dc2fd43928 feat(assistants): support flowID=0 in REST API to create assistant with new flow
- Allow POST /flows/0/assistants/ to create a new flow together with the assistant, mirroring the existing GraphQL createAssistant(flowID: 0) behavior
- Require both assistants.create and flows.create permissions when flowID=0
- Add explicit flow ownership check for non-zero flowID using flows.admin scope
- Load flow data in the response by fetching it via assistant.FlowID after creation, ensuring AssistantFlow is fully populated in all cases
2026-05-08 18:54:14 +03:00
Sergey KozyrenkoandCursor 95893bf502 feat(knowledge): rich tiptap editor for content with per-panel scrolling
- replace plain textarea with a tiptap-based markdown editor (StarterKit, tiptap-markdown, placeholder) and a basic formatting toolbar so authors can edit knowledge content with rich formatting while keeping markdown as the storage format for embeddings
- introduce a reusable MarkdownEditor shared component and a tiptap Storage type augmentation
- move the save action from the input addon into the page header on the right
- give each desktop resizable panel its own internal scroll so long meta or content no longer makes the whole page scroll

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-08 17:55:38 +07:00
Sergey KozyrenkoandCursor 318acc9f77 feat(knowledge): add knowledge documents UI with list and detail pages
Wire up KnowledgesProvider with Apollo subscriptions and cache policies,
add /knowledges routes and sidebar entry, plus minor formatting cleanups
across file-manager, upload-validation and resources upload helpers.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-08 17:55:38 +07:00
Sergey KozyrenkoandCursor 012cb741ad refactor(file-manager): chevron drill-in, responsive bulk bar and tri-state toggle fix
- File manager core:
  - Chevron click on folder rows now drills in via `onOpenDirectory`
    (when set), matching the existing double-click / Enter semantics.
    Consumers that don't wire the prop keep the legacy expand/collapse
    behaviour, so flow-files / resources trees stay unchanged.
  - Bulk actions bar wraps and collapses to icon-only buttons (Cancel
    included) on small viewports so the bar stays usable on mobile.
  - Fix tri-state subtree toggle requiring two clicks when the
    directory's own path was never in the selection (e.g. user ticked
    children one-by-one). \`toggleSubtreeOnSet\` now accepts an optional
    \`rootPath\` and ignores it for the "all selected?" check, mirroring
    what \`computeDirSelectionState\` shows on the visible checkbox.
    Covered by new regression tests in \`file-manager-utils.test.ts\`.
  - Built-in icons swapped: copy-path uses \`ClipboardCopy\` instead of
    \`Copy\`; bulk \"Save as resources\" uses \`FolderOutput\` instead of
    \`BookmarkPlus\`.

- Pull dialog: flatten the container listing (\`name\` as \`path\`,
  absolute path in \`id\`) so the chevron / double-click drill into
  real subfolders instead of toggling a synthetic \`work/\` wrapper that
  has no meaningful navigation target. Selection is mapped back to
  absolute paths via a name → absolute lookup before pulling.

- Resources page: drop the focus-derived \`currentDir\` plumbing —
  toolbar mkdir / upload always target the library root, row context
  menu loses \"Upload files here\" and renames \"New folder here\" to
  \"New folder\". Page wraps in \`h-[calc(100dvh-3rem)]\` so the bulk
  bar stays inside the viewport. Tooltips simplified accordingly.

- Flow files toolbar: replace the standalone Info icon with rich
  per-button tooltips that explain where each gesture lands
  (/work/uploads, /work/resources, separate Container snapshot area);
  upload button uses the standard \`Upload\` glyph.

- Attach resources dialog: switch the ad-hoc footer to a proper
  \`DialogFooter\` with responsive layout, tighten the dialog title.

- \`Dialog\` / \`Sheet\` footers always apply the inter-button gap,
  not only at the \`sm+\` breakpoint.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-08 17:55:37 +07:00
Sergey KozyrenkoandCursor d743bf5105 refactor(flow-files): share upload validator and rely on subscriptions for cache sync
Two cleanups closing the remaining P2/P3 gaps in the flow-files / resources
upload + delete paths.

A.4 — unify upload-batch validation
- New shared validator at `frontend/src/lib/upload-validation.ts` (with
  tests) exposing `validateUploadBatch(files, limits)`. Mirrors the
  per-file / per-batch / empty-file rules enforced by both backends
  (`pkg/resources/resources.go`, `pkg/flowfiles/files.go`).
- `useResourcesUpload` migrated off its private validator onto the shared
  helper; behaviour and toast strings unchanged.
- `useFlowFilesUpload` now runs the same preflight before constructing
  the FormData. Hitting any of the 300 MB / 1000 files / 2 GB / 0-byte
  rules surfaces a synchronous toast instead of a network round-trip
  followed by a generic 413.
- Added `FLOW_FILES_MAX_FILE_SIZE_MB`, `FLOW_FILES_MAX_UPLOAD_TOTAL_SIZE_MB`
  and `FLOW_FILES_MAX_UPLOAD_FILES_PER_REQUEST` to flow-files-constants
  alongside the existing resources constants — kept as a separate set so
  the two backends can diverge later without touching unrelated call
  sites.

C.2 — drop redundant refetchFiles() after flow-file mutations
- The backend already publishes per-file flowFileAdded / flowFileDeleted
  events (with directory expansion on delete), `lib/apollo.ts` already
  maps them through the universal subscriptionCacheLink, and
  `useFlowFilesRealtime` already wires the three subscriptions. Only the
  imperative `await refetchFiles()` in upload/delete plus the
  `onSuccess={refetchFiles}` props on pull/attach dialogs were left over
  from the pre-subscription era.
- Dropped `refetchFiles` from `useFlowFilesUpload` and `useFlowFilesDelete`
  param types and removed the matching `await` calls. Added optional
  `onAfterDelete` to the delete hook (mirrors `useResourcesDelete`) for
  callers that want a UI hook without driving a refetch.
- Made `onSuccess` optional on `FlowFilesPullDialog` and
  `FlowFilesAttachResourcesDialog`; removed the `onSuccess={refetchFiles}`
  passthroughs in `flow-files.tsx`. The pull dialog's internal
  `refetchListing` over the container listing (a separate hook) is kept.

Verified: vitest 140/140, eslint clean on touched files, tsc shows only
the same pre-existing errors as before this change (`User.ts`/`user.ts`
casing; `single possibly undefined` in unrelated delete branches).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-08 17:55:37 +07:00
Sergey KozyrenkoandCursor 3540407aa6 feat(frontend): atomic batch resource ops and context-aware uploads
- Send `sources[]` (was single `source`) to /resources/copy,
  /resources/move and /files/to-resources so multi-select operations
  execute in one DB transaction; replace the per-feature 409 aggregation
  state and the now-unused `resources-conflict-dialog` with the shared
  `useOverwriteAction` workflow returning `OverwriteOutcome`.
- Extend `FileManager` with `emptyAreaActions` (right-click context menu
  over the tree's empty area), `appliesToFiles` filter (companion to
  `appliesToDirs`), `onActiveRowChange` focus reporting and row-level
  external-file drop (`onExternalFileDrop`).
- `useFilesDragAndDrop`: capture-phase `onDropCapture` resets the
  internal counter / `isDragging` flag before any descendant claims the
  drop with `stopPropagation`, fixing the page-level upload overlay
  staying stuck after a row-level drop.
- `useResourcesUpload` gains `defaultDir` (read via ref so `uploadFiles`
  stays reference-stable) and `openFilePickerForDir` so toolbar /
  sidebar / CTA pickers upload into the focused folder by default and
  per-row "Upload here" actions can target a specific directory.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-08 17:55:37 +07:00
Sergey KozyrenkoandCursor 76cb4c1283 refactor(frontend): unify overwrite flow and atomic multi-path file APIs
- Extract shared OverwriteConfirmDialog, OverwriteCtaButtons, and
  useOverwriteAction hook; reuse across Pull, Attach, Promote, Move, Copy
  dialogs to drop per-dialog overwrite switches in favour of explicit
  "… with overwrite" CTA + Replace-all confirm.
- Move file-manager into components/shared, add bulkDownloadAction and
  onOpenDirectory navigation override for navigation-style browsers.
- Switch flow files / resources delete and download to atomic multi-path
  endpoints via paths[]= query, drop Promise.allSettled fan-out.
- Add useFlowContainerFiles + container browse in Pull dialog with
  client-side conflict preflight (flow-files-conflicts).
- Extract getApiErrorStatusCode helper to deduplicate 409 detection.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-08 17:55:36 +07:00
Sergey KozyrenkoandCursor 0c65579066 feat(file-manager): extensible bulk actions API and additive shift-click selection
Replace the single `onBulkDelete` prop with a generic `bulkActions` array so the
host owns which gestures appear in the footer bar. Built-in helpers (`bulkDeleteAction`,
`bulkCopyPathsAction`, `bulkMoveAction`, `bulkCopyAction`, `bulkPromoteAction`)
match the row-action pattern; each entry supports inline button or trailing
overflow menu, optional confirm dialog, isDisabled / isHidden predicates, and
receives the deduped FileNode[]. The bar also surfaces a cumulative size
summary alongside the item count.

Fix Shift+click range selection so it matches user expectations and the rest
of the file-manager's folder semantics:

- Range clicks are now ADDITIVE: the visible-order slice is unioned onto the
  previous selection instead of replacing it, so Cmd-clicked picks, earlier
  shift-ranges, and explicitly clicked folder subtrees survive a follow-up
  Shift+click.
- Folders inside the slice expand to their full subtree via `dirSubtreePaths`,
  mirroring the contract of a plain folder click. Without this, a Shift+click
  across collapsed sibling folders left the folder paths in `selectedPaths`
  but rendered their tri-state checkboxes as unchecked because no descendants
  had been added to the selection.
- Anchor preservation across chained Shift+clicks is unchanged; toggle/single
  still move the anchor.

Migrate `flow-files`, `resources`, and the move/copy/promote dialogs to the
new `bulkActions` API.

Tests: 131 passing — covers reverse direction, expanded vs. collapsed folders,
nested folders, mixed file/folder anchors, empty folders in range, omitted
`dirSubtreePaths` (tree-less callers), anchor=null and off-screen anchor
fallbacks, chained shift-clicks accumulating subtrees, toggle + shift-click
combinations, idempotent same-row range clicks, and the additive contract's
explicit divergence from Finder/Explorer (range never shrinks the selection).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-08 17:55:36 +07:00
Dmitry Ng a348e41a31 feat(settings): add version and isDevelopMode fields to Settings model and GraphQL schema
- Introduced new fields `version` and `isDevelopMode` in the Settings model to provide application versioning and development mode status.
- Updated GraphQL schema and resolvers to support the new fields, ensuring they are accessible via the Settings query.
- Enhanced Swagger documentation to reflect the changes in the Settings API endpoint.
- Added necessary validation and response handling for the new fields in the Settings service.
2026-05-08 13:06:07 +03:00
mason5052 2d407b928e docs(rfc): clarify lifecycle, terminal semantics, and webhook event names
Address Copilot review feedback on PR #306:

- Lifecycle diagram: show running <-> waiting (waiting is a paused state that resumes to running when user input arrives) and document that both running and waiting can reach the terminal statuses finished or failed.

- Replace overloaded 'finished' wording with explicit 'terminal' semantics throughout. finished and failed remain distinct terminal statuses; the queue and webhook layers treat both as terminal.

- Align webhook event names with status terminology: flow.finished for success, flow.failed for failure. Update payload example accordingly and note the failed-flow shape.

Signed-off-by: mason5052 <ehehwnwjs5052@gmail.com>
2026-05-07 13:18:34 -04:00
mason5052 c0e9ed74fd docs(graphiti): use user-facing env vars for OpenAI endpoint
Address Copilot review feedback on PR #305: the 'Current Limitations' bullet for the Graphiti integration mixed PentAGI's user-facing .env variables with the container env vars defined in docker-compose-graphiti.yml.

Reword both README.md and backend/docs/config.md to lead with the user-facing OPEN_AI_KEY and OPEN_AI_SERVER_URL .env variables and explicitly note that docker-compose-graphiti.yml maps them into the bundled vxcontrol/graphiti container as OPENAI_API_KEY and OPENAI_BASE_URL. Operators set the .env variables; the container variables are an implementation detail.

Signed-off-by: mason5052 <ehehwnwjs5052@gmail.com>
2026-05-07 13:16:01 -04:00
mason5052 ad7d2b12ce docs(flows): refine prompt block, snapshot source, and filename limit wording
Address Copilot review feedback on PR #304:

- Clarify the UserFiles template variable produces a <task_files> XML block with <uploads>/<resources> nested sections (matches flowfiles.FileListingForPrompt output).

- Distinguish that uploads/resources mirror to /work/uploads/ and /work/resources/, while container snapshots can originate from arbitrary container paths and are cached only under container/ on the flow side.

- Note that the 255 filename limit is enforced by len(name) <= 255, i.e. byte-length, so it is roughly 255 ASCII characters.

Signed-off-by: mason5052 <ehehwnwjs5052@gmail.com>
2026-05-07 13:11:54 -04:00
mason5052 295e7d3b01 docs(rfc): propose persistent flow queue and completion webhooks
Proposes a design direction for native flow concurrency control and
completion notifications. The RFC follows the maintainer's relocated
proposal pattern at examples/proposals/<topic>.md and explicitly
builds on the lessons from PR #268 (rejected because the in-memory
queue was hidden lifecycle state).

The RFC covers:

- Goals limited to capping concurrent flows, persisting queued flows
  as first-class lifecycle, replacing external polling with at-least-
  once webhooks, and preserving the existing createFlow contract.
- Non-Goals that explicitly forbid hidden in-memory queues, multi-
  tenant scheduling, generic event bus features, and changing the
  meaning of 'finished' for tasks/subtasks/toolcalls.
- Design Principles for persistence, visibility, manageability,
  explicit promotion, clear finished semantics, and at-least-once
  delivery.
- A proposed concurrency model with a new persisted 'queued' status,
  a single MAX_CONCURRENT_FLOWS knob, an explicit promoter, and
  full UI/API visibility plus user cancellation.
- A proposed completion webhook model with per-flow and global URLs,
  HMAC-SHA256 signatures, persisted deliveries, bounded retries,
  and SSRF mitigations.
- Storage and API surface sketches that do not commit to a final
  schema.
- Open Questions covering per-user limits, blocking semantics on
  createFlow, signature alignment with the issue #235 receipt
  direction, and behavior of resources/uploads against queued flows.
- A Suggested First Milestone that lands the queue end-to-end before
  webhooks, to keep PR sizes reviewable.

This is documentation only. No runtime code, schema, GraphQL, REST,
or UI behavior changes here.

Refs #298

Signed-off-by: mason5052 <ehehwnwjs5052@gmail.com>
2026-05-07 12:28:06 -04:00
mason5052 fa53a4e1d2 docs(graphiti): note beta status and OpenAI-only provider limitation
The Graphiti container shipped with docker-compose-graphiti.yml only
takes OPENAI_API_KEY and OPEN_AI_SERVER_URL for entity extraction.
PentAGI configures many other LLM providers (Anthropic, Google AI,
AWS Bedrock, DeepSeek, GLM, Kimi, Qwen) for the main flow, but those
credentials are not consumed by Graphiti today. Until that changes,
operators need to plan around an OpenAI-compatible endpoint just for
the knowledge graph.

This commit makes the limitation visible in two surfaces without
changing runtime behavior:

- README.md: Adds a beta callout at the top of the Knowledge Graph
  Integration section and a new 'Current Limitations' subsection
  covering provider scope, fixed model, independent billing, and the
  lack of an in-app graph explorer.
- backend/docs/config.md: Mirrors the beta callout under Graphiti
  Knowledge Graph Settings and adds a 'Current Limitations (Beta)'
  subsection with the same constraints, so config-focused readers
  see the same message.

Both notes explicitly point at the simple fallback: leave
GRAPHITI_ENABLED=false if the deployment cannot reach an
OpenAI-compatible endpoint.

Refs #187

Signed-off-by: mason5052 <ehehwnwjs5052@gmail.com>
2026-05-07 12:22:38 -04:00
mason5052 e869445430 docs(flows): document flow-scoped Files tab, sources, and current limits
Add a How-to subsection that describes the Files tab on a flow page
without restating implementation details. The new section covers:

- The three file sources surfaced in the UI (uploads, resources,
  container snapshots) with their exact action labels.
- The on-host layout under {dataDir}/flow-{id}-data/ and the
  corresponding container paths /work/uploads and /work/resources.
- Per-file actions (Download, Copy path, Save as resource, Delete)
  and the Pull action's disabled state when the container is not
  running.
- Automatic injection of uploaded files and attached resources into
  agent system prompts via the <UserFiles> block, so users understand
  how the assistant sees their files.
- Current limits (300 MB / 1000 files / 2 GB / 255-char names) and
  current limitations, including that flow deletion does not yet
  archive or remove the flow data directory on disk.

This is a documentation-only change and does not introduce or change
runtime behavior.

Refs #193

Signed-off-by: mason5052 <ehehwnwjs5052@gmail.com>
2026-05-07 12:19:30 -04:00
mason5052 3278c62b96 fix(controller): avoid JSON round-trip and N+1 prompter loads
Address two reviewer concerns on the issue #300 follow-up:

* Replace the `DumpTemplates()` -> `json.Unmarshal` round-trip in
  buildUserPrompter with a new `templates.LoadDefaultPromptsMap()`
  helper that returns the embedded defaults as a `PromptsMap`
  directly. `defaultPrompter.DumpTemplates()` now delegates to the
  same helper, so the JSON output for that API is unchanged.
* Add an optional `prompter` field to `assistantWorkerCtx`. When
  set, `LoadAssistantWorker` reuses it instead of re-querying
  `GetUserPrompts` and re-merging defaults. `LoadFlowWorker`
  populates it once per flow load so multi-assistant flows pay the
  DB+merge cost a single time.

Tests updated to match the new pure-merge `buildUserPrompter`
signature; behavior for users with no overrides is unchanged.

Signed-off-by: mason5052 <ehehwnwjs5052@gmail.com>
2026-05-06 22:30:26 -04:00
mason5052 73d5b8366d fix: drop unverified ollama tags and broaden hint context
Address review on PR #303.

- helpers.go: remove the concrete model examples (llama3.1, qwen2.5, mistral-nemo) from the Ollama tools-unsupported hint. PentAGI does not verify Ollama model capabilities from upstream metadata, so a hard-coded list of supposedly tool-capable tags is risky and ages poorly. The hint now points users to select an Ollama model whose own metadata advertises tool/function calling support.

- helpers.go: rewrite the comment and error wording so it is no longer flow-only. The helper is shared by NewFlowProvider and NewAssistantProvider, so the message now refers to tool execution in flows and assistant sessions, and the doc-comment notes that wording must stay context-neutral.

- helpers_test.go: tighten TestWrapToolCallIDTemplateError to match the new wording, ban the previous concrete model tags, and ban flow-only language ('flow execution', 'flow creation'). The test still verifies that the original underlying error is wrapped via errors.Is.

Signed-off-by: mason5052 <ehehwnwjs5052@gmail.com>
2026-05-06 22:11:12 -04:00
mason5052 552eda8746 fix: clarify Ollama models without tool support
## Summary
Surface an actionable hint when an Ollama model that does not support
tool/function calling is selected for a flow or assistant session, so
users do not have to parse a five-wrap-deep "failed to determine tool
call ID template" stack trace to figure out why flow creation fails.

## Problem
A user on an Ollama deployment of `gemma3:27b-it-q4_K_M` reports that
the Provider/LLM test passes the basic completion checks but flow
creation fails with:

  failed to create flow worker: failed to get flow provider: failed
  to determine tool call ID template: failed to collect tool call ID
  samples: all sample collection attempts failed: failed to call LLM:
  400 Bad Request: registry.ollama.ai/library/gemma3:27b-it-q4_K_M
  does not support tools

The underlying signal "does not support tools" is emitted by the
Ollama API itself; PentAGI buries it five wraps deep, so the user is
left guessing whether the issue is configuration, networking, or
something internal to PentAGI.

## Solution
Add an unexported helper `wrapToolCallIDTemplateError` in
`pkg/providers/helpers.go` that detects the upstream "does not support
tools" substring and prepends a one-sentence guidance message naming
the constraint and a few known-good Ollama tags
(`llama3.1`, `qwen2.5`, `mistral-nemo`). All other errors keep the
existing wording. The original error is preserved via `%w` so log
spans, langfuse traces, and any future `errors.Is/As` callers continue
to work.

Both call sites in `pkg/providers/providers.go`
(`NewFlowProvider`, `NewAssistantProvider`) now route through the
helper.

No schema, API, or DB changes. No new lifecycle state. No background
work. The behavior change is the wording of one error string in one
upstream-defined failure case.

## User Impact
- Users who pick an Ollama model without tool support get a clear,
  actionable error during flow / assistant creation instead of a deep
  stack trace.
- Users on tool-capable models (Anthropic, OpenAI, Bedrock, and
  tool-capable Ollama tags) see no behavioral or message change.
- No restart, migration, or configuration step required.

## Test Plan
- New table-driven test `TestWrapToolCallIDTemplateError` covers:
  - nil error -> nil
  - upstream "does not support tools" chain (matching the real five-
    wrap shape) -> actionable message + `errors.Is` round-trips to the
    original error
  - generic non-tools error -> existing wrap text preserved, no
    new guidance appended
- `go test ./pkg/providers/...` passes locally.
- `go build ./...` and `go vet ./pkg/providers/...` clean.

Closes #280

Signed-off-by: mason5052 <ehehwnwjs5052@gmail.com>
2026-05-06 18:30:32 -04:00
mason5052 08c050ce21 fix: apply custom prompts to new sessions
Custom prompts saved via the Settings -> Prompts UI are persisted to the
database, but every assistant and flow session creation path was using
templates.NewDefaultPrompter() with a leftover TODO, so user overrides
never reached the agents and Langfuse traces always showed the defaults.

Add a controller-side helper that loads the user's saved prompts and
overlays them on the compiled defaults. Prompt types the user has not
customized continue to use the defaults; an empty body row is treated
as no override (the UI uses delete to reset). A database error fails
session creation explicitly instead of silently falling back.

Wire the helper into the four affected call sites in NewAssistantWorker,
LoadAssistantWorker, NewFlowWorker, and LoadFlowWorker.

Closes #300

Signed-off-by: mason5052 <ehehwnwjs5052@gmail.com>
2026-05-06 18:10:17 -04:00
Dmitry Ng 6890584c64 feat(resources): add multi-source move, copy and flow-file promotion
- Add Sources []string to MoveResourceRequest, CopyResourceRequest and AddResourceFromFlowRequest; merged with Source, deduplicated; multi-source uses destination as base dir and runs in a single atomic DB transaction
- Fix MoveResource response to return Added + Updated (not Updated only) so Apollo cache receives new parent directory entries alongside moved items
- Add missing errResourceNotFound case in CopyResource (was 500 instead of 404)
- Cover all new behaviour with table-driven tests (basename conflict, force overwrite, missing source, empty input, dir-into-itself guard, etc.)
2026-05-06 17:03:13 +03:00
mason5052 1cd643f72c docs: tighten macOS installer warning guidance 2026-05-05 20:14:58 +00:00
Dmitry Ng 3a52079278 feat(knowledge): add pgvector knowledge base management
- GraphQL/REST CRUD + semantic search for knowledge documents
- KnowledgeStore with admin/user-scoped filtering, re-embedding on update
- Real-time subscriptions (created/updated/deleted) per user and admin
- user_id tracking in all agent-stored documents (guide/answer/code/memory)
- sqlc queries, goose migrations, privilege grants, user_id backfill
- Memory cleanup on flow deletion; stale orphan purge via migration
- Unit tests for all KnowledgeStore operations including security cases
- Frontend GraphQL schema and TypeScript types regenerated
2026-05-05 01:09:20 +03:00
Dmitry Ng ca9f4a0211 feat: add multi-path support and ZIP improvements across file APIs
- Added `paths[]` query/body parameter to DeleteFlowFile, DownloadFlowFile,
  GetFlowContainerFiles, PullFlowFiles, ListResources, DeleteResource, and
  DownloadResource; single `path` parameter retained for backward compatibility.
- Introduced `DeduplicatePaths` in flowfiles package with coverage-based
  deduplication (parent covers children), path normalization, and traversal safety.
- Added `ZipRelativePaths` to create ZIP archives from cache-relative paths,
  sharing `zipWriteFile` helper with refactored `ZipDirectory`.
- Switched all ZIP and single-file responses to buffered `DataFromReader` with
  explicit `Content-Length`, fixing Swagger UI download rendering.
- Expanded response payloads: delete and pull operations now enumerate all
  affected nested files; list responses include ancestor directories for tree
  completeness.
- Extended test coverage across flowfiles, flow_files, and resources packages
  with batch, deduplication, atomicity, Docker exec, and security scenarios.
2026-05-04 14:32:39 +03:00
Dmitry Ng f57e988586 feat(cast): add JSON control character sanitization for tool call arguments
- Implemented `SanitizeJSONControlChars` to escape literal control characters in JSON string values, ensuring compliance with the JSON specification.
- Enhanced `SanitizeToolCallArguments` method to apply sanitization across tool call arguments in the chain.
- Added comprehensive tests for both sanitization functions to validate behavior with various input scenarios.
2026-05-03 00:48:47 +03:00
Dmitry Ng 9cd52b102a fix(csum): prevent out-of-range errors in recent section determination
- Updated the logic in `determineRecentSectionsToKeep` to clamp the lower bound of the recent sections to keep, ensuring it does not exceed the available sections. This prevents potential out-of-range errors when `keepQASections` is greater than the total number of sections.
2026-05-03 00:47:47 +03:00
Dmitry Ng 46c7807af9 fix(main): router initialization
- Updated router initialization to include the Docker client
2026-05-03 00:47:04 +03:00
Dmitry Ng e370450dab feat(browser): enhance HTML and MD content handling with warnings for small content and errors for binary URLs
- Updated `getHTML` and `getMD` methods to return warnings for small content instead of errors.
- Implemented checks for binary URLs, returning descriptive errors when such URLs are encountered.
- Added new tests to validate the updated behavior for small and empty content handling.
2026-05-03 00:45:27 +03:00
Dmitry Ng b254ff6f90 refactor(flow_manager): improve error handling for running tasks 2026-05-03 00:43:51 +03:00
Dmitry Ng 75eb8e0f1e fix(aslog): implement TryLock to prevent deadlock in workerMsgUpdater
- Added TryLock mechanism to avoid deadlock situations when reading from the channel while the mutex is held.
- Enhanced timer handling to reset when the mutex is not available, ensuring continuous operation of the stream.
2026-05-03 00:42:17 +03:00
Dmitry Ng c068d86bf0 feat(docker): update Dockerfile and add new vLLM configurations
- Added new provider configurations for vLLM Qwen 3.6 in both thinking and non-thinking modes.
- Updated the Dockerfile to include the new configuration files for vLLM Qwen 3.6 and ensure proper setup for deployment.
2026-05-02 18:57:42 +03:00
Sergey KozyrenkoandCursor 268732f610 feat(file-manager): add subtree selection, open gesture, and parent-dir drop forwarding
- Folder rows now surface a tri-state checkbox derived from descendant selection;
  clicking / shift-clicking / toggling a folder flips the entire subtree in one
  gesture, including descendants of a collapsed folder.
- Files get a new onOpen prop, fired on double-click and Enter; directories keep
  expanding/collapsing. The resources page wires it to the existing download flow.
- Drop on a file row forwards to its parent folder so the whole folder acts as a
  single drop zone (Finder/Explorer semantics), with a shared drag-enter counter
  so highlight stays stable when moving the cursor between sibling rows.
- Extract pure data layer into useFileManagerData and pure selection reducers
  (computeRowClickSelection / computeToggleSelection / computeToggleSelectAll /
  computeDirSelectionState) into file-manager-utils; bundle per-tree row props
  into display / handlers so memoized rows stay reference-stable across parent
  re-renders, keyboard expansion, and selection changes.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-02 17:24:42 +07:00
Dmitry Ng ba14913c0e refactor: standardize resource ID handling and improve flow file management
- Updated resource ID handling to ensure consistent string coercion for numeric IDs across components.
- Enhanced sorting of resources in the FlowForm to use alphabetical order based on path.
- Improved resource attachment logic in the FlowFilesAttachResourcesDialog to avoid deduplication of descendants.
- Introduced utility functions for converting REST resource entries to a consistent format for Apollo cache.
- Adjusted upload handling to ensure proper type consistency between REST and GraphQL responses.
- Refactored promote functionality to align with updated resource ID handling and improve clarity in parameters.
2026-05-01 16:11:45 +03:00
Dmitry Ng 8830ae7010 fix: update resource handling and API documentation
- Adjusted descriptions in API documentation to clarify paths for uploads, resources, and containers.
- Updated data models to use consistent naming conventions (e.g., `isDir` to `is_dir`, `modifiedAt` to `modified_at`).
- Changed resource ID types from string to uint64 for better consistency across the application.
- Enhanced flow file upload functionality to support batch processing of resource files.
- Removed deprecated code related to resource entry responses in tests.
2026-05-01 16:11:09 +03:00
Dmitry Ng 629c018a68 fix: bug with retrieving resources recursive via graphql 2026-05-01 16:09:06 +03:00
Dmitry Ng b6f7fd7ef8 feat: enhance task and subtask handling with interruption management 2026-05-01 16:05:12 +03:00
Sergey Kozyrenko 3da56244dd feat: integrate user resources into flows and polish file manager
- Replace resources feature mocks with real GraphQL + REST integration
  (Apollo subscriptions-backed cache, dedicated hooks for search, upload,
  copy, move, mkdir, delete, plus conflict / mkdir / copy / move dialogs
  and a shared FileDropZone UI component).
- Let flows attach user resources on creation and in chat messages:
  FlowForm exposes resourceIds as a form field with a multi-select
  dropdown (file/folder icons), wired through createFlow, createAssistant,
  putUserInput and callAssistant mutations.
- Add attach-resources and save-as-resource (promote) dialogs to the
  flow files page; unify drag-and-drop via a shared
  hooks/use-files-drag-and-drop.
- Harden file manager: align skeleton layout (grid + column config) with
  real rows, extract use-file-manager-dnd, add group selection state and
  tree-node accessibility fixes.
- Normalize numeric id/userId from REST /resources/ responses to strings
  so GraphQL ID-typed consumers (zod-validated resource picker) work.
  Marked with TODO(backend) for removal once the REST endpoint matches
  the GraphQL ID scalar.
- Ignore *.tsbuildinfo artifacts.

Made-with: Cursor
2026-05-01 04:34:42 +07:00
Sergey Kozyrenko 0c412cedf9 refactor(flow-files): naming 2026-05-01 04:34:42 +07:00
Sergey Kozyrenko ca747b867a chore: remove unused shadcn AI and crud reference components
Drops `components/ai/file-tree.tsx` and `components/blocks/{crud,skeleton}/*`
reference snippets that were never imported anywhere; the real
file manager lives under `components/file-manager/` and is the only
implementation in use.

Made-with: Cursor
2026-05-01 04:34:41 +07:00
Sergey Kozyrenko f35d2cc0ae refactor(file-manager): polish API, accessibility, and naming
- split monolithic FileManager into FileManagerTreeNode, FileManagerBulkActionsBar, and useFileManagerKeyboardNavigation
- group FileManagerProps columns/search into nested configs and rename visibility booleans from show* to is*Visible per project convention
- replace abbreviations (idx, i, Sep, Item) with full names across components, hooks, and tests
- add ARIA tree-pattern attributes (aria-level, aria-posinset, aria-setsize, aria-multiselectable) and fix aria-hidden hiding the Select-all checkbox
- add labels.formatModified to localize the date column
- make walkTree strictly pure by hiding its internal accumulator
- move side effects out of the setState updater in useFileManagerSelection
- drop redundant stopPropagation in favor of the data-fm-skip-row-click marker

Made-with: Cursor
2026-05-01 04:34:41 +07:00
Sergey Kozyrenko 58f3c09cb0 chore: add shadcn AI and crud reference components
- vendor the shadcn ai/file-tree primitive (recursive collapsible tree with shared expand/select context) for future AI chat surfaces
- vendor the shadcn crud-file-manager and skeleton-file-manager demo blocks as design references; not wired into any route yet

Made-with: Cursor
2026-05-01 04:34:41 +07:00
Sergey Kozyrenko 929ee4e8c2 style: reformat flow-form long lines
- collapse multi-line imports and helpers in flow-form back onto single lines per the active prettier config; no behavioral changes

Made-with: Cursor
2026-05-01 04:34:41 +07:00
Sergey Kozyrenko 2b8d4186c6 feat: support async handlers in ConfirmationDialog
- handleConfirm now accepts () => Promise<void> | void; the dialog awaits the promise before closing
- show a Loader2 spinner on the confirm button while the handler is in flight, and disable both confirm and cancel
- block onOpenChange and outside-clicks while processing so the dialog can't be dismissed mid-action
- caller no longer needs to manage its own loading state for confirm-then-async flows

Made-with: Cursor
2026-05-01 04:34:40 +07:00
Sergey Kozyrenko 52825cadeb refactor: introduce typed axios api wrapper and migrate consumers
- add ApiResponse<T> / ApiSuccessResponse<T> / ApiErrorResponse / ApiHttpError types describing the backend protocol
- expose a typed api wrapper with helper methods (api.get / api.post / api.put / api.delete) that returns ApiResponse<T> directly and accepts per-call AxiosRequestConfig
- add unwrapApiResponse(...) and getApiErrorMessage(...) helpers so callers no longer reimplement success/error branching
- set a sensible default request timeout (30s) on the shared axios instance; long uploads still opt out via { timeout: 0 }
- migrate user-provider and password-change-form from the raw axios instance to the new typed api helpers, dropping their bespoke error-shape interfaces

Made-with: Cursor
2026-05-01 04:34:40 +07:00
Sergey Kozyrenko d390fb1dba refactor: integrate FileManager into flow files page
- replace the inline file tree implementation in flow-files with the new FileManager component
- compose row actions via factory helpers (downloadAction / copyPathAction / deleteAction) instead of bespoke menus
- delegate search highlighting, expand/collapse, multi-select and bulk delete to the shared component; the page now only owns upload, drag-and-drop, pull-from-container and per-file delete confirmation
- switch to the typed axios helpers (api / unwrapApiResponse / getApiErrorMessage) for upload, pull and delete calls

Made-with: Cursor
2026-05-01 04:34:40 +07:00
Sergey Kozyrenko d9416363dd feat: add reusable file manager component
- introduce src/components/file-manager with tree rendering, search highlighting, multi-select (single / toggle / shift-range), keyboard navigation (arrows, Home/End, Space, Cmd+A, Esc) and bulk delete
- expose unified actions[] API with downloadAction / copyPathAction / deleteAction factory helpers instead of separate built-in props
- split orchestration into useFileManagerExpansion and useFileManagerSelection hooks; derive expanded/selected state during render without useEffect, preserving Set identity for memo-friendly downstream
- add ARIA tree semantics (role=tree on the container, treeitem rows, roving tabindex via activeRowPath, aria-expanded/aria-selected)
- pure tree utils: O(1) folder lookup via Map, normalizeRootGroups, dedupeOverlappingPaths, findNodeByPath, plus 37 vitest unit tests
- ship shadcn checkbox primitive (depends on @radix-ui/react-checkbox) which the file manager uses for row and select-all controls

Made-with: Cursor
2026-05-01 04:34:40 +07:00
Sergey Kozyrenko 3002b2bf5e feat: add resourses 2026-05-01 04:34:39 +07:00
Dmitry NgandOctopus 956c11eadc feat: introduce engagement-log/technical-channel language policy across agent prompts
- Replaced ambiguous "user's language" guidance in tools/args.go with explicit engagement-log vs technical-channel markers per field, with strong English-only requirement for vector-store and search-engine queries.
- Added a unified LANGUAGE POLICY block to every agent prompt (primary_agent, assistant, pentester, coder, installer, searcher, memorist, generator, refiner, reporter, enricher), tailored per agent based on its actual tool set.
- Extended template variables and tool access (TerminalToolName, FileToolName) for coder, pentester, installer, memorist, generator, refiner, and enricher to match their runtime tool registrations.
- Fixed inverted UseAgents condition and removed misleading vector-store write references in assistant prompt; corrected MEMORY SYSTEM INTEGRATION for mode-specific tool references.
- Compressed COMPLETION REQUIREMENTS across templates and aligned closing-tool guidance with the channel mapping (engagement-log message vs technical-channel result).

Fixes #285.

Co-Authored-By: Octopus <liyuan851277048@icloud.com>
2026-04-30 15:29:56 +03:00
Dmitry Ng 47044dd1cf Merge pull request #294 from mason5052/codex/issue-289-web-ui-account-guidance
docs: clarify web UI account setup
2026-04-30 12:05:17 +04:00
Dmitry Ng c0035ac130 Merge pull request #293 from mason5052/codex/issue-291-fix-processor-doc-links
docs: fix processor wizard integration links
2026-04-30 12:03:07 +04:00
Dmitry Ng b9ac8fef5f Merge pull request #292 from mason5052/codex/issue-192-assistant-flow-management-docs
docs: explain assistant flow management for active flows
2026-04-30 12:01:12 +04:00
Dmitry Ng 47de4e44e6 docs: update links in configuration and flow execution documents, add directory for proposals 2026-04-30 10:09:03 +03:00
MasonandMason Kim 6257612689 docs: add OSINT integration scenarios (#278)
* docs: add OSINT integration scenarios

* docs: clarify OSINT scenario payloads

* docs: clarify OSINT provider identifiers

* docs: distinguish OSINT provider ids

---------

Co-authored-by: Mason Kim(ZINUS US_SALES) <mkim@zinus.com>
2026-04-30 10:47:08 +04:00
mason5052 4a8c491299 docs: clarify web UI account setup 2026-04-29 11:00:50 -04:00
mason5052 29d5723620 docs: fix processor wizard integration links 2026-04-29 10:58:03 -04:00
Mason Kim(ZINUS US_SALES) 9666cf35ca docs: explain assistant flow management 2026-04-28 19:19:57 -04:00
mason5052 ffdeec280f docs: refine macOS installer warning guidance 2026-04-28 23:03:09 +00:00
Dmitry Ng 402dfbe0ee Merge pull request #277 from mason5052/codex/issue-235-evidence-chain-rfc
docs: add evidence chain RFC
2026-04-29 01:35:59 +04:00
Dmitry Ng 425f075a96 Merge pull request #276 from mason5052/codex/issue-71-scope-of-work-template
docs: add scope-of-work pentest template
2026-04-29 01:08:29 +04:00
Dmitry NgandCopilot de6f527e6f Apply suggestions from code review
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Signed-off-by: Dmitry Ng <19asdek91@gmail.com>
2026-04-29 01:07:47 +04:00
Dmitry Ng a8289fcbba Merge pull request #275 from mason5052/codex/issue-69-openvas-custom-image-guide
docs: add OpenVAS custom image guide
2026-04-29 01:05:19 +04:00
Dmitry Ng fb607a8bc7 Merge branch 'feature/next-release' into codex/issue-69-openvas-custom-image-guide
Signed-off-by: Dmitry Ng <19asdek91@gmail.com>
2026-04-29 01:05:07 +04:00
Dmitry Ng 1d6f842bb9 test: add comprehensive coverage for FlowFileService HTTP handlers
- Added table-driven scenarios for all 8 endpoints (Get/Upload/Delete/Download flow files, Pull from container, GetContainerFiles, AddResourcesToFlow, AddResourceFromFlow) covering success paths, all privilege combinations (view/upload/admin/cross-user), error responses (forbidden/not-found/conflict/invalid request), and security checks (path traversal, symlink rejection).
- Introduced reusable test infrastructure: sqlite-backed flows/user_resources schema, fakeDockerClient implementing the full docker.DockerClient interface, flowFileCaptureSubscriptions recording both FlowPublisher and ResourcePublisher events, and helpers for multipart upload bodies and container TAR fixtures.
- Added direct unit tests for shellQuote, parseFlowIDParam, cleanupPendingUploads, and flowScopeForFiles privilege matrix.
- Lifts handler coverage from 0% to 60-90% across the file and total services package coverage from 10.2% to 28.6%.
2026-04-28 22:48:23 +03:00
Dmitry Ng 452a2d51e2 fix: expand ResourceService coverage with comprehensive scenarios
- Restructured single-case tests for List, Mkdir, Download, and CleanupOrphanBlobs into table-driven scenarios.
- Extended Upload, Delete, Copy, and Move scenarios with admin, forbidden, malformed JSON, invalid path, missing source, and trailing-slash hint cases.
- Added dedicated tests for blob deduplication on upload/copy, non-multipart bodies, orphan blob preservation on rollback, and direct deleteOrphanBlob coverage.
- Introduced helpers for parameterized multipart field names, custom UID context, and on-disk blob counting.
2026-04-28 22:02:49 +03:00
Dmitry Ng aa4b70eaba feat: add user resources system and flow integration
- UserResource model with MD5-deduplicated blob storage and virtual path filesystem
- REST API for resource CRUD (upload, mkdir, move, copy, delete, download)
- GraphQL query/mutations with resourceIds support on createFlow, putUserInput, createAssistant, callAssistant
- Resource → flow copy with hierarchy restore; incremental container sync (find missing, copy once)
- FlowWorker.PutResources delegates copy, docker push and flowFileAdded events
- Agent prompts updated with {{.UserFiles}} XML listing of /work/uploads and /work/resources
- Resource subscriptions: resourceAdded/Updated/Deleted
2026-04-28 17:00:17 +03:00
Dmitry Ng 7c4ebda2c2 feat: enhance Docker client with container file operations and API integration
- Added methods for non-recursive directory listing and file stat operations in the Docker client.
- Implemented a new API endpoint to retrieve files from a running container's directory.
- Updated documentation to reflect new file operations and API changes.
- Introduced data structures for container file metadata and integrated them into the flow file service.
- Enhanced flow file management capabilities with improved synchronization between local and container file systems.
2026-04-27 13:19:39 +03:00
Dmitry Ng 72b1c8489e feat: implement flow file management with upload and retrieval capabilities
- Added new endpoints for managing flow files, including listing, uploading, and deleting files within flow workspaces.
- Introduced FlowFile model to represent file metadata.
- Enhanced GraphQL schema to support flow file operations and subscriptions for real-time updates.
- Updated API documentation to reflect new flow file functionalities.
2026-04-27 10:03:42 +03:00
Dmitry Ng 7cdb3a61cb Merge pull request #272 from mason5052/codex/issue-193-flow-file-uploads-v1
feat: add flow-scoped file uploads
2026-04-24 04:03:39 +04:00
Dmitry Ng 5e902ca255 docs: update API tokens section to reflect new naming convention in settings 2026-04-24 03:00:48 +03:00
Dmitry Ng 378db10732 Merge pull request #270 from mason5052/codex/issue-191-settings-coverage
docs: clarify current web settings coverage
2026-04-24 03:52:41 +04:00
Dmitry Ng fadb4dc80e Merge pull request #269 from mason5052/codex/issue-35-capability-boundaries-docs
[codex] docs: clarify current PentAGI capability boundaries
2026-04-24 03:50:05 +04:00
Dmitry Ng 5067e8f5a4 feat: add assistant flow management tools and summarizer cache
- new get_flow_status / stop_flow / submit_flow_input / patch_flow_subtasks tools in assistant executor, backed by FlowWorker callbacks
- flowStatusTool supports 5 detail levels with verbose mode, polling for task readiness, and per-size summarization
- summarizer LRU cache (1000 entries, 4 h TTL, SHA-256 key) on flowProvider to skip redundant LLM calls
- updated assistant.tmpl with full flow management protocol: state reference, decision guide, constraints
- updated flow_execution.md with terminal timeout config, new tools, and cache
2026-04-24 02:37:09 +03:00
Dmitry Ng 172fb8754f Merge pull request #267 from mason5052/codex/issue-74-memory-lifecycle-docs
docs: clarify memory lifecycle across flows
2026-04-22 22:15:23 +04:00
Dmitry Ng b748af5374 docs: reorganize Pentesting Prompt Methodology section in README.md 2026-04-22 21:08:34 +03:00
Dmitry Ng 6919511022 Merge pull request #266 from mason5052/codex/issue-79-pentest-methodology-guide
docs: add pentesting prompt methodology guidance
2026-04-22 21:49:33 +04:00
Dmitry Ng ec449dd414 fix: update troubleshooting instructions for Docker Compose installation 2026-04-22 20:47:53 +03:00
Dmitry Ng 329c9ae1d0 Merge pull request #265 from mason5052/codex/issue-254-compose-check-alignment
fix: align compose checks with docker compose
2026-04-22 21:35:45 +04:00
Dmitry Ng a1b6e9e826 docs: update Assistant mode description in README.md to include sub-agent delegation feature 2026-04-22 20:24:08 +03:00
Dmitry Ng 4b5e5e80f6 Merge pull request #264 from mason5052/codex/issue-61-first-use-guide
docs: add first-use guide after login
2026-04-22 21:07:56 +04:00
mason5052 31a502ff73 docs: add evidence chain RFC 2026-04-22 13:07:27 -04:00
mason5052 5bc534c590 docs: add scope-of-work pentest template 2026-04-22 13:05:40 -04:00
mason5052 3e4e800c44 docs: add OpenVAS custom image guide 2026-04-22 13:04:01 -04:00
mason5052 acd1b06b04 docs: add macOS installer warning guidance 2026-04-22 13:02:00 -04:00
Dmitry Ng 211931839e feat: add Azure OpenAI provider configuration file 2026-04-22 20:00:17 +03:00
Dmitry Ng 239dd31c91 feat: add GetUsageStatsByModelAgentsForFlow query and related GraphQL types
- Implemented a new SQL query to retrieve usage statistics by model and agents for a specific flow.
- Added corresponding Go types and methods to handle the new query in the database layer.
- Updated GraphQL schema to include the new ModelAgentsUsageStats type and the usageStatsByModelAgentsForFlow query.
- Enhanced frontend components to display the new usage statistics in the flow dashboard.
2026-04-22 19:51:20 +03:00
mason5052 c893bb817e docs: fix pentesting methodology links
Signed-off-by: mason5052 <ehehwnwjs5052@gmail.com>
2026-04-22 12:36:18 -04:00
mason5052 aa718e2330 docs: clarify settings config paths
Signed-off-by: mason5052 <ehehwnwjs5052@gmail.com>
2026-04-22 12:36:12 -04:00
mason5052 a285a99e28 docs: tighten memory lifecycle guidance
Signed-off-by: mason5052 <ehehwnwjs5052@gmail.com>
2026-04-22 12:36:08 -04:00
mason5052 263eaf56ab fix: harden flow file uploads
Signed-off-by: mason5052 <ehehwnwjs5052@gmail.com>
2026-04-22 12:35:55 -04:00
Dmitry Ng 93aae13015 feat: add Noto Sans font family for enhanced PDF report generation
- Introduced Noto Sans, Noto Sans Mono, and Noto Sans SC fonts to improve text rendering in PDF reports.
- Updated report-pdf.tsx to register new fonts and handle CJK text rendering.
- Enhanced README.md to document the new fonts and their usage in the application.
2026-04-22 19:09:08 +03:00
Dmitry Ng 5d7106b2a8 feat: implement tooltip animation for chart components to enhance user experience
- Added a custom hook to manage tooltip animation state and session tracking.
- Updated ChartTooltip component to handle first active state and session key.
- Integrated tooltip animation logic into various chart components in the DashboardAnalytics page.
2026-04-22 18:03:47 +03:00
Dmitry Ng 83270bab5d chore: update GraphQL Codegen dependencies to latest versions in package.json and pnpm-lock.yaml 2026-04-22 16:58:37 +03:00
Dmitry Ng fa78acc04c Merge remote-tracking branch 'origin/feature/frontend' into feature/next-release 2026-04-22 16:00:32 +03:00
Dmitry Ng 01987b60fc feat: enhance ChartCard component to display a no-data state with a bar chart icon 2026-04-22 15:56:12 +03:00
Dmitry Ng 17005d8ef8 chore: update Dockerfile to set PNPM environment variables and remove unused dependencies from pnpm-lock.yaml 2026-04-22 15:30:06 +03:00
Dmitry Ng 269d851eab chore: migrate project to pnpm by updating installation commands and CI configuration 2026-04-22 15:10:55 +03:00
Dmitry Ng 897bb7ec53 chore: update pgx dependency to version 5.8.0 in go.mod and go.sum 2026-04-22 15:04:51 +03:00
Dmitry Ng 8fed9a8cd8 docs: clarify proxy configuration and Docker pull test in network validation documentation 2026-04-22 14:46:45 +03:00
Dmitry Ng 246abf7367 Merge pull request #262 from mason5052/codex/issue-258-docker-mirror-docs
docs: add Docker mirror guidance for restricted networks
2026-04-22 15:30:51 +04:00
Dmitry Ng 78e46bd77a refactor: update TERMINAL_TOOL_TIMEOUT to 1200 seconds with detailed documentation
- Changed default terminal tool timeout from 600 to 1200 seconds.
- Updated related documentation across .env.example, README.md, and config files to reflect the new timeout settings and their constraints.
- Enhanced descriptions in code comments and documentation to clarify timeout behavior, including clamping rules for values outside the accepted range.
2026-04-22 13:22:32 +03:00
Dmitry Ng 0e7c238cad Merge pull request #261 from mason5052/codex/issue-256-terminal-timeout
feat: add TERMINAL_TOOL_TIMEOUT configuration
2026-04-21 15:33:33 +04:00
Dmitry Ng 4294eac935 docs: update authentication settings in configuration documentation to reflect changes in OAuth client initialization 2026-04-21 13:19:27 +03:00
Dmitry Ng 25524cb271 Merge pull request #260 from mason5052/codex/issue-219-oauth-docs
docs: clarify OAuth callback setup for GitHub and Google
2026-04-21 13:29:42 +04:00
Dmitry Ng 3e16e02c9a Merge pull request #259 from Kairos-T/main
fix(docs): resolve mermaid syntax errors
2026-04-21 13:18:44 +04:00
Sergey Kozyrenko 4e55e30829 feat: update dashboard page and dashboard flow component
(cherry picked from commit 4bacc346d95d41bd89af4a27fffe566dbf1d8d4b)
2026-04-21 07:46:16 +07:00
Sergey Kozyrenko ed222648b7 fix: migration to pnpm
(cherry picked from commit daf3d4839f3595ef0716b6f2452b6567c778c76d)
2026-04-21 01:59:08 +07:00
Sergey Kozyrenko 93443fc959 fix: lint
(cherry picked from commit 2aac8ff0563483d01b16bb5ee8c191fafa8aff14)
2026-04-21 01:58:18 +07:00
mason5052 4d7c3678a9 feat: add flow-scoped file uploads 2026-04-19 14:27:06 -04:00
mason5052 e86052b041 docs: clarify current web settings coverage 2026-04-16 12:38:51 -04:00
mason5052 ea8aa205bc docs: clarify current PentAGI capability boundaries 2026-04-16 12:27:11 -04:00
Mason Kim(ZINUS US_SALES) 4e2ece8945 docs: clarify memory lifecycle across flows
Signed-off-by: Mason Kim(ZINUS US_SALES) <mkim@zinus.com>
2026-04-15 19:35:08 -04:00
Mason Kim(ZINUS US_SALES) a9a0b76226 docs: add pentesting prompt methodology guide
Signed-off-by: Mason Kim(ZINUS US_SALES) <mkim@zinus.com>
2026-04-15 18:04:50 -04:00
Mason Kim(ZINUS US_SALES) a07c28c2ae docs: add authorized-use reminder
Signed-off-by: Mason Kim(ZINUS US_SALES) <mkim@zinus.com>
2026-04-15 17:52:16 -04:00
Mason Kim(ZINUS US_SALES) 92232f5755 fix: accept compose version output on error
Signed-off-by: Mason Kim(ZINUS US_SALES) <mkim@zinus.com>
2026-04-15 17:51:28 -04:00
Mason Kim(ZINUS US_SALES) eea0a86c85 fix: align compose checks with docker compose
Signed-off-by: Mason Kim(ZINUS US_SALES) <mkim@zinus.com>
2026-04-15 16:18:36 -04:00
Mason Kim(ZINUS US_SALES) af1bf049af docs: add first-use guide after login
Signed-off-by: Mason Kim(ZINUS US_SALES) <mkim@zinus.com>
2026-04-15 16:15:21 -04:00
Mason Kim(ZINUS US_SALES) f984c7865e docs: add Docker mirror guidance for restricted networks
Signed-off-by: Mason Kim(ZINUS US_SALES) <mkim@zinus.com>
2026-04-15 13:45:45 -04:00
Mason Kim(ZINUS US_SALES) 1d6da349d4 fix: clamp oversized terminal timeout 2026-04-15 13:14:16 -04:00
Mason Kim(ZINUS US_SALES) ef195de84a docs: fix OAuth callback URL docs 2026-04-15 13:14:06 -04:00
Mason Kim(ZINUS US_SALES) 86d7666c86 feat: add configurable terminal tool timeout
Signed-off-by: Mason Kim(ZINUS US_SALES) <mkim@zinus.com>
2026-04-15 12:34:03 -04:00
Mason Kim(ZINUS US_SALES) 72a5671562 docs: clarify OAuth callback configuration
Signed-off-by: Mason Kim(ZINUS US_SALES) <mkim@zinus.com>
2026-04-15 11:02:56 -04:00
Kairos 7214abeefb fix(docs): resolve mermaid syntax errors
- added the previously stripped parentheses

Signed-off-by: Kairos <contact@kairostay.com>
2026-04-15 11:06:02 +08:00
Kairos 9b61afb042 fix(docs): resolve mermaid syntax errors
Signed-off-by: Kairos <contact@kairostay.com>
2026-04-15 10:46:55 +08:00
Dmitry Ng 2ec8ef3d9b ci: update CI workflow to use 'main' branch instead of 'master' for build triggers 2026-04-12 02:23:47 +03:00
Dmitry Ng e97eaec410 chore: update package-lock.json with dependency version upgrades for ajv, axios, and brace-expansion 2026-04-12 02:09:13 +03:00
Dmitry Ng 301d681bfa docs: update README for improved structure and clarity, including new sections for architecture and LLM provider configurations 2026-04-12 01:08:58 +03:00
Dmitry Ng 87ac00f195 test(graphiti): strengthen search method tests with proper types 2026-04-11 15:20:52 +03:00
Dmitry Ng 51385079ed Merge pull request #244 from mason5052/test/graphiti-client-coverage
test: add unit tests for graphiti client disabled mode
2026-04-11 16:13:25 +04:00
Dmitry Ng 20ff85ebd6 Merge pull request #243 from mason5052/infra/docker-compose-healthchecks
infra: add healthcheck for pgvector in docker-compose
2026-04-11 16:11:24 +04:00
Dmitry Ng 6753e2b3d6 test(langfuse): strengthen noop tests with safer assertions 2026-04-11 14:02:21 +03:00
Mason b323a8ace0 test: add unit tests for langfuse context and noop observer (#242)
* test: add unit tests for langfuse context and noop observer

Add tests for observation context put/get round-trip, nested context
override behavior, and noop observer: trace ID generation, parent
inheritance, explicit override, Shutdown, ForceFlush, and enqueue.

* test: add edge case tests for noop observer branch coverage

Add two missing branch tests: explicit ObservationID with no parent
context (verifies new trace generation), and explicit TraceID with
parent (verifies observation ID is NOT inherited when trace is explicit).
2026-04-11 14:43:36 +04:00
Dmitry Ng 10e77fb546 test(langfuse): fix float assertions and strengthen type checks 2026-04-11 13:40:15 +03:00
Dmitry Ng 930830e742 test(schema): improve test clarity with null byte comments 2026-04-11 13:17:55 +03:00
Dmitry Ng c08cc0ff10 Merge pull request #247 from vxcontrol/feature/switch_provider
Runtime provider switching
2026-04-09 01:03:37 +04:00
Dmitry Ng 7c25f356ed feat: enable runtime provider switching
Adds conditional chain normalization in processChain to preserve reasoning cache when provider unchanged while fixing incomplete tool_calls and converting IDs when switching providers. Extends GraphQL API with modelProvider parameter for seamless provider changes without restart.
2026-04-08 23:58:56 +03:00
Dmitry Ng 44e14775a4 Merge pull request #241 from mason5052/test/langfuse-helpers-coverage
test: add unit tests for langfuse helpers package
2026-04-09 00:52:59 +04:00
Dmitry Ng 5e2deebd17 Merge pull request #246 from vxcontrol/feature/frontend
UI terminal: modular architecture, Unicode fix, and security hardening
2026-04-09 00:46:35 +04:00
Sergey Kozyrenko f49d9cba42 feat: update terminal 2026-04-09 02:24:58 +07:00
Sergey Kozyrenko 046f0dbe92 feat: update terminal 2026-04-09 01:36:20 +07:00
mason5052 166035b3de test: add unit tests for graphiti client disabled mode
Add tests for NewClient with enabled=false, IsEnabled nil/disabled/enabled
receivers, GetTimeout nil/configured, AddMessages no-op on disabled client,
and all 7 search methods returning "graphiti is not enabled" error when
disabled. All tests are hermetic with no network dependency.
2026-04-08 12:06:32 -04:00
mason5052 161b122d91 test: add getCurrentTimeRef test and strengthen ModelParameters assertions
Add missing TestGetCurrentTimeRef coverage. Replace shallow key-presence
checks in ModelParameters.ToLangfuse tests with full value assertions:
verify MapValue string/integer/boolean/list payloads for inf default,
explicit max_tokens, formatted floats, json mode, and stop words.
2026-04-08 11:29:00 -04:00
mason5052 223b832840 infra: add healthcheck for pgvector in docker-compose
Add pg_isready healthcheck to pgvector service and update pentagi and
pgexporter depends_on to use service_healthy condition. This prevents
the application from starting before PostgreSQL is ready to accept
connections, matching the pattern used in docker-compose-langfuse.yml.
2026-04-08 09:47:20 -04:00
mason5052 cad6b01ebb test: add unit tests for langfuse helpers package
Add comprehensive unit tests for all utility functions in the langfuse
helpers package: mergeMaps, ObservationLevel, GenerationUsageUnit,
GenerationUsage, ModelParameters, GetLangchainModelParameters, trace/span
ID generation, time helpers, and pointer helpers.
2026-04-08 09:44:01 -04:00
Dmitry Ng e687b8edfb Merge pull request #240 from vxcontrol/dependabot/npm_and_yarn/frontend/npm_and_yarn-127d3e4132
build(deps): bump the npm_and_yarn group across 1 directory with 4 updates
2026-04-08 14:22:27 +04:00
dependabot[bot] 8933e208f8 build(deps): bump the npm_and_yarn group across 1 directory with 4 updates
Bumps the npm_and_yarn group with 4 updates in the /frontend directory: [picomatch](https://github.com/micromatch/picomatch), [yaml](https://github.com/eemeli/yaml), [flatted](https://github.com/WebReflection/flatted) and [jspdf](https://github.com/parallax/jsPDF).


Updates `picomatch` from 2.3.1 to 2.3.2
- [Release notes](https://github.com/micromatch/picomatch/releases)
- [Changelog](https://github.com/micromatch/picomatch/blob/master/CHANGELOG.md)
- [Commits](https://github.com/micromatch/picomatch/compare/2.3.1...2.3.2)

Updates `picomatch` from 4.0.3 to 4.0.4
- [Release notes](https://github.com/micromatch/picomatch/releases)
- [Changelog](https://github.com/micromatch/picomatch/blob/master/CHANGELOG.md)
- [Commits](https://github.com/micromatch/picomatch/compare/2.3.1...2.3.2)

Updates `yaml` from 1.10.2 to 1.10.3
- [Release notes](https://github.com/eemeli/yaml/releases)
- [Commits](https://github.com/eemeli/yaml/compare/v1.10.2...v1.10.3)

Updates `yaml` from 2.8.1 to 2.8.3
- [Release notes](https://github.com/eemeli/yaml/releases)
- [Commits](https://github.com/eemeli/yaml/compare/v1.10.2...v1.10.3)

Updates `flatted` from 3.3.3 to 3.4.2
- [Commits](https://github.com/WebReflection/flatted/compare/v3.3.3...v3.4.2)

Updates `jspdf` from 4.2.0 to 4.2.1
- [Release notes](https://github.com/parallax/jsPDF/releases)
- [Changelog](https://github.com/parallax/jsPDF/blob/master/RELEASE.md)
- [Commits](https://github.com/parallax/jsPDF/compare/v4.2.0...v4.2.1)

---
updated-dependencies:
- dependency-name: picomatch
  dependency-version: 2.3.2
  dependency-type: indirect
  dependency-group: npm_and_yarn
- dependency-name: picomatch
  dependency-version: 4.0.4
  dependency-type: indirect
  dependency-group: npm_and_yarn
- dependency-name: yaml
  dependency-version: 1.10.3
  dependency-type: indirect
  dependency-group: npm_and_yarn
- dependency-name: yaml
  dependency-version: 2.8.3
  dependency-type: indirect
  dependency-group: npm_and_yarn
- dependency-name: flatted
  dependency-version: 3.4.2
  dependency-type: indirect
  dependency-group: npm_and_yarn
- dependency-name: jspdf
  dependency-version: 4.2.1
  dependency-type: indirect
  dependency-group: npm_and_yarn
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-04-08 01:56:23 +00:00
Dmitry Ng 36ac0c876b Merge pull request #234 from octo-patch/fix/issue-220-user-defined-provider-precedence
fix: user-defined providers take precedence over built-in providers
2026-04-08 04:58:07 +04:00
Dmitry Ng 1a51a7d70a Merge pull request #237 from vxcontrol/dependabot/npm_and_yarn/frontend/npm_and_yarn-c4bc6a0a9e
build(deps-dev): bump vite from 7.2.2 to 7.3.2 in /frontend in the npm_and_yarn group across 1 directory
2026-04-08 04:36:53 +04:00
Dmitry Ng fc91758b9c Merge pull request #238 from vxcontrol/feature/frontend
Add Analytics Dashboard and Template Management System
2026-04-08 04:36:05 +04:00
Dmitry Ng 089dcb36b4 feat: implement flow templates management 2026-04-08 03:34:32 +03:00
Dmitry Ng 445f131430 chore: remove unused frontend Dockerfile, entrypoint script, and Nginx configuration files 2026-04-08 00:54:35 +03:00
Dmitry Ng 51cb312b57 Merge pull request #230 from mason5052/test/server-models-validation
test: add unit tests for key server/models validation types
2026-04-08 01:20:43 +04:00
Dmitry Ng 9f882276a2 Merge pull request #232 from vxcontrol/dependabot/go_modules/backend/go_modules-a978bc362c
build(deps): bump github.com/go-jose/go-jose/v4 from 4.1.3 to 4.1.4 in /backend in the go_modules group across 1 directory
2026-04-08 01:15:36 +04:00
Sergey Kozyrenko fe9ba1a89e feat: update terminal 2026-04-07 23:14:34 +07:00
mason5052 1b2681cd99 test: shadow loop variable to prevent parallel subtest capture
Add tt := tt inside each for-range loop before t.Run to ensure
parallel subtests capture their own immutable copy of the test case.
2026-04-06 19:15:29 -04:00
dependabot[bot] 04a054431e build(deps-dev): bump vite
Bumps the npm_and_yarn group with 1 update in the /frontend directory: [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite).


Updates `vite` from 7.2.2 to 7.3.2
- [Release notes](https://github.com/vitejs/vite/releases)
- [Changelog](https://github.com/vitejs/vite/blob/v7.3.2/packages/vite/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite/commits/v7.3.2/packages/vite)

---
updated-dependencies:
- dependency-name: vite
  dependency-version: 7.3.2
  dependency-type: direct:development
  dependency-group: npm_and_yarn
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-04-06 20:24:41 +00:00
salecharohitandClaude Sonnet 4.6 264116827d feat(bedrock): auto-seed provider from BEDROCK_CONFIG_PATH on startup
- Add Name field to ProviderConfig; YAML name: key sets the provider
  name shown in the UI (e.g. glm_flash)
- Add SeedDefaultProviders to ProviderController: upserts the Bedrock
  provider into the DB for all existing users at startup and lazily for
  new users on their first Settings page visit
- Editing the YAML and restarting PentAGI automatically propagates new
  values with no UI interaction required
- Simplify to a single BEDROCK_CONFIG_PATH variable: compose uses it as
  the host-side volume mount path and translates it to the fixed
  container path via :+ substitution, eliminating PENTAGI_BEDROCK_CONFIG_PATH
- Fix bedrock_test.go: pass &config.Config{} to DefaultProviderConfig
  after its signature was updated to accept a config argument

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 15:19:54 +05:30
salecharohitandClaude Sonnet 4.6 b1b606df7a fix(docker): align BEDROCK_CONFIG_PATH pattern with existing providers
Follow the same two-variable convention used for LLM_SERVER_CONFIG_PATH
and OLLAMA_SERVER_CONFIG_PATH:
- PENTAGI_BEDROCK_CONFIG_PATH: host-side path to the YAML file, mounted
  into the container at /opt/pentagi/conf/bedrock.provider.yml
- BEDROCK_CONFIG_PATH: in-container path passed to the app, set to
  /opt/pentagi/conf/bedrock.provider.yml when using the above

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 12:46:47 +05:30
salecharohitandClaude Sonnet 4.6 aeeb98dd00 fix(docker): hardcode BEDROCK_CONFIG_PATH in-container path in compose
Instead of passing BEDROCK_CONFIG_PATH through from the host env (which
required users to know the internal container path), set it directly to
the fixed mount point /opt/pentagi/conf/bedrock.provider.yml in compose.
Users now only need PENTAGI_BEDROCK_CONFIG_PATH pointing to their host
file — consistent with how PENTAGI_LLM_SERVER_CONFIG_PATH and
PENTAGI_OLLAMA_SERVER_CONFIG_PATH work.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 12:41:43 +05:30
Octopus a12ffe9c01 fix: user-defined providers take precedence over built-in providers (fixes #220) 2026-04-05 09:44:53 +08:00
salecharohitandClaude Sonnet 4.6 4be1a26cba docs: document BEDROCK_CONFIG_PATH in README
Add BEDROCK_CONFIG_PATH to the AWS Bedrock Provider Configuration table
and the full env reference section to document the custom YAML config
path feature added in the feature branch.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-04 22:49:44 +05:30
salecharohitandClaude Sonnet 4.6 36b7981240 feat(bedrock): add BEDROCK_CONFIG_PATH support for custom provider config
Mirrors the existing LLM_SERVER_CONFIG_PATH / OLLAMA_SERVER_CONFIG_PATH
pattern so operators can supply a YAML file that overrides the built-in
embedded bedrock/config.yml without modifying source code.

Changes:
- config.go: add BedrockConfig field mapped to BEDROCK_CONFIG_PATH env var
- bedrock/bedrock.go: DefaultProviderConfig now accepts *config.Config;
  reads from BedrockConfig path when set, falls back to embedded config.yml
- providers.go, cmd/ctester/main.go: pass cfg to updated DefaultProviderConfig
- docker-compose.yml: wire BEDROCK_CONFIG_PATH env var and mount
  ${PENTAGI_BEDROCK_CONFIG_PATH:-./glm_flash_bedrock.yml} into the container
- .env.example: document the new BEDROCK_CONFIG_PATH variable
- glm_flash_bedrock.yml: example config exporting the glm_flash DB provider
  (zai.glm-4.7-flash via Bedrock) as a portable YAML file

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-04 22:42:17 +05:30
dependabot[bot] 17a76e46e2 build(deps): bump github.com/go-jose/go-jose/v4
Bumps the go_modules group with 1 update in the /backend directory: [github.com/go-jose/go-jose/v4](https://github.com/go-jose/go-jose).


Updates `github.com/go-jose/go-jose/v4` from 4.1.3 to 4.1.4
- [Release notes](https://github.com/go-jose/go-jose/releases)
- [Commits](https://github.com/go-jose/go-jose/compare/v4.1.3...v4.1.4)

---
updated-dependencies:
- dependency-name: github.com/go-jose/go-jose/v4
  dependency-version: 4.1.4
  dependency-type: indirect
  dependency-group: go_modules
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-04-03 04:22:29 +00:00
Dmitry Ng d56952653f Merge pull request #231 from mason5052/test/schema-validation
test: add unit tests for schema package JSON Schema validation
2026-04-02 11:08:46 +04:00
Sergey Kozyrenko 53ea23e49e feat: dashboard 2026-04-02 00:17:30 +07:00
mason5052 8ddc25f411 test: add failure-path coverage for schema validation
Add missing negative-path tests:
- Schema.Valid() with invalid $ref that fails compilation
- GetValidator() with same invalid schema returns error
- ValidateBytes() with malformed JSON input returns error
2026-03-31 21:54:51 -04:00
mason5052 62dbefdd25 test: fill coverage gaps in server/models validation tests
Add missing test coverage identified by cross-review:

New files:
- assistants_test.go: AssistantStatus enum, Assistant struct, CreateAssistant,
  PatchAssistant (stop/input actions), AssistantFlow nested validation
- prompts_test.go: PromptType enum (8 valid constants from templates pkg),
  Prompt struct, PatchPrompt validation

Extended existing files:
- users_test.go: add AuthCallback positive-path test, UserRolePrivileges
  validation, fix brittle double-call assertion in UserPreferences test
- api_tokens_test.go: add APITokenWithSecret validation (valid, invalid
  embedded token, invalid JWT)
- flows_test.go: add Flow.Valid, FlowTasksSubtasks.Valid,
  FlowContainers.Valid, Task.Valid, TaskSubtasks.Valid, Subtask.Valid,
  Container.Valid with valid/invalid/missing-field cases
2026-03-31 21:53:39 -04:00
mason5052 cc0260b205 test: add unit tests for schema package JSON Schema validation
Add comprehensive test coverage for the schema package including
Schema validation, JSON Schema Draft 7 compilation, document validation,
database serialization, and custom Type marshaling.

Tests cover:
- Schema.Valid() with various schema types (string, object, array, etc.)
- Schema.GetValidator() compilation
- Schema.ValidateString/ValidateBytes/ValidateGo with valid and invalid docs
- Schema.Value()/Scan() database serialization round-trip
- Type.MarshalJSON() including object auto-properties and ExtProps
- Type.UnmarshalJSON() including ExtProps extraction
- Pattern, enum, and array constraint validation
- scanFromJSON helper with string, bytes, and error cases
2026-03-31 20:37:16 -04:00
mason5052 5d4638e79d test: add unit tests for server/models validation functions
Add comprehensive test coverage for the server/models package validation
logic including enum types, struct validators, and custom validators.

Test files added:
- users_test.go: UserStatus, UserType, Login, Password, User,
  UserPassword, AuthCallback, UserRole, UserPreferences validation
- providers_test.go: ProviderType, Provider, CreateProvider,
  PatchProvider, ProviderInfo validation
- api_tokens_test.go: TokenStatus, APIToken, CreateAPITokenRequest,
  UpdateAPITokenRequest, APITokenClaims validation
- flows_test.go: FlowStatus, TaskStatus, SubtaskStatus, ContainerStatus,
  ContainerType, Role, Privilege, RolePrivileges, PatchFlow validation
- init_test.go: Custom validators (stpass, vmail, oauth_min_scope,
  solid, semver, semverex) and scanFromJSON helper
2026-03-31 20:36:51 -04:00
Dmitry Ng e8d49de9af Merge pull request #228 from vxcontrol/dependabot/npm_and_yarn/frontend/npm_and_yarn-127d3e4132
Bump the npm_and_yarn group across 1 directory with 4 updates
2026-03-29 22:02:51 +04:00
+7 790da20c13 docs: add CONTRIBUTORS.md to acknowledge all project contributors
This document recognizes all individuals who contributed to PentAGI
during its development from January 2025 to March 2026.

Co-authored-by: mason5052 <ehehwnwjs5052@gmail.com>
Co-authored-by: niuqun2003 <niuqun2003@gmail.com>
Co-authored-by: Priyanka Singh <priyankasingh15102004@gmail.com>
Co-authored-by: Alex-wuhu <yanglongwei06@gmail.com>
Co-authored-by: liri-ha <258306986+liri-ha@users.noreply.github.com>
Co-authored-by: manusjs <manusjs@users.noreply.github.com>
Co-authored-by: stoykovstoyk <stoykov.stoyk@gmail.com>
Co-authored-by: Kai Kreuzer <kai@openhab.org>
Co-authored-by: Mriganka Dey <mriganka.dey@joulestowatts.com>
Co-authored-by: Salman Muin Kayser Chishti <13schishti@gmail.com>
Co-authored-by: Vaibhavee Singh <vaibhaveesingh89@gmail.com>
Co-authored-by: Peter Dave Hello <hsu@peterdavehello.org>
Co-authored-by: S.B <30941141+s-b-repo@users.noreply.github.com>
Co-authored-by: SkyFlyingMouse <248163859+SkyFlyingMouse@users.noreply.github.com>
Co-authored-by: haosenwang1018 <167664334+haosenwang1018@users.noreply.github.com>
Co-authored-by: Tony Xu <hhktony@gmail.com>
2026-03-29 20:46:55 +03:00
Dmitry Ng 600419bed3 feat: add license compliance documentation and reporting tools
- Introduce CONTRIBUTING.md for license compliance guidelines for developers.
- Update Dockerfile to generate license reports for frontend and backend dependencies.
- Add scripts for generating license reports and include them in the Docker build process.
- Create README.md and .gitignore files in the licenses directory for better organization.
- Update go.mod and go.sum to use the latest versions of vxcontrol dependencies.

This enhances the project's compliance with licensing requirements and improves dependency management.
2026-03-29 18:48:06 +03:00
Dmitry Ng c8cd0e68f9 feat: add Docker host network mode support and improve agent terminal execution
- Add host network mode support in Docker client (DOCKER_NETWORK=host)
- Update documentation for network modes (bridge vs host)
- Enhance OOB port allocation guidance with mandatory directives
- Improve terminal command execution descriptions (detach, timeout)
- Fix MSF workflow issues: add process isolation rules and RPC daemon patterns
- Add terminal execution mechanics to adviser prompts for better monitoring
- Update installer locale with host network mode explanation

Fixes agent issues with msfconsole hanging, port conflicts, and process isolation.
2026-03-29 15:53:30 +03:00
dependabot[bot] 1b9a6f4824 Bump the npm_and_yarn group across 1 directory with 4 updates
Bumps the npm_and_yarn group with 4 updates in the /frontend directory: [picomatch](https://github.com/micromatch/picomatch), [yaml](https://github.com/eemeli/yaml), [flatted](https://github.com/WebReflection/flatted) and [jspdf](https://github.com/parallax/jsPDF).


Updates `picomatch` from 2.3.1 to 2.3.2
- [Release notes](https://github.com/micromatch/picomatch/releases)
- [Changelog](https://github.com/micromatch/picomatch/blob/master/CHANGELOG.md)
- [Commits](https://github.com/micromatch/picomatch/compare/2.3.1...2.3.2)

Updates `picomatch` from 4.0.3 to 4.0.4
- [Release notes](https://github.com/micromatch/picomatch/releases)
- [Changelog](https://github.com/micromatch/picomatch/blob/master/CHANGELOG.md)
- [Commits](https://github.com/micromatch/picomatch/compare/2.3.1...2.3.2)

Updates `yaml` from 1.10.2 to 1.10.3
- [Release notes](https://github.com/eemeli/yaml/releases)
- [Commits](https://github.com/eemeli/yaml/compare/v1.10.2...v1.10.3)

Updates `yaml` from 2.8.1 to 2.8.3
- [Release notes](https://github.com/eemeli/yaml/releases)
- [Commits](https://github.com/eemeli/yaml/compare/v1.10.2...v1.10.3)

Updates `flatted` from 3.3.3 to 3.4.2
- [Commits](https://github.com/WebReflection/flatted/compare/v3.3.3...v3.4.2)

Updates `jspdf` from 4.2.0 to 4.2.1
- [Release notes](https://github.com/parallax/jsPDF/releases)
- [Changelog](https://github.com/parallax/jsPDF/blob/master/RELEASE.md)
- [Commits](https://github.com/parallax/jsPDF/compare/v4.2.0...v4.2.1)

---
updated-dependencies:
- dependency-name: picomatch
  dependency-version: 2.3.2
  dependency-type: indirect
  dependency-group: npm_and_yarn
- dependency-name: picomatch
  dependency-version: 4.0.4
  dependency-type: indirect
  dependency-group: npm_and_yarn
- dependency-name: yaml
  dependency-version: 1.10.3
  dependency-type: indirect
  dependency-group: npm_and_yarn
- dependency-name: yaml
  dependency-version: 2.8.3
  dependency-type: indirect
  dependency-group: npm_and_yarn
- dependency-name: flatted
  dependency-version: 3.4.2
  dependency-type: indirect
  dependency-group: npm_and_yarn
- dependency-name: jspdf
  dependency-version: 4.2.1
  dependency-type: indirect
  dependency-group: npm_and_yarn
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-29 12:26:02 +00:00
1379 changed files with 273486 additions and 92753 deletions

No files matched your search

+12
View File
@@ -1,9 +1,21 @@
frontend/coverage
frontend/dist
frontend/node_modules
frontend/e2e/test-results
frontend/e2e/playwright-report
frontend/e2e/blob-report
frontend/e2e/.auth
**/*.tsbuildinfo
frontend/ssl
**/*.log
**/*.env
**/.env.*
!**/.env.example
**/.DS_Store
**/Thumbs.db
# locally built helper binaries; the image builds its own
backend/ctester
backend/etester
backend/ftester
+252 -7
View File
@@ -1,9 +1,74 @@
# PentAGI Environment Variables
## Core runtime
DEBUG=false
## DATA_DIR defaults to ./data (resolves to /opt/pentagi/data inside the image).
DATA_DIR=
## Optional namespace for instances sharing external resources — one PostgreSQL,
## one worker node, one Neo4j/Graphiti, one Langfuse (empty = standalone instance).
## Must match ^[a-z][a-z0-9_]{0,31}$; invalid value aborts startup.
## NOT derived from it, set per instance yourself: DATA_DIR (sharing it overwrites
## flow data), DOCKER_PORTS_BASE, listen ports, INSTALLATION_ID.
## See backend/docs/config.md -> "Multi-Instance Deployment (TENANT_ID)".
TENANT_ID=
## Base host port for per-flow sandbox port publishing (default 28000).
## Each instance owns [DOCKER_PORTS_BASE, DOCKER_PORTS_BASE+2000).
DOCKER_PORTS_BASE=
## For communication with PentAGI Cloud API
INSTALLATION_ID=
LICENSE_KEY=
# PentAGI stack images settings (docker-compose.yml)
PENTAGI_IMAGE=vxcontrol/pentagi:latest
PGVECTOR_IMAGE=vxcontrol/pgvector:latest
PGEXPORTER_IMAGE=quay.io/prometheuscommunity/postgres-exporter:v0.16.0
SCRAPER_IMAGE=vxcontrol/scraper:latest
## Graphiti stack images (docker-compose-graphiti.yml)
NEO4J_IMAGE=neo4j:5.26.2
GRAPHITI_IMAGE=vxcontrol/graphiti:latest
## Langfuse stack images (docker-compose-langfuse.yml)
LANGFUSE_WORKER_IMAGE=langfuse/langfuse-worker:3
LANGFUSE_WEB_IMAGE=langfuse/langfuse:3
CLICKHOUSE_IMAGE=clickhouse/clickhouse-server:24
MINIO_IMAGE=cgr.dev/chainguard/minio:latest
REDIS_IMAGE=redis:7
POSTGRES_IMAGE=postgres:16
## Observability stack images (docker-compose-observability.yml)
GRAFANA_IMAGE=grafana/grafana:11.4.0
NODE_EXPORTER_IMAGE=prom/node-exporter:v1.8.2
CADVISOR_IMAGE=gcr.io/cadvisor/cadvisor:v0.51.0
OTEL_IMAGE=otel/opentelemetry-collector-contrib:0.116.1
VICTORIAMETRICS_IMAGE=victoriametrics/victoria-metrics:v1.108.1
CLICKSTORE_IMAGE=clickhouse/clickhouse-server:24
LOKI_IMAGE=grafana/loki:3.3.2
JAEGER_IMAGE=jaegertracing/all-in-one:1.56.0
## Which builds updates are offered from: preview (default), stable or nightly.
## preview follows the channels this installation already uses
## stable offers only builds that belong to a published release
## nightly offers the newest build in the channel, release or not
## An unrecognised value falls back to preview.
UPDATE_STRATEGY=
## How often the server checks PentAGI Cloud API for a newer available version
## (shown as a version badge in the web UI), as a Go duration.
UPDATE_CHECK_INTERVAL=
## PentAGI Cloud API endpoint, as host[:port] — the client always uses HTTPS, so a
## scheme here is redundant and a path is ignored. Leave empty for update.pentagi.com.
UPDATE_SERVER_HOST=
## PentAGI Support API endpoint, as host[:port] — the client always uses HTTPS, so a
## scheme here is redundant and a path is ignored. Leave empty for support.pentagi.com.
SUPPORT_SERVER_HOST=
## Allow to interact with user while executing tasks
ASK_USER=
@@ -14,6 +79,17 @@ OPEN_AI_SERVER_URL=https://api.openai.com/v1
ANTHROPIC_API_KEY=
ANTHROPIC_SERVER_URL=https://api.anthropic.com/v1
## Anthropic Workload Identity Federation, used in place of ANTHROPIC_API_KEY when the key is empty.
## The token file is read inside the pentagi container on every exchange, so mount it there. A token carrying jti
## is exchanged only once: the file must hold a new token before each refresh, well within the minted token's lifetime.
## ANTHROPIC_IDENTITY_TOKEN is read once and cannot be rotated, so it suits only runs shorter than its own lifetime.
ANTHROPIC_FEDERATION_RULE_ID=
ANTHROPIC_ORGANIZATION_ID=
ANTHROPIC_SERVICE_ACCOUNT_ID=
ANTHROPIC_WORKSPACE_ID=
ANTHROPIC_IDENTITY_TOKEN_FILE=
ANTHROPIC_IDENTITY_TOKEN=
## Google AI (Gemini) LLM provider
GEMINI_API_KEY=
GEMINI_SERVER_URL=https://generativelanguage.googleapis.com
@@ -26,6 +102,7 @@ BEDROCK_ACCESS_KEY_ID=
BEDROCK_SECRET_ACCESS_KEY=
BEDROCK_SESSION_TOKEN=
BEDROCK_SERVER_URL=
BEDROCK_CONFIG_PATH=
## DeepSeek LLM provider
DEEPSEEK_API_KEY=
@@ -42,19 +119,39 @@ KIMI_API_KEY=
KIMI_SERVER_URL=https://api.moonshot.ai/v1
KIMI_PROVIDER=
## Qwen (Alibaba Cloud DashScope) LLM provider
## Qwen Cloud or Alibaba Cloud Model Studio LLM provider
QWEN_API_KEY=
QWEN_SERVER_URL=https://dashscope-us.aliyuncs.com/compatible-mode/v1
# Gateway prefix: qwen_cloud or dashscope; leave empty for direct DashScope
QWEN_PROVIDER=
## MiniMax LLM provider
MINIMAX_API_KEY=
MINIMAX_SERVER_URL=https://api.minimax.io/v1
MINIMAX_PROVIDER=
## Mistral LLM provider
MISTRAL_API_KEY=
MISTRAL_SERVER_URL=https://api.mistral.ai/v1
MISTRAL_PROVIDER=
## xAI (Grok) LLM provider
XAI_API_KEY=
XAI_SERVER_URL=https://api.x.ai/v1
XAI_PROVIDER=
## Custom LLM provider
LLM_SERVER_URL=
LLM_SERVER_KEY=
LLM_SERVER_MODEL=
LLM_SERVER_PROVIDER=
LLM_SERVER_CONFIG_PATH=
LLM_SERVER_LEGACY_REASONING=
LLM_SERVER_PRESERVE_REASONING=
## Set LLM_SERVER_API_TYPE to azure or azure_ad to talk to an Azure OpenAI deployment;
## leave it empty for a plain OpenAI-compatible endpoint. LLM_SERVER_API_VERSION is the
## api-version Azure requires and is ignored by the plain endpoint.
LLM_SERVER_API_TYPE=
LLM_SERVER_API_VERSION=
## Ollama LLM provider (Local Server or Cloud)
# Local: http://ollama-server:11434, Cloud: https://ollama.com
@@ -73,6 +170,7 @@ EMBEDDING_KEY=
EMBEDDING_MODEL=
EMBEDDING_PROVIDER=
EMBEDDING_BATCH_SIZE=
EMBEDDING_MAX_TEXT_BYTES=
EMBEDDING_STRIP_NEW_LINES=
## Summarizer
@@ -106,7 +204,8 @@ MAX_LIMITED_AGENT_TOOL_CALLS=
## Agent planning step for pentester, coder, installer
AGENT_PLANNING_STEP_ENABLED=
## HTTP proxy to use it in isolation environment
## HTTP proxy for every backend LLM, embedding, search and update-check call (local endpoints included);
## sandboxes, the scraper and Graphiti do not use it
PROXY_URL=
## SSL/TLS Certificate Configuration
@@ -117,6 +216,10 @@ EXTERNAL_SSL_INSECURE=
## Default: 600 (10 minutes). Set to 0 to use the default.
HTTP_CLIENT_TIMEOUT=
## Default terminal tool timeout in seconds applied when an agent requests timeout=0 or a negative value.
## Default: 1200 (20 minutes). Range: 1–10800 (up to 3 hours). Values <= 0 or above 10800 are clamped to 10800 (agents always get a finite timeout).
TERMINAL_TOOL_TIMEOUT=
## Scraper URLs and settings
## For Docker (default):
SCRAPER_PUBLIC_URL=
@@ -137,10 +240,15 @@ PENTAGI_DOCKER_SOCKET=
PENTAGI_DOCKER_CERT_PATH=
PENTAGI_LLM_SERVER_CONFIG_PATH=
PENTAGI_OLLAMA_SERVER_CONFIG_PATH=
PENTAGI_BEDROCK_CONFIG_PATH=
## PentAGI security settings
PUBLIC_URL=https://localhost:8443
CORS_ORIGINS=https://localhost:8443
## Reverse proxies whose X-Forwarded-For is believed, comma separated CIDRs.
## Empty means the peer address is the client address.
TRUSTED_PROXIES=
COOKIE_SIGNING_SALT=salt # change this to improve security
## PentAGI internal server settings (inside the container)
@@ -152,6 +260,10 @@ SERVER_SSL_CRT=
SERVER_SSL_KEY=
SERVER_USE_SSL=true
## Go pprof HTTP listener (empty = disabled). Use host:port, e.g. :7777.
## Instances sharing a host network need distinct addresses.
PPROF_ADDR=
## OAuth google
OAUTH_GOOGLE_CLIENT_ID=
OAUTH_GOOGLE_CLIENT_SECRET=
@@ -180,10 +292,20 @@ TRAVERSAAL_API_KEY=
## Tavily search engine API
TAVILY_API_KEY=
## Firecrawl search engine API
## FIRECRAWL_API_URL is optional; leave the default for the cloud API or point it at a self-hosted instance
FIRECRAWL_API_KEY=
FIRECRAWL_API_URL=
## Perplexity search engine API
## PERPLEXITY_MODEL is the model sent to the chat/completions API (sonar,
## sonar-pro, sonar-reasoning, ...); empty or unset defaults to sonar.
## PERPLEXITY_CONTEXT_SIZE is low, medium or high.
## PERPLEXITY_TIMEOUT is seconds to wait for one request; empty uses 120.
PERPLEXITY_API_KEY=
PERPLEXITY_MODEL=
PERPLEXITY_CONTEXT_SIZE=
PERPLEXITY_TIMEOUT=
## SEARXNG search engine API
SEARXNG_URL=
@@ -193,6 +315,11 @@ SEARXNG_SAFESEARCH=0
SEARXNG_TIME_RANGE=
SEARXNG_TIMEOUT=
## Web search internal analytics engine (optional fallback for the web_search tool)
WEB_SEARCH_INTERNAL_ENABLED=false
WEB_SEARCH_INTERNAL_MAX_SITES=5
WEB_SEARCH_INTERNAL_MAX_SITE_BYTES=10240
## Langfuse observability settings
LANGFUSE_BASE_URL=
LANGFUSE_PROJECT_ID=
@@ -208,35 +335,153 @@ DOCKER_TLS_VERIFY=
DOCKER_CERT_PATH=
## Docker settings inside primary terminal container
DOCKER_INSIDE=true # enable to use docker socket
# SECURITY NOTE: DOCKER_INSIDE=true mounts the host Docker socket into every
# sandbox container so agents can launch sub-containers (Docker-in-Docker).
# This grants any process inside the sandbox unrestricted access to the Docker
# API, which can be exploited via prompt injection to escape the sandbox and
# reach the host (issue #337). Only enable this when DinD is required and you
# understand the risk. Consider using a least-privilege socket proxy such as
# https://github.com/Tecnativa/docker-socket-proxy instead of the raw socket.
DOCKER_INSIDE=false # enable to use docker socket (see security note above; default false)
DOCKER_NET_ADMIN=true # enable to use net_admin capability
DOCKER_SOCKET=/var/run/docker.sock # path on host machine
## Docker daemon the WORKER CONTAINER itself talks to (only used when DOCKER_INSIDE=true).
## Injected into the sandbox as DOCKER_HOST / DOCKER_TLS_VERIFY / DOCKER_CERT_PATH.
## Setting DOCKER_INSIDE_HOST also stops auto-detecting and mounting the host socket,
## so an agent reaches only the daemon you designate — unless DOCKER_SOCKET is set
## explicitly, which still takes precedence and is mounted as before.
## DOCKER_INSIDE_CERT_PATH is resolved on the WORKER NODE and bind-mounted read-only
## at the same path inside the container.
DOCKER_INSIDE_HOST=
DOCKER_INSIDE_TLS_VERIFY=
DOCKER_INSIDE_CERT_PATH=
## Sandbox isolation test. Runs ONCE at startup and nowhere else. Its only effect
## is whether agents get Docker at all: PentAGI launches one worker exactly the way
## a flow does, checks that its daemon is separate from PentAGI's own and refuses
## host-escape requests, and removes it. A sandbox that fails the test is turned
## OFF and the log says which check decided it -- PentAGI still starts. Off by
## default, and then the log warns the isolation was never measured. Needs the
## separate-daemon arrangement of examples/guides/worker_node.md.
DOCKER_INSIDE_POLICY_TESTS=false
DOCKER_NETWORK=
DOCKER_WORK_DIR=
DOCKER_PUBLIC_IP=0.0.0.0 # public ip of host machine
DOCKER_DEFAULT_IMAGE=
DOCKER_DEFAULT_IMAGE_FOR_PENTEST=
## Worker the startup sandbox check runs in, and the image it pulls into the
## sandbox to prove an agent could. Small on purpose: the check pays for it on
## every start. Only used when DOCKER_INSIDE_POLICY_TESTS=true.
DOCKER_DEFAULT_IMAGE_FOR_TEST=vxcontrol/kali-linux:test
# Comma-separated allow-list for the image the model may choose; empty means no restriction
DOCKER_ALLOWED_IMAGES=
# "llm" (default) lets the model choose the image, "fixed" always uses the pentest image
DOCKER_IMAGE_SELECTION_MODE=
# Provider used to repeat a call that the flow's own provider failed; empty disables it
LLM_FALLBACK_PROVIDER=
# Postgres (pgvector) settings
PENTAGI_POSTGRES_USER=postgres
PENTAGI_POSTGRES_PASSWORD=postgres # change this to improve security
PENTAGI_POSTGRES_DB=pentagidb
## Postgres (pgvector) connection pool settings
DATABASE_MAX_OPEN_CONNS=
DATABASE_MAX_IDLE_CONNS=
DATABASE_VECTOR_MAX_CONNS=
## Postgres schema handling, only used when TENANT_ID is set (Supabase needs
## DATABASE_EXTENSIONS_SCHEMA=extensions; its pooler may need the other one).
## See backend/docs/config.md -> "Multi-Instance Deployment (TENANT_ID)".
DATABASE_EXTENSIONS_SCHEMA=
DATABASE_SEARCH_PATH_VIA_OPTIONS=
## Graphiti knowledge graph settings
## Set GRAPHITI_ENABLED=true and GRAPHITI_URL=http://graphiti:8000 to enable embedded Graphiti
GRAPHITI_ENABLED=false
GRAPHITI_TIMEOUT=30
GRAPHITI_URL=
GRAPHITI_MODEL_NAME=
GRAPHITI_CPUS=2.0
GRAPHITI_MEMORY=2G
## Graphiti LLM provider preset: openai, gemini, custom, or litellm.
## Model and request settings are loaded from examples/graphiti/<provider>.yaml.
## OpenAI, Gemini, and custom providers reuse the corresponding credentials above.
## Keep this set to llm_configs only when the adjacent graphiti directory is installed.
## Older .env files omit it, so a newer compose file cannot shadow built-in configs
## with an empty host directory.
## Override the host path for development deployments when needed.
GRAPHITI_CONFIG_PATH=./graphiti
GRAPHITI_CONFIG_DIR=llm_configs
GRAPHITI_LLM_CLIENT_TYPE=openai
GRAPHITI_LITELLM_BASE_URL=
GRAPHITI_LITELLM_API_KEY=
## Use the shared EMBEDDING_URL, EMBEDDING_KEY, and EMBEDDING_MODEL settings above.
## Graphiti requires an OpenAI-compatible embedding endpoint. When disabled,
## Graphiti uses the selected LLM provider credentials instead.
GRAPHITI_SEPARATE_EMBEDDING=false
## Graphiti runtime and logging
GRAPHITI_SEMAPHORE_LIMIT=20
GRAPHITI_TELEMETRY_ENABLED=false
GRAPHITI_LOG_FORMAT=json
GRAPHITI_LOG_LEVEL=INFO
GRAPHITI_LOG_STDOUT=events
GRAPHITI_FLOW_LOGGER_WARN_COUNT=256
GRAPHITI_DEBUG_RUNTIME_RESOURCES=false
GRAPHITI_SEARCH_SCOPE=flowid
## Graphiti ingestion policy and worker settings
GRAPHITI_INGEST_POLICY_RULES='{"graphiti_search":"REJECT","tool_execution_terminal":"PROCESS","tool_execution_file":"PROCESS"}'
GRAPHITI_INGEST_POLICY_FIELD=both
GRAPHITI_INGEST_POLICY_DEFAULT_ACTION=SKIP_LLM
GRAPHITI_INGEST_USE_GROUP_ACTORS=true
GRAPHITI_INGEST_WORKER_COUNT=16
GRAPHITI_INGEST_LOCK_BY_GROUP_ID=true
GRAPHITI_INGEST_TASK_MAX_RETRIES=1
GRAPHITI_INGEST_TASK_RETRY_DELAY_SEC=2.0
GRAPHITI_INGEST_TASK_TIMEOUT_SEC=0
GRAPHITI_INGEST_QUEUE_MAX_SIZE=0
GRAPHITI_INGEST_DEAD_LETTER_ENABLED=false
## Graphiti extraction and graph-linking settings
GRAPHITI_TAXONOMY_LAYER_PROFILE=STRUCTURAL,EVIDENCE,PROGRESS,ATTEMPT
GRAPHITI_USE_COMBINED_FULL_EXTRACTION=true
GRAPHITI_USE_COMBINED_EXTRACTION=true
GRAPHITI_COMBINED_FULL_GATING_ENABLED=true
GRAPHITI_COMBINED_DIAGNOSTIC_SAMPLES=false
GRAPHITI_ANCHOR_NODE_MODE=smart
GRAPHITI_ANCHOR_NODE_LIMIT=25
GRAPHITI_ANCHOR_MASS_TYPE_LIMIT=10
GRAPHITI_ANCHOR_QUERY_TIMEOUT=10
# Neo4j settings (used by Graphiti stack)
NEO4J_USER=neo4j
NEO4J_DATABASE=neo4j
NEO4J_PASSWORD=devpassword # change this to improve security
NEO4J_URI=bolt://neo4j:7687
NEO4J_CPUS=4.0
NEO4J_MEMORY=4G
## /dev/shm is a separate limit but its actual usage counts toward NEO4J_MEMORY.
NEO4J_SHM_SIZE=4g
NEO4J_NOFILE=65536
## JVM heap/page cache sizing; NEO4J_CPUS/NEO4J_MEMORY only cap the container. Defaults favor
## heap over page cache for a low write-throughput deployment with occasional wide reads.
NEO4J_HEAP_INITIAL_SIZE=2G
NEO4J_HEAP_MAX_SIZE=2G
NEO4J_PAGECACHE_SIZE=1G
## Caps a single transaction so one runaway query fails cleanly instead of exhausting heap.
NEO4J_TRANSACTION_MAX=1G
NEO4J_BOLT_ADVERTISED_ADDRESS=
## Set only when a reverse proxy in front of Neo4j Browser strips/rewrites the Host
## header (so the dynamic Host-header-based advertised address is wrong); format host:port.
NEO4J_HTTP_ADVERTISED_ADDRESS=
## PentAGI image settings
PENTAGI_IMAGE=
## Host directory with static, non-.env-tunable Neo4j/APOC settings and the
## pinned APOC plugin jar (conf/ and plugins/ subdirectories)
NEO4J_DIR=./neo4j
## Scraper network settings
## Default ports: SCRAPER_LISTEN_IP=127.0.0.1, SCRAPER_LISTEN_PORT=9443
+1 -1
View File
@@ -99,7 +99,7 @@ Include any new environment variables, configuration changes, or migration steps
- [ ] I have added tests to cover my changes
- [ ] All new and existing tests pass
- [ ] I have run `go fmt` and `go vet` (for Go code)
- [ ] I have run `npm run lint` (for TypeScript/JavaScript code)
- [ ] I have run `pnpm run lint` (for TypeScript/JavaScript code)
#### Security
- [ ] I have considered security implications
+57
View File
@@ -0,0 +1,57 @@
#!/usr/bin/env bash
# Decide whether a run has to re-check that frontend/src/graphql/types.ts is fresh.
# Echoes `changed=true|false`. Split out of ci.yml so the range selection is testable
# (frontend/e2e/ci-codegen-gate.unit.test.ts drives it over real git fixtures).
#
# Usage: codegen-inputs-changed.sh <event_name> <before_sha> <base_sha> <head_sha>
set -uo pipefail
EVENT="${1:-}"
BEFORE="${2:-}"
BASE_SHA="${3:-}"
HEAD_SHA="${4:-}"
# On pull_request, `before` is the PR's PREVIOUS HEAD, so a follow-up push diffs a range
# that no longer contains the commit that edited the schema — the gate would skip itself
# on every push after the first. The PR's base is the range that always spans the change.
if [ "$EVENT" = "pull_request" ]; then
base="$BASE_SHA"
else
base="$BEFORE"
fi
# When the range can't be resolved (new branch, force-push, tag), check anyway.
# stdout is consumed verbatim as a workflow output, so diagnostics go to stderr.
if [ -z "$base" ] || [ "$base" = "0000000000000000000000000000000000000000" ] \
|| ! git cat-file -e "$base^{commit}" 2>/dev/null; then
echo "reason=unresolvable-base" >&2
echo "changed=true"
exit 0
fi
# The generated file is in the list too: a push that edits only it would otherwise skip
# the check, and the drift surfaces later on someone else's unrelated codegen push.
INPUTS=(
backend/pkg/graph/schema.graphqls
frontend/graphql-schema.graphql
frontend/graphql-codegen.ts
frontend/pnpm-lock.yaml
frontend/src/graphql/types.ts
)
if ! files=$(git diff --name-only --no-renames "$base" "$HEAD_SHA"); then
echo "reason=diff-failed" >&2
echo "changed=true"
exit 0
fi
for input in "${INPUTS[@]}"; do
case $'\n'"$files"$'\n' in
*$'\n'"$input"$'\n'*)
echo "changed=true"
exit 0
;;
esac
done
echo "changed=false"
+98 -59
View File
@@ -1,13 +1,26 @@
name: Docker build and push
on:
# pull_request so the lint/codegen/test gate runs on fork PRs too: a fork's commits never push to
# this repo, so a push-only trigger let a fork edit the schema without regenerating types.ts (or
# ship a lint/test failure) and merge green, since e2e.yml's tsc build cannot see stale codegen.
# lint-and-test uses no secrets and is fork-safe; docker-build stays gated to main/tags below.
pull_request:
types: [opened, synchronize, reopened]
push:
branches:
- "**"
- main
tags:
- "v[0-9]+.[0-9]+.[0-9]+"
workflow_dispatch:
concurrency:
group: ci-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
permissions:
contents: read
jobs:
lint-and-test:
runs-on: ubuntu-latest
@@ -17,70 +30,81 @@ jobs:
with:
fetch-depth: 0
# Go setup and cache
- name: Verify Node version pins match .nvmrc
run: |
NVMRC="$(tr -dc '0-9.' < frontend/.nvmrc)"
echo "Expected Node: $NVMRC"
grep -q "node:${NVMRC}-slim" Dockerfile || { echo "::error::Dockerfile node tag != .nvmrc ($NVMRC)"; exit 1; }
# Go setup and cache (setup-go's cache:true already covers the build cache
# and the module cache; a second actions/cache restore over the read-only
# ~/go/pkg/mod collides with "File exists" whenever both caches hit)
- name: Set up Go
uses: actions/setup-go@v6
with:
go-version: '1.24'
go-version: "1.26.5"
cache: true
cache-dependency-path: backend/go.sum
# Cache Go dependencies
- name: Go Mod Cache
uses: actions/cache@v5
# pnpm setup
- name: Install pnpm
uses: pnpm/action-setup@v4
with:
path: |
~/.cache/go-build
~/go/pkg/mod
key: ${{ runner.os }}-go-${{ hashFiles('backend/go.sum') }}
restore-keys: |
${{ runner.os }}-go-
package_json_file: frontend/package.json
# Node.js setup and cache
- name: Set up Node.js
uses: actions/setup-node@v6
with:
node-version: '23'
cache: 'npm'
cache-dependency-path: 'frontend/package-lock.json'
# Cache npm dependencies
- name: Get npm cache directory
id: npm-cache-dir
run: echo "dir=$(npm config get cache)" >> $GITHUB_OUTPUT
- name: Cache npm packages
uses: actions/cache@v5
id: npm-cache
with:
path: |
${{ steps.npm-cache-dir.outputs.dir }}
frontend/node_modules
key: ${{ runner.os }}-npm-${{ hashFiles('frontend/package-lock.json') }}
restore-keys: |
${{ runner.os }}-npm-
node-version-file: frontend/.nvmrc
cache: "pnpm"
cache-dependency-path: "frontend/pnpm-lock.yaml"
# Frontend lint and test
- name: Frontend - Install dependencies
if: steps.npm-cache.outputs.cache-hit != 'true'
working-directory: frontend
run: npm ci
continue-on-error: true
run: pnpm install --frozen-lockfile
- name: Frontend - Prettier
working-directory: frontend
run: npm run prettier
continue-on-error: true
run: pnpm run prettier
- name: Frontend - Lint
working-directory: frontend
run: npm run lint
continue-on-error: true
run: pnpm run lint
- name: Frontend - Type check
working-directory: frontend
run: pnpm run typescript
# Only when a codegen input moved. The lockfile is included on purpose: a codegen
# version bump can change the output, and skipping it there would let types.ts go
# stale and fail the next schema push for something its author did not do.
- name: Frontend - Detect GraphQL codegen input changes
id: codegen-inputs
run: |
.github/scripts/codegen-inputs-changed.sh \
'${{ github.event_name }}' \
'${{ github.event.before }}' \
'${{ github.event.pull_request.base.sha }}' \
'${{ github.sha }}' >> "$GITHUB_OUTPUT"
# The app ships the operations compiled into src/graphql/types.ts; regenerate and
# diff so it can't drift from graphql-schema.graphql (the codegen input the stand's
# schema-compat pre-flight validates against).
- name: Frontend - GraphQL codegen is fresh
if: steps.codegen-inputs.outputs.changed == 'true'
working-directory: frontend
run: |
pnpm run graphql:generate
git diff --exit-code src/graphql/types.ts || {
echo "::error file=frontend/src/graphql/types.ts::src/graphql/types.ts is stale — run 'pnpm run graphql:generate' in frontend/ and commit the result"
exit 1
}
- name: Frontend - Test
working-directory: frontend
run: npm run test
continue-on-error: true
run: pnpm run test
# Backend lint and test
- name: Backend - Download dependencies
@@ -88,18 +112,32 @@ jobs:
run: go mod download
continue-on-error: true
# The installer embeds the deployment descriptors it extracts onto a host —
# the compose files, the observability configuration, the Jaeger plugin — and
# that embedded copy is GENERATED from symlinks in cmd/installer/files/links,
# not committed (see cmd/installer/files/.gitignore).
#
# It has to run before the tests, not only before a build: the checker's
# compose-consistency tests read the generated copy, because that copy is what
# a host actually gets. Without this step they fail on a missing file, and an
# installer built in this workflow would ship compose files with the image tags
# hardcoded instead of the ${COMPONENT_IMAGE:-default} variables the update
# mechanism writes into — an update that resolves correctly and then applies
# nothing.
- name: Backend - Generate embedded installer files
working-directory: backend/cmd/installer/files
run: go run generate.go
- name: Backend - Lint
uses: golangci/golangci-lint-action@v9
with:
version: latest
version: v2.12.2
working-directory: backend
args: --timeout=5m --issues-exit-code=0
continue-on-error: true
args: --timeout=5m
- name: Backend - Test
working-directory: backend
run: go test ./... -v
continue-on-error: true
run: go test ./... -race -v
- name: Backend - Test Build
working-directory: backend
@@ -112,17 +150,18 @@ jobs:
PACKAGE_VER=${LATEST_TAG#v}
CURRENT_COMMIT=$(git rev-parse HEAD)
TAG_COMMIT=$(git rev-list -n 1 "$LATEST_TAG" 2>/dev/null || echo "")
if [ "$CURRENT_COMMIT" != "$TAG_COMMIT" ]; then
PACKAGE_REV=$(git rev-parse --short HEAD)
# Fixed width, as in scripts/version.sh: --short widens with the size of the clone.
PACKAGE_REV=$(printf '%s' "$CURRENT_COMMIT" | cut -c1-7)
else
PACKAGE_REV=""
fi
LDFLAGS="-X pentagi/pkg/version.PackageName=pentagi -X pentagi/pkg/version.PackageVer=${PACKAGE_VER} -X pentagi/pkg/version.PackageRev=${PACKAGE_REV}"
echo "Building with version: ${PACKAGE_VER}${PACKAGE_REV:+-$PACKAGE_REV}"
# Build for AMD64
GOOS=linux GOARCH=amd64 go build -trimpath -ldflags "$LDFLAGS" -o /tmp/pentagi-amd64 ./cmd/pentagi
echo "✓ Successfully built for linux/amd64"
@@ -130,11 +169,10 @@ jobs:
# Build for ARM64
GOOS=linux GOARCH=arm64 go build -trimpath -ldflags "$LDFLAGS" -o /tmp/pentagi-arm64 ./cmd/pentagi
echo "✓ Successfully built for linux/arm64"
continue-on-error: true
docker-build:
needs: lint-and-test
if: github.ref == 'refs/heads/master' || startsWith(github.ref, 'refs/tags/v')
if: github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/v')
runs-on: ubuntu-latest
steps:
- name: Checkout
@@ -158,16 +196,17 @@ jobs:
# Get latest tag version (without 'v' prefix)
LATEST_TAG=$(git describe --tags --abbrev=0 2>/dev/null || echo "v0.0.0")
VERSION=${LATEST_TAG#v}
# Get current commit hash
CURRENT_COMMIT=$(git rev-parse HEAD)
# Get commit hash of the latest tag
TAG_COMMIT=$(git rev-list -n 1 "$LATEST_TAG" 2>/dev/null || echo "")
# Set revision only if current commit differs from tag commit
if [ "$CURRENT_COMMIT" != "$TAG_COMMIT" ]; then
PACKAGE_REV=$(git rev-parse --short HEAD)
# Fixed width, as in scripts/version.sh: --short widens with the size of the clone.
PACKAGE_REV=$(printf '%s' "$CURRENT_COMMIT" | cut -c1-7)
echo "revision=${PACKAGE_REV}" >> $GITHUB_OUTPUT
echo "is_release=false" >> $GITHUB_OUTPUT
echo "Building development version: ${VERSION}-${PACKAGE_REV}"
@@ -184,7 +223,7 @@ jobs:
echo "patch=${VERSION}" >> $GITHUB_OUTPUT
echo " Docker tags: latest, ${major}, ${major}.${minor}, ${VERSION}"
fi
echo "version=${VERSION}" >> $GITHUB_OUTPUT
- name: Generate Docker metadata
@@ -193,8 +232,8 @@ jobs:
with:
images: vxcontrol/pentagi
tags: |
# For master branch - latest tag
type=raw,value=latest,enable=${{ github.ref == 'refs/heads/master' }}
# For main branch - latest tag
type=raw,value=latest,enable=${{ github.ref == 'refs/heads/main' }}
# For release builds only - tag with major, minor and patch versions
type=raw,value=${{ steps.version.outputs.major }},enable=${{ steps.version.outputs.is_release == 'true' }}
type=raw,value=${{ steps.version.outputs.minor }},enable=${{ steps.version.outputs.is_release == 'true' }}
+199
View File
@@ -0,0 +1,199 @@
# Posts the sticky E2E PR comment. Runs in base-repo context (writable token)
# after the fork-safe E2E workflow completes. Never checks out or executes PR
# code; the only artifact-derived values rendered are numeric counts.
name: E2E report
on:
workflow_run:
workflows: ["E2E"]
types:
- completed
permissions:
actions: read
pull-requests: write
# A cancelled superseded run must not race the report of the run that
# replaced it and become the sticky comment's last writer.
concurrency:
group: e2e-report-${{ github.event.workflow_run.head_repository.full_name }}-${{ github.event.workflow_run.head_branch }}
cancel-in-progress: true
jobs:
comment:
if: >
github.event.workflow_run.event == 'pull_request' &&
github.event.workflow_run.conclusion != 'cancelled'
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: Download results
id: results
continue-on-error: true
uses: actions/download-artifact@v4
with:
name: e2e-results
path: results
run-id: ${{ github.event.workflow_run.id }}
github-token: ${{ github.token }}
# Present only when the visual snapshot step itself failed (a real pixel diff),
# so its download outcome is the precise advisory signal — see visualDiffers below.
- name: Download visual diffs
id: visualdiffs
continue-on-error: true
uses: actions/download-artifact@v4
with:
name: e2e-visual-diffs
path: visual-diffs
run-id: ${{ github.event.workflow_run.id }}
github-token: ${{ github.token }}
- name: Post sticky comment
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
const run = context.payload.workflow_run;
// Match the PR whose head is still this run's — one commit can belong to several PRs, so
// taking the first association (either source) could hand the report to a stale or
// foreign one. Same filter on both paths: workflow_run.pull_requests (empty for forks)
// and the head-SHA lookup that covers them.
// workflow_run.pull_requests carries head.repo.name but no full_name, unlike the API
// lookup — enforce the repo only when it is present, so the primary path still matches.
const isThisRun = (pr) =>
pr.head?.sha === run.head_sha &&
pr.head?.ref === run.head_branch &&
(pr.head?.repo?.full_name == null || pr.head.repo.full_name === run.head_repository?.full_name);
let prNumber = run.pull_requests.find(isThisRun)?.number;
if (!prNumber) {
const { data: prs } = await github.rest.repos.listPullRequestsAssociatedWithCommit({
owner: context.repo.owner,
repo: context.repo.repo,
commit_sha: run.head_sha,
});
prNumber = prs.find(isThisRun)?.number;
}
if (!prNumber) {
core.info(`No PR found for ${run.head_sha}; skipping comment.`);
return;
}
let runJobs = [];
let jobsFetched = false;
try {
const { data: jobs } = await github.rest.actions.listJobsForWorkflowRun({
owner: context.repo.owner,
repo: context.repo.repo,
run_id: run.id,
per_page: 100,
});
runJobs = jobs.jobs;
jobsFetched = true;
} catch (error) {
core.info(`run jobs unavailable: ${error}`);
}
// Only skip when we actually fetched the jobs and this run has no completed mock
// job (e.g. it failed before e2e-mock). A transient jobs-API failure must not be
// mistaken for that and silently leave a stale comment; fall through to results.json.
const mockJob = runJobs.find((job) => /mock/.test(job.name));
if (jobsFetched && (!mockJob || mockJob.conclusion === 'skipped')) {
core.info('No completed mock job in this run; leaving the sticky comment as it is.');
return;
}
// e2e.yml uploads results.json with `if-no-files-found: ignore`, so a run that never
// wrote one publishes no artifact at all: a failed download means the file is absent,
// a successful download with unreadable stats means it is corrupt.
const resultsDownloaded = '${{ steps.results.outcome }}' === 'success';
let statsLine = resultsDownloaded
? 'The results file could not be parsed, so no test counts are available.'
: 'No results artifact was produced for this run.';
let statsRead = false;
let noFailures = false;
try {
const report = JSON.parse(fs.readFileSync('results/results.json', 'utf8'));
const n = (value) => Number(value) || 0;
const { expected, unexpected, flaky, skipped } = report.stats ?? {};
statsLine = `**${n(expected)} passed**, ${n(unexpected)} failed, ${n(flaky)} flaky, ${n(skipped)} skipped.`;
noFailures = n(unexpected) === 0;
statsRead = true;
} catch (error) {
core.info(`results.json unavailable: ${error}`);
}
// The job conclusion is load-bearing, not a nicety: results.json is written before a
// global-timeout abort can be observed (its un-run tests land in `skipped`, so
// `unexpected` stays 0), and only the job's own conclusion reflects the abort. So a
// green needs BOTH zero failures AND a successful job; whenever either source is
// unreadable the verdict is unknown — never a green, and never a red.
const jobFailed = jobsFetched && mockJob?.conclusion !== 'success';
const mockStatus = jobFailed || (statsRead && !noFailures)
? 'fail'
: statsRead && jobsFetched
? 'pass'
: 'unknown';
// Key the advisory on the e2e-visual-diffs artifact (uploaded only when the snapshot
// step itself failed), not on the visual job's conclusion — a tag-guard, install or
// build failure would otherwise read as "snapshots differ".
const visualDiffers = '${{ steps.visualdiffs.outcome }}' === 'success';
const conclusion = mockStatus === 'fail' ? '❌' : mockStatus === 'unknown' || visualDiffers ? '⚠️' : '✅';
const marker = '<!-- e2e-report -->';
const unconfirmedReason = !jobsFetched && !statsRead
? 'neither the workflow jobs API nor `results.json` could be read'
: !jobsFetched
? 'the workflow jobs API was unreachable, so this reflects `results.json` alone, which cannot distinguish a clean pass from a run killed mid-flight'
: '`results.json` could not be read, so this reflects the job conclusion alone and no test counts were checked';
const advisoryLine = mockStatus === 'unknown'
? `⚠️ **Result unconfirmed** — ${unconfirmedReason}. Check the run before merging.`
: visualDiffers
? '⚠️ **Visual snapshots differ** — advisory only, does not block merge. Download the `e2e-visual-diffs` artifact to compare expected / actual / diff (a missing baseline uploads actual only).'
: null;
const body = [
marker,
`### ${conclusion} E2E (mock tier)`,
'',
statsLine,
...(advisoryLine ? ['', advisoryLine] : []),
'',
`[Run + report/trace artifacts](${run.html_url}) · commit ${run.head_sha.slice(0, 7)}`,
'',
'Debug a red run locally: download the `e2e-report` artifact and open the trace with `pnpm exec playwright show-trace <trace.zip>`.',
].join('\n');
const comments = await github.paginate(github.rest.issues.listComments, {
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: prNumber,
per_page: 100,
});
// Author check: anyone can pre-post the marker; only the bot's own
// comment may claim the sticky slot.
const existing = comments.find(
(comment) =>
comment.body?.startsWith(marker) &&
comment.user?.type === 'Bot' &&
comment.user?.login === 'github-actions[bot]',
);
if (existing) {
await github.rest.issues.updateComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: existing.id,
body,
});
} else {
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: prNumber,
body,
});
}
+120
View File
@@ -0,0 +1,120 @@
# Tier 3: real feature stand. Split into its own workflow so the PR gate
# (e2e.yml) never subscribes to `labeled` events — a label must not be able to
# publish a skipped `e2e-mock` check that branch protection would count as
# satisfied. Label-gated + a protected Environment whose required reviewers
# approve before any secret is exposed; even a mislabeled run blocks on a human.
# Fork PRs get Tier 1 only.
name: E2E Stand
on:
pull_request:
types: [labeled]
workflow_dispatch:
permissions:
contents: read
# Keyed on the label too: concurrency is evaluated for the whole run before the job's `if`, so a run
# started by an unrelated label would share this group and cancel an approved stand run mid-flight.
concurrency:
group: e2e-stand-${{ github.event.pull_request.number || github.run_id }}-${{ github.event.label.name }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
e2e-stand:
# GitHub withholds secrets from fork `pull_request` runs: without the fork check a labelled fork
# PR holds reviewers for an environment approval and then fails on empty credentials. Assert repo
# identity rather than negating `head.repo.fork`: a deleted fork sends `head.repo: null`, and
# GitHub coerces null and false alike to 0, so the negation lets that PR through.
if: >
github.event_name == 'workflow_dispatch' ||
(github.event.label.name == 'e2e:stand' &&
github.event.pull_request.head.repo.full_name == github.repository)
runs-on: ubuntu-latest
timeout-minutes: 30
environment: e2e-stand
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Install pnpm
uses: pnpm/action-setup@v4
with:
package_json_file: frontend/package.json
- name: Set up Node.js
uses: actions/setup-node@v6
with:
node-version-file: frontend/.nvmrc
cache: "pnpm"
cache-dependency-path: "frontend/pnpm-lock.yaml"
- name: Install dependencies
working-directory: frontend
run: pnpm install --frozen-lockfile
# Deploy-skew pre-flight: one readable failure instead of dozens of red
# specs when the stand's schema no longer satisfies the frontend contract.
- name: Schema-compat pre-flight
working-directory: frontend
run: node e2e/tools/schema-compat.mjs
env:
E2E_BASE_URL: ${{ secrets.E2E_STAND_URL }}
E2E_USER: ${{ secrets.E2E_STAND_USER }}
E2E_PASSWORD: ${{ secrets.E2E_STAND_PASSWORD }}
- name: Install Playwright browsers
working-directory: frontend
run: pnpm exec playwright install --with-deps chromium
# The config scopes the stand tier to @stand specs — no CLI grep to
# drift out of sync with the tags.
- name: Run stand smoke
working-directory: frontend
run: E2E_TIER=stand npx playwright test -c e2e/playwright.config.ts
env:
E2E_BASE_URL: ${{ secrets.E2E_STAND_URL }}
E2E_USER: ${{ secrets.E2E_STAND_USER }}
E2E_PASSWORD: ${{ secrets.E2E_STAND_PASSWORD }}
# Traces, videos and screenshots are disabled on this tier. results.json still
# embeds the stand URL (baseURL in navigation/locator error messages) and the
# user (in locator text) on a failing run, so redact the secrets before the
# public-repo upload — GitHub masks secrets in logs, never in artifacts.
- name: Redact secrets from report
id: redact
if: always()
working-directory: frontend
run: |
node -e '
const fs = require("fs");
const f = "e2e/test-results/results.json";
if (!fs.existsSync(f)) process.exit(0);
let s = fs.readFileSync(f, "utf8");
// Derived forms too, not just the raw value: auth.setup.ts builds a locator name from
// the regex-escaped user, so a failed login writes `user@host\.com` into the error —
// and since this redacts the JSON text, that backslash is itself encoded as `\\`.
const regexEscaped = (v) => v.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const jsonEncoded = (v) => JSON.stringify(v).slice(1, -1);
for (const v of [process.env.E2E_BASE_URL, process.env.E2E_USER, process.env.E2E_PASSWORD]) {
if (!v) continue;
const forms = [v, regexEscaped(v), encodeURIComponent(v)];
for (const form of new Set([...forms, ...forms.map(jsonEncoded)])) {
s = s.split(form).join("<redacted>");
}
}
fs.writeFileSync(f, s);
'
env:
E2E_BASE_URL: ${{ secrets.E2E_STAND_URL }}
E2E_USER: ${{ secrets.E2E_STAND_USER }}
E2E_PASSWORD: ${{ secrets.E2E_STAND_PASSWORD }}
- name: Upload report
if: always() && steps.redact.outcome == 'success'
uses: actions/upload-artifact@v4
with:
name: e2e-stand-report
path: frontend/e2e/test-results/results.json
retention-days: 3
if-no-files-found: ignore
+227
View File
@@ -0,0 +1,227 @@
# The fork-safe gate: read-only permissions, no secrets, no write steps.
# PR comments are posted by e2e-report.yml (workflow_run) which runs in
# base-repo context — a fork PR's GITHUB_TOKEN cannot write comments.
name: E2E
on:
pull_request:
# Never subscribe to `labeled`: on a label event the gate jobs would skip,
# and GitHub counts a skipped required check as satisfied — a label could
# supersede a red e2e-mock. The stand tier lives in e2e-stand.yml, which owns
# the `labeled` trigger.
types: [opened, synchronize, reopened]
push:
branches:
- main
tags:
- "v[0-9]+.[0-9]+.[0-9]+"
schedule:
- cron: "0 3 * * *"
workflow_dispatch:
inputs:
tier:
description: "Extra tier to run on top of mock + visual (stand tier: dispatch E2E Stand)"
type: choice
options:
- none
- local
default: local
permissions:
contents: read
# Keyed on the PR number (not the branch name — two fork PRs named identically
# would cancel each other) so successive pushes to the same PR supersede each other.
concurrency:
group: e2e-${{ github.event.pull_request.number || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
e2e-mock:
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Install pnpm
uses: pnpm/action-setup@v4
with:
package_json_file: frontend/package.json
- name: Set up Node.js
uses: actions/setup-node@v6
with:
node-version-file: frontend/.nvmrc
cache: "pnpm"
cache-dependency-path: "frontend/pnpm-lock.yaml"
- name: Install dependencies
working-directory: frontend
run: pnpm install --frozen-lockfile
- name: Install Playwright browsers
working-directory: frontend
run: pnpm exec playwright install --with-deps chromium
- name: Run E2E (mock tier, production bundle)
working-directory: frontend
run: pnpm e2e
- name: Upload results.json
if: always()
uses: actions/upload-artifact@v4
with:
name: e2e-results
path: frontend/e2e/test-results/results.json
retention-days: 7
if-no-files-found: ignore
- name: Upload report and traces
if: always()
uses: actions/upload-artifact@v4
with:
name: e2e-report
path: frontend/e2e/test-results
retention-days: 7
if-no-files-found: ignore
- name: Append trend record
if: always()
continue-on-error: true
working-directory: frontend
run: node e2e/tools/trend.mjs
env:
E2E_TREND_SHA: ${{ github.sha }}
E2E_TREND_REF: ${{ github.head_ref || github.ref_name }}
- name: Upload trend
if: always()
uses: actions/upload-artifact@v4
with:
name: e2e-trend
path: frontend/e2e/test-results/trend.jsonl
retention-days: 90
if-no-files-found: ignore
# Visual snapshots: pinned container = pixel-stable baselines. Advisory —
# never a required check.
e2e-visual:
runs-on: ubuntu-latest
timeout-minutes: 20
container:
image: mcr.microsoft.com/playwright:v1.61.1-noble
steps:
- name: Checkout
uses: actions/checkout@v6
# Compare the container's own Playwright build to @playwright/test rather than a
# hardcoded literal, so bumping the package without re-tagging the image (or vice
# versa) fails here instead of drifting the pixel baselines. Read the version from
# the image's own /ms-playwright/.docker-info: this image ships no global
# playwright, so `npx playwright --version` (before pnpm install) would fetch the
# registry latest and compare the package against that, not against the container.
- name: Verify container image matches @playwright/test
run: |
pkg="$(node -p "require('./frontend/package.json').devDependencies['@playwright/test'].replace(/[^0-9.]/g, '')")"
container="$(node -p "JSON.parse(require('fs').readFileSync('/ms-playwright/.docker-info','utf8')).driverVersion")"
if [ "$pkg" != "$container" ]; then
echo "::error::e2e-visual container ships Playwright $container but @playwright/test is $pkg — bump the container tag to v$pkg-noble and regenerate baselines"
exit 1
fi
- name: Install pnpm
uses: pnpm/action-setup@v4
with:
package_json_file: frontend/package.json
# The dist must be built with the pinned Node, not whatever the
# Playwright container ships — local baselines are built under .nvmrc
# and pixel-stability assumes identically built bundles.
- name: Set up Node.js
uses: actions/setup-node@v6
with:
node-version-file: frontend/.nvmrc
- name: Install dependencies
working-directory: frontend
run: pnpm install --frozen-lockfile
- name: Build
working-directory: frontend
run: pnpm run build
- name: Run visual snapshots
id: snapshots
working-directory: frontend
run: E2E_VISUAL=1 E2E_VISUAL_CONTAINER=1 npx playwright test -c e2e/playwright.config.ts
# The step failing is not the same signal as a snapshot differing: a webServer or build
# failure inside it also exits non-zero and still leaves results.json behind, which would
# publish the artifact and make the report say "snapshots differ". Look for the diff images.
- name: Detect snapshot diffs
id: diffs
if: failure() && steps.snapshots.outcome == 'failure'
working-directory: frontend
run: |
# -actual.png too: a missing baseline fails the test but writes no diff image, and only the
# snapshot matcher writes either name — a non-snapshot failure leaves test-failed-N.png.
if find e2e/test-results \( -name '*-diff.png' -o -name '*-actual.png' \) -print -quit | grep -q .; then
echo "found=true" >> "$GITHUB_OUTPUT"
else
echo "found=false" >> "$GITHUB_OUTPUT"
fi
# Its presence is the precise "snapshots differ" signal the report keys the advisory on.
- name: Upload diffs
if: always() && steps.diffs.outputs.found == 'true'
uses: actions/upload-artifact@v4
with:
name: e2e-visual-diffs
path: frontend/e2e/test-results
retention-days: 7
if-no-files-found: ignore
# Tier 2: branch-built image + isolated compose stack + the mock-LLM agent
# loop. Not part of the PR gate — nightly and on-demand only.
e2e-local:
if: >
github.event_name == 'schedule' ||
(github.event_name == 'workflow_dispatch' && inputs.tier == 'local')
runs-on: ubuntu-latest
timeout-minutes: 40
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Install pnpm
uses: pnpm/action-setup@v4
with:
package_json_file: frontend/package.json
- name: Set up Node.js
uses: actions/setup-node@v6
with:
node-version-file: frontend/.nvmrc
cache: "pnpm"
cache-dependency-path: "frontend/pnpm-lock.yaml"
- name: Install dependencies
working-directory: frontend
run: pnpm install --frozen-lockfile
- name: Install Playwright browsers
working-directory: frontend
run: pnpm exec playwright install --with-deps chromium
- name: Run Tier 2 (branch image + mock LLM)
run: ./frontend/e2e/tools/run-local-tier.sh
- name: Upload report and traces
if: always()
uses: actions/upload-artifact@v4
with:
name: e2e-local-report
path: frontend/e2e/test-results
retention-days: 7
if-no-files-found: ignore
+12 -1
View File
@@ -7,6 +7,13 @@
backend/tmp
backend/build
backend/data
# locally built helper binaries (cmd/ctester, cmd/etester, cmd/ftester)
backend/ctester
backend/etester
backend/ftester
backend/vendor
backend/cmd/installer/**/log.json
frontend/coverage
frontend/dist
@@ -17,9 +24,13 @@ node_modules
.cursorrules
.cursorignore
.cursor/
.agents/
.playwright-mcp/
skills-lock.json
build/*
data/*
neo4j/*
.bak/*
!.gitkeep
.claude/
@@ -29,7 +40,7 @@ data/*
*.swp
*.swo
*~
__pycache__/
# OS
Thumbs.db
+24 -4
View File
@@ -5,7 +5,8 @@
"type": "go",
"request": "launch",
"name": "Launch Go Backend",
"program": "${workspaceFolder}/backend/cmd/pentagi/main.go",
"program": "${workspaceFolder}/backend/cmd/pentagi/",
"buildFlags": "-ldflags='-X pentagi/pkg/version.PackageName=pentagi -X pentagi/pkg/version.PackageVer=2.1.0 -X pentagi/pkg/version.PackageRev=93e99748'",
"envFile": "${workspaceFolder}/.env",
"env": {
"CORS_ORIGINS": "http://localhost:*,https://localhost:*",
@@ -30,7 +31,7 @@
"type": "node",
"request": "launch",
"name": "Launch Frontend",
"runtimeExecutable": "npm",
"runtimeExecutable": "pnpm",
"runtimeArgs": ["run", "dev"],
"env": {
"VITE_APP_LOG_LEVEL": "DEBUG",
@@ -56,6 +57,7 @@
"envFile": "${workspaceFolder}/.env",
"env": {},
"args": [
"-type", "custom",
// "-type", "openai",
// "-type", "anthropic",
// "-type", "gemini",
@@ -65,6 +67,9 @@
// "-type", "glm",
// "-type", "kimi",
// "-type", "qwen",
// "-type", "minimax",
// "-type", "mistral",
// "-type", "xai",
"-config", "${workspaceFolder}/examples/configs/moonshot.provider.yml",
// "-config", "${workspaceFolder}/examples/configs/deepseek.provider.yml",
// "-config", "${workspaceFolder}/examples/configs/ollama-cloud.provider.yml",
@@ -74,10 +79,16 @@
// "-config", "${workspaceFolder}/examples/configs/ollama-qwen332b-fp16-tc.provider.yml",
// "-config", "${workspaceFolder}/examples/configs/vllm-qwen3.5-27b-fp8.provider.yml",
// "-config", "${workspaceFolder}/examples/configs/vllm-qwen332b-fp16.provider.yml",
// "-config", "${workspaceFolder}/examples/configs/vllm-qwen3.6-27b-fp8.provider.yml",
// "-config", "${workspaceFolder}/examples/configs/vllm-qwen3.8-27b-fp8.provider.yml",
// "-config", "${workspaceFolder}/examples/configs/vllm-mixed.provider.yml",
// "-config", "${workspaceFolder}/examples/configs/hcnsec.provider.yml",
// "-config", "${workspaceFolder}/examples/configs/custom-openai.provider.yml",
// "-config", "${workspaceFolder}/examples/configs/opencode.provider.yml",
// "-config", "${workspaceFolder}/examples/configs/openrouter.provider.yml",
// "-config", "${workspaceFolder}/examples/configs/deepinfra.provider.yml",
// "-config", "${workspaceFolder}/examples/configs/novita.provider.yml",
// "-config", "${workspaceFolder}/examples/configs/xai.provider.yml",
// "-report", "${workspaceFolder}/examples/tests/openai-report.md",
// "-report", "${workspaceFolder}/examples/tests/anthropic-report.md",
// "-report", "${workspaceFolder}/examples/tests/gemini-report.md",
@@ -89,15 +100,24 @@
// "-report", "${workspaceFolder}/examples/tests/ollama-qwen332b-fp16-tc-report.md",
// "-report", "${workspaceFolder}/examples/tests/vllm-qwen3.5-27b-fp8.report.md",
// "-report", "${workspaceFolder}/examples/tests/vllm-qwen332b-fp16-report.md",
// "-report", "${workspaceFolder}/examples/tests/vllm-qwen3.6-27b-fp8.report.md",
// "-report", "${workspaceFolder}/examples/tests/vllm-qwen3.8-27b-fp8.report.md",
// "-report", "${workspaceFolder}/examples/tests/vllm-mixed.report.md",
"-report", "${workspaceFolder}/examples/tests/moonshot-report.md",
// "-report", "${workspaceFolder}/examples/tests/deepseek-report.md",
// "-report", "${workspaceFolder}/examples/tests/glm-report.md",
// "-report", "${workspaceFolder}/examples/tests/kimi-report.md",
// "-report", "${workspaceFolder}/examples/tests/qwen-report.md",
// "-report", "${workspaceFolder}/examples/tests/qwen-cloud-report.md",
// "-report", "${workspaceFolder}/examples/tests/minimax-report.md",
// "-report", "${workspaceFolder}/examples/tests/mistral-report.md",
// "-report", "${workspaceFolder}/examples/tests/hcnsec-report.md",
// "-report", "${workspaceFolder}/examples/tests/custom-openai-report.md",
// "-report", "${workspaceFolder}/examples/tests/opencode-report.md",
// "-report", "${workspaceFolder}/examples/tests/openrouter-report.md",
// "-report", "${workspaceFolder}/examples/tests/deepinfra-report.md",
// "-report", "${workspaceFolder}/examples/tests/novita-report.md",
// "-report", "${workspaceFolder}/examples/tests/xai-report.md",
"-agents", "all",
"-groups", "all",
"-workers", "8",
@@ -133,9 +153,9 @@
"LLM_SERVER_CONFIG_PATH": "${workspaceFolder}/examples/configs/openrouter.provider.yml",
"DATABASE_URL": "postgres://postgres:postgres@localhost:5432/pentagidb?sslmode=disable",
// Langfuse (optional) uncomment to enable
"LANGFUSE_BASE_URL": "http://localhost:4000",
// "LANGFUSE_BASE_URL": "http://localhost:4000",
// Observability (optional) uncomment to enable
"OTEL_HOST": "localhost:8148",
// "OTEL_HOST": "localhost:8148",
},
"args": [
"-flow", "0",
+2 -1
View File
@@ -4,7 +4,8 @@
],
"go.testTimeout": "300s",
"go.testEnvVars": {
"INSTALLER_LOG_FILE": "${workspaceFolder}/build/log.json"
"INSTALLER_LOG_FILE": "${workspaceFolder}/build/log.json",
"DEBUG": "false"
},
"go.testExplorer.enable": true,
"search.useIgnoreFiles": true,
+224 -86
View File
@@ -4,21 +4,66 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
## Core Interaction Rules
1. **Always use English** for all interactions, responses, explanations, and questions with users.
2. **Password Complexity Requirements**: For all password-related development (registration, password reset, API token generation, etc.), the following rules must be enforced:
- Minimum 12 characters
- Must contain at least 1 uppercase letter, 1 lowercase letter, 1 number, and 1 special character
- Common weak passwords (e.g., `password`, `123456`) are prohibited
- Both backend and frontend validation must be implemented; do not rely on frontend validation alone
1. **English** for code, comments, documentation, commit messages and identifiers.
2. **Password Complexity Requirements**: For all password-related development (registration, password reset, API token generation, etc.), enforce the same policy in **both** backend and frontend — never rely on frontend validation alone. Source of truth, keep the two in sync: `backend/pkg/password/policy.go` (the API validator and the installer both call it) and `frontend/src/features/authentication/password-change-form.tsx` (zod schema). The policy:
- Length 8–72 characters (72 **bytes**, the most bcrypt will hash — a longer value fails inside `bcrypt.GenerateFromPassword`, after validation).
- A password is valid if it is **either** 16+ characters (any composition), **or** 8–15 characters containing at least 1 lowercase letter, 1 uppercase letter, 1 number, and 1 special character from `!@#$&*`.
3. **Markdown is prose, not wrapped to a width.** In a `.md` file every paragraph, list item and table row is one line, and the text is split into paragraphs where the thought changes, not where a column ends — the viewer wraps it. Hard wrapping at a fixed width belongs only to comments in code.
## Code Comments
The target: comment lines at 0–2% of a file of logic and about 18% of a file of type declarations; function bodies of hundreds of lines carry none, because the code says what it does.
**A comment earns its place only by carrying what the code cannot show**: why this decision and not the obvious one, what external constraint it works around, why the code exists at all, and — where it genuinely matters — the boundary conditions. It must help maintenance and must not cost readability.
1. **Never restate the code.** If the sentence follows from the line under it, delete it. A doc comment that only repeats an identifier's name is noise; delete it rather than reword it. A comment that repeats the `fmt.Errorf` or log message on the next line is noise too.
2. **Short and dense beats long and dense.** No filler that dilutes the point.
3. **English only.** No Russian, not even a quoted requirement.
4. **No `§`, no requirement ids like `(R37)`, no reference to a document that is not in this repository.** A planning document that is not tracked leaves every pointer into it dead. Do not just delete the token — rewrite the sentence so it stands alone, or delete the comment. "The spec says X" is not a reason; if the reason is real, state the reason. (`§` is a legitimate *string* separator in `backend/cmd/installer/wizard/models/types.go`, and in `markdown-editor-marked.ts` it is the delimiter of the anonymizer placeholder `§*Name*§` that the code reads — neither is a pointer into a document.)
5. **No archaeology.** Git holds the history. Delete "it used to be", "no longer", "before this", "now that X arrives", "was an overgeneralisation". Keep the invariant the story was there to protect. This applies to test *names* as well as test comments.
6. **No meta-commentary** about why the enum has five members rather than four, and no narrative padding that sets a scene or argues with an imagined reviewer.
7. **Rationale lives in one place** — the production code. A `_test.go` gets at most one line saying what a case pins down, and only when the test name does not already say it.
8. **When you change a comment, verify it against the code**, including that the case it describes is still reachable where it sits. A shorter comment that is wrong is worse than the long one.
Keep, and shorten only where it stays unambiguous: package doc comments; the contract of an exported identifier (units, ownership, zero/nil semantics, what the caller must hold); locking, ordering and fail-closed rationale; load-bearing formatting facts; workarounds for a library, protocol, database or browser quirk. Never touch `TODO`/`FIXME`, `//nolint`, `// eslint-disable`, `//go:generate`, `//go:embed`, build tags, or the swaggo `// @...` annotations in `pkg/server/services/` — they are machine-read, not prose.
Two kinds of comment here are machine-read even though they look like prose: the triple-quoted descriptions in `schema.graphqls`, which reach `models_gen.go`, the frontend types and every API consumer; and the comment above a `-- name:` line in `backend/sqlc/models/*.sql`, which is copied verbatim into `pkg/database/*.sql.go`. Both need regeneration after an edit.
### The GraphQL schema
`backend/pkg/graph/schema.graphqls` is a **public** artifact: introspection is on by design, so every triple-quoted description in it ships to clients and bloats the spec. A `#` comment does not ship — the parser drops it, so no client sees it and regeneration leaves every output unchanged — but it is read by everyone who edits the file. The schema carries almost no prose.
**No triple-quoted descriptions anywhere.** Not on types, not on fields, not on operations, not on enum values.
**A comment on a type, when one is genuinely needed, is a single `#` line above it, with no trailing period.** It earns its place only by saying something a client cannot get from the name — for example that the bytes are served over REST and not here, or that every mutation of the shipped template is refused.
**Fields inside types and inputs are never commented.** The name and the type are the documentation; anything more belongs in `backend/docs/` or in the Go code.
**Queries, mutations and subscriptions are never commented.** Their names say what they do; if a name does not, rename it. A single `#` line may head a *group* of operations as a navigation marker, nothing more.
**Enum values are commented only where the name does not give it**, and then about what the value leads to or how the algorithm treats it — one `#` line each.
After editing the schema, regenerate: `gqlgen`, then `swag init` — the swagger document is built from the gqlgen-generated models — and then `pnpm run graphql:generate` in `frontend/`.
**Proving a comment-only change touched no code.** For anything larger than a few files, compare the comment-free token stream of each file against its previous revision rather than reading the diff: a ~30-line Go program over `go/scanner` for `.go`, and `ts.createPrinter({removeComments:true})` over `ts.createSourceFile(...)` for `.ts`/`.tsx` (the raw `ts.createScanner` returns `Unknown` inside JSX and is not a substitute). Prove the checker itself in both directions — plant a one-token change and confirm it fails, plant a comment-only change and confirm it passes — before trusting it. A dead reference inside a string literal (a `t.Errorf` format, a `describe(...)` title) is a code token and needs its own deliberate edit.
## Project Overview
**PentAGI** is an automated security testing platform powered by AI agents. It runs autonomous penetration testing workflows using a multi-agent system (Researcher, Developer, Executor agents) that coordinates LLM providers, Docker-sandboxed tool execution, and a persistent vector memory store.
**PentAGI** is an automated security testing platform powered by AI agents. A `primary_agent` drives a flow, a `generator`/`refiner` pair plans and re-plans its subtasks, and specialist agents — `pentester`, `coder`, `searcher`, `installer`, `memorist`, `adviser`, `reflector`, `enricher`, `reporter`, `summarizer`, `assistant`, `tool_call_fixer` — execute them against LLM providers, Docker-sandboxed tools and a pgvector memory store. The authoritative list of roles is the `MsgchainType` enum in `backend/pkg/database/models.go`, mirrored as `AgentType` in the GraphQL schema.
The application is a monorepo:
The application is a monorepo with:
- **`backend/`** — Go REST + GraphQL API server
- **`frontend/`** — React + TypeScript web UI
- **`observability/`** — Optional monitoring stack configs
- **`observability/`** — optional monitoring stack configs
- **`scripts/`** — version stamping, image entrypoint, helper scripts
## Build & Development Commands
@@ -26,42 +71,101 @@ The application is a monorepo with:
```bash
go mod download # Install dependencies
go build -trimpath -o pentagi ./cmd/pentagi # Build main binary
go test ./... # Run all tests
go test ./pkg/foo/... -v -run TestName # Run specific test
golangci-lint run --timeout=5m # Lint
# Code generation (run after schema changes)
go run github.com/99designs/gqlgen --config ./gqlgen/gqlgen.yml # GraphQL resolvers
swag init -g ../../pkg/server/router.go -o pkg/server/docs/ --parseDependency --parseInternal --parseDepth 2 -d cmd/pentagi # Swagger docs
go generate ./cmd/installer/files/ # REQUIRED once per fresh clone and again after a change under
# cmd/installer/files/links or to a file linked there: fs.go,
# fs_test.go and fs/ in cmd/installer/files/ are generated and
# gitignored; the installer tests fail without them
go build -trimpath -o pentagi ./cmd/pentagi # Quick compile; the binary reports version "ce"
go test ./... # Default test tier (see Testing)
golangci-lint run --timeout=5m # Lint — config backend/.golangci.yml (v2 schema); CI pins v2.12.2
```
A binary whose reported version matters needs the ldflags CI passes: `-ldflags "-X pentagi/pkg/version.PackageVer=<ver> -X pentagi/pkg/version.PackageRev=<short-sha>"`.
### Frontend (run from `frontend/`)
```bash
npm ci # Install dependencies
npm run dev # Dev server on http://localhost:8000
npm run build # Production build
npm run lint # ESLint check
npm run lint:fix # ESLint auto-fix
npm run prettier # Prettier check
npm run prettier:fix # Prettier auto-format
npm run test # Vitest
npm run test:coverage # Coverage report
npm run graphql:generate # Regenerate GraphQL types from schema
nvm use # Node from .nvmrc — corepack does not manage Node
corepack enable # once per Node install: activates the pnpm pinned in package.json
pnpm install
pnpm run dev # Dev server on http://localhost:8000 (VITE_PORT / VITE_HOST / VITE_USE_HTTPS override it)
pnpm run build # tsc -b && vite build
pnpm run typescript # Typecheck only. Use THIS: the root tsconfig is `files: []`, so
# `tsc --noEmit -p tsconfig.json` passes without checking anything
pnpm run lint # ESLint, --max-warnings 0 over src, e2e and scripts
pnpm run prettier # Format check (prettier:fix / lint:fix to write)
pnpm run test # Vitest (test:watch, test:coverage)
pnpm run e2e # Playwright, mock tier (see Testing)
pnpm run graphql:generate # Regenerate src/graphql/types.ts
```
### Docker (run from repo root)
```bash
docker compose up -d # Start core services
docker compose up -d # Core services
docker compose -f docker-compose.yml -f docker-compose-observability.yml up -d # + monitoring
docker compose -f docker-compose.yml -f docker-compose-langfuse.yml up -d # + LLM analytics
docker compose -f docker-compose.yml -f docker-compose-graphiti.yml up -d # + knowledge graph
docker build -t local/pentagi:latest . # Build image
docker build -t local/pentagi:latest . # Image, version "ce"
./scripts/build-image.sh # Image stamped the way
# the pipeline stamps it
```
The full stack runs at `https://localhost:8443` when using Docker Compose. Copy `.env.example` to `.env` and fill in at minimum the database and at least one LLM provider key.
`docker-compose.e2e.yml` is not part of that stack: it is the isolated Tier-2 e2e backend, started under its own compose project (see the header of the file).
The full stack runs at `https://localhost:8443`. Copy `.env.example` to `.env` and fill in at minimum the database and one LLM provider key.
## Testing
**Backend.** `go test ./...` is not the whole suite — one tier sits behind a build tag and is invisible without it:
```bash
PENTAGI_TEST_DSN=postgres://… go test -p 1 -tags postgres ./pkg/database/... ./pkg/timezone/... ./migrations/
```
The tier fails when its variable is unset. `-p 1` because each package migrates into its own schema of one database, while `pg_trgm` is installed once per database: a second package running beside the first fails with `operator class gin_trgm_ops does not exist`. Under a plain `go test ./...` the suites that need a live dependency skip themselves instead — `TEST_DATABASE_URL` for the statement-timeout suite, a reachable Docker daemon for `pkg/docker` — and `go test` without `-v` does not print skips, so a green run can mean they never ran.
**Frontend.** Vitest for units; Playwright for the rest, in three tiers chosen by `E2E_TIER`:
- `mock` (default) — builds the production bundle, serves it, answers every call from a cassette;
- `local` — real backend from `docker-compose.e2e.yml` with a mock LLM (`e2e/tools/run-local-tier.sh`);
- `stand` — a deployed stand, needs `E2E_BASE_URL` and credentials.
Visual snapshots run only inside the pinned Playwright container (`pnpm run e2e:visual`); never on the host. The authoritative verdict of a run is `e2e/test-results/.last-run.json`, not the exit code of a piped command.
**The written playbooks live in `frontend/docs/`** and are worth reading before a manual pass: `e2e.md` (harness, cassettes, tiers, traps), `live-testing.md` (driving the real UI) and `list-detail-pages.md`.
## Writing Tests
Where a test lives and what it is called decide whether anyone finds it again. Each rule below is here because breaking it happened: `pkg/providers` grew 43 test files for 17 source files, one per fix, and seven of them each loaded the model catalogues to check a single property.
**Layout — one test file per source file.**
1. Tests of `x.go` live in `x_test.go`. A test for a bug, a feature or a regression goes into the test file of the source it pins — never into a new file named after the fix, the feature or the ticket. What decides the file is the code the test exists to pin, not the code it happens to execute most, and not the package it was written in: a test of `pconfig.GetOptionsForType` belongs in `pkg/providers/pconfig`.
2. The only other names: `fixtures_test.go` — test doubles shared by more than one test file of the package, and a package's catalogue of realistic sample inputs with their builders (the message chains of `pkg/cast`); `x_ext_test.go` — tests that must be `package <name>_test` because of an import cycle, with one line saying which; `x_live_test.go` — the `//go:build postgres` tier; `x_linux_test.go` and other GOOS/GOARCH suffixes — filename build constraints, never renamed away; `main_test.go` for `TestMain` and the tests of `main.go`; `example_test.go` for `Example…` functions only.
3. A helper defined in one test file and used by another is a hidden dependency: deleting the first breaks the second. Shared doubles live in `fixtures_test.go`, one per role — read it before writing another fake embedder, log recorder or Docker client.
**Names.**
4. `Test<Component>_<Unit>_<Behaviour>`: the source file in CamelCase, the one function or method under test, and what must hold — `TestTerminal_ExecCommand_KeepsPartialOutputOnTimeout`. Then `go test -run 'TestTerminal_'` selects a component and `-run 'TestTerminal_ExecCommand'` a unit. The name promises nothing the assertions do not check. Subtests are lower-case sentences.
**Before adding a test**, find the existing test of the same unit. The same setup with another input is a new row in its table, not a new function; the same input class with the same asserted outcome is a duplicate.
**Every assertion must be able to fail.** Each of these shipped here and stayed green with the behaviour it named removed:
5. A double standing in for a database, log or network write returns `ctx.Err()` once its context is done. One that ignores the context cannot tell a write on a cancelled context from a live one.
6. No expected value computed by the code under test or read from a production constant — a literal.
7. Test through the public entry — `Handle`, `Execute`, the Gin handler via `httptest`, `resolver.Mutation().X` — not the helper behind it, which stays green when the entry stops calling it.
8. Timing: lower bounds, or generous upper bounds as literals; a starved CI runner must not fail the test. Every blocking wait sits in a `select` with a timeout that fails with a reason. Parallel subtests do not share a double that mutates state.
9. `err != nil` does not say which error: use `errors.Is` or the distinguishing text.
**Proof and gates.**
10. A new or rewritten test is shown failing with its behaviour broken: mutate the production line its path takes, see `--- FAIL`, restore. Mutate in a throwaway copy of the tree — an interrupted script once left production code mutated in the working copy.
11. Run the package with `-race` — CI runs `go test ./... -race` — and without `-trimpath`, which breaks tests that open source files (`pkg/providers` parses `pkg/database/models.go`).
12. Renaming or moving a test file updates every document that names it, this one included, in the same change.
13. A test passes on any developer's machine, so it never depends on that machine's timezone, locale or installation. Build times in an explicit zone — `time.UTC`, or `Asia/Riyadh` (+03:00, no DST) where a non-zero offset matters — import `_ "time/tzdata"` wherever a zone is loaded by name, and never assert on what a local server happens to carry (its zone catalogue, its version). Prove a test that touches dates under `TZ=America/Los_Angeles`, `TZ=Asia/Shanghai` and `TZ=Pacific/Kiritimati`, and on the frontend also under `LC_ALL=zh_CN.UTF-8`; the Go test cache does not key on `TZ`, so run with `-count=1` or a zone-bound test comes back `(cached) ok`.
14. Coverage is not test strength: statement coverage of `pkg/csum` rose while 38% of its mutants still went unnoticed. A package that implements an algorithm over structured input — `pkg/cast` parsing, `pkg/csum` summarisation — is tested end to end on realistic inputs, step by step, with an exact assertion after every step, and its strength is measured by a mutation sweep, before and after any test is merged or deleted. Run that sweep one mutant at a time and cap each test binary's memory and time in its own process group: a mutated loop counter can allocate gigabytes in seconds, and killing `go test` leaves its test binary running.
## Architecture
@@ -69,82 +173,116 @@ The full stack runs at `https://localhost:8443` when using Docker Compose. Copy
| Package | Role |
|---|---|
| `cmd/pentagi/` | Main entry point; initializes config, DB, server |
| `pkg/config/` | Environment-based config parsing |
| `pkg/server/` | Gin router, middleware, auth (JWT/OAuth2/API tokens), Swagger |
| `pkg/controller/` | Business logic for REST endpoints |
| `pkg/graph/` | gqlgen GraphQL schema (`schema.graphqls`) and resolvers |
| `pkg/database/` | GORM models, SQLC queries, goose migrations |
| `pkg/providers/` | LLM provider adapters (OpenAI, Anthropic, Gemini, Bedrock, Ollama, etc.) |
| `pkg/tools/` | Penetration testing tool integrations |
| `pkg/docker/` | Docker SDK wrapper for sandboxed container execution |
| `pkg/terminal/` | Terminal session and command execution management |
| `pkg/queue/` | Async task queue |
| `pkg/csum/` | Chain summarization for LLM context management |
| `pkg/graphiti/` | Knowledge graph (Neo4j via Graphiti) integration |
| `pkg/observability/` | OpenTelemetry tracing, metrics, structured logging |
| `cmd/pentagi/` | Entry point: config, tenant schema, DB pools, goose migrations, telemetry, Docker, providers, flow restore, HTTP server |
| `pkg/config/` | One env-tagged `Config`; validates `TENANT_ID` and derives the schema name. The widest dependency in the backend |
| `pkg/server/` | Gin engine and middleware. The work is in its subpackages: `services/` REST handlers, `models/` DTOs and their `Valid()` gates, `auth/` sessions + token JWTs + privilege checks, `oauth/`, `rdb/` filtering and paging, `response/`, `update/` |
| `pkg/controller/` | Flow/task/subtask agent runtime: spawns and stops workers, publishes agent, message, tool-call, terminal and screenshot logs to the subscription hub |
| `pkg/graph/` | gqlgen schema (`schema.graphqls`), resolvers, `model/` (generated) and `subscriptions/` (the pub/sub hub) |
| `pkg/database/` | sqlc-generated queries and models, tenant helpers, statement timeouts, and the legacy GORM handle. GORM *models* live in `pkg/server/models/` |
| `pkg/providers/` | LLM adapters. `provider/` holds the interface, the `ProviderType` constants and `AllProviderTypes`; `pconfig/` the per-agent model config; `openaicompat/` the shared OpenAI-shaped door; `embeddings/` a separate axis |
| `pkg/tools/` | The agent tool-call layer: schemas (`registry.go`), dispatcher (`executor.go`), and the tools — terminal, code, browser, memory, knowledge, `web_search` over `searchers/` |
| `pkg/docker/` | Docker SDK wrapper for the per-flow sandbox containers |
| `pkg/csum/` | Chain summarization for LLM context management, over the `chainAST` in `pkg/cast/` |
| `pkg/templates/` | Embedded agent prompts (`prompts/*.tmpl`) and the validator that checks a user-edited prompt still renders |
| `pkg/graphiti/` | HTTP client for the Graphiti knowledge-graph service. It does not speak Neo4j |
| `pkg/observability/` | OpenTelemetry traces/metrics/logs, `langfuse/`, `profiling/` |
| `pkg/flowfiles/`, `pkg/resources/` | Per-flow file tree and sandbox transfer; the user-level resource store |
| `pkg/schema/`, `pkg/password/`, `pkg/system/`, `pkg/timezone/`, `pkg/version/`, `pkg/terminal/` | Validation plumbing; the password policy; shared HTTP client; IANA name resolution; link-time version; console output for the `cmd/*tester` CLIs |
Database migrations live in `backend/migrations/sql/` and run automatically via goose at startup.
Migrations are `backend/migrations/sql/*.sql`, **embedded into the binary** and run by goose at startup — a new migration needs a rebuild, not just a restart. A failure aborts the boot.
### Frontend Structure
```
frontend/src/
├── app.tsx / main.tsx # Entry points and router setup
├── pages/ # Route-level page components
│ ├── flows/ # Flow management UI
│ └── settings/ # Provider, prompt, token settings
├── components/
│ ├── layouts/ # App shell layouts
│ └── ui/ # Base Radix UI components
├── graphql/ # Auto-generated Apollo types (do not edit)
├── hooks/ # Custom React hooks
├── lib/ # Apollo client, HTTP utilities
└── schemas/ # Zod validation schemas
├── main.tsx / app.tsx # Entry point; Apollo and the context providers wrap the router tree
├── pages/ # Route components, one directory per route group (flows, settings, …)
├── features/<domain>/ # Domain code: authentication, flows, knowledges, resources, templates
├── providers/ # Context providers — where the queries and subscriptions live
├── components/ui/ # Design-system primitives (shadcn registry; about half wrap Radix)
├── components/shared/ # Composites used by more than one area or by the app shell
├── components/layouts/ # App shell layouts
├── graphql/types.ts # Generated. Never edit by hand — it carries no banner saying so
├── hooks/ lib/ styles/ models/ types/ test-utils/
└── (outside src) e2e/ docs/ scripts/ eslint-rules/ # Playwright suite, testing playbooks,
# build helpers, and one local ESLint rule
```
State is managed primarily through Apollo Client (GraphQL) with real-time updates via GraphQL subscriptions over WebSocket.
Placement rule, as the code applies it: `components/ui` and `components/shared` never import `features/*` (ESLint rejects it); `components/ui` reaches the app only through the generic hooks in `hooks/`; `components/shared` holds composites that more than one area renders and takes its domain data through props (the version panel is the one that reads a domain provider); `features/<domain>` is where data coupling belongs — providers, generated types and REST calls — and a feature is normally consumed by its own domain's pages.
Server state comes from **Apollo Client 4** (note the v4 import paths, `@apollo/client/react`). `lib/apollo.ts` splits subscriptions onto a `graphql-ws` WebSocket link. Components seldom call Apollo directly: the queries and subscriptions live in `src/providers/*`, which `app.tsx` mounts around the router — add a new read there first. Not everything is GraphQL: account, resource and flow-file writes go over REST through `@/lib/axios`.
### Data Flow
1. User creates a "flow" (penetration test) via the UI or REST API.
2. The backend queues the flow and spawns agent goroutines.
3. The Researcher agent gathers information; the Developer plans attack strategies; the Executor runs tools in isolated Docker containers.
4. Results, tool outputs, and LLM reasoning are stored in PostgreSQL (with pgvector for semantic search/memory).
5. Real-time progress is pushed to the frontend via GraphQL subscriptions.
1. A user creates a "flow" — the UI calls the GraphQL `createFlow` mutation; REST is the programmatic equivalent.
2. `CreateFlow` (`pkg/controller/flows.go`) reserves the row and builds the worker asynchronously; there is no queue, and a build failure marks the flow `failed` and says so on its message log.
3. The `primary_agent` decomposes the flow into tasks; the `generator` produces each task's subtasks and the `refiner` re-plans after every completed one. Subtasks run one at a time and delegate to the specialist agents.
4. Those agents call tools — terminal, file, browser, search — inside per-flow Docker containers.
5. Results, tool output and LLM reasoning land in PostgreSQL (pgvector for semantic memory).
6. Progress reaches the UI through GraphQL subscriptions fed by `pkg/graph/subscriptions`.
7. Beside flows there is an **assistant**: an interactive chat attached to a flow, sharing its containers and provider settings but with its own log tables.
### Authentication
- **Session cookies** for browser login (secure, httpOnly)
- **OAuth2** via Google and GitHub
- **Bearer tokens** (API tokens table) for programmatic API access
- **Session cookies** for browser login — cookie store keyed by `COOKIE_SIGNING_SALT` mixed with `TENANT_ID`; `HttpOnly` always, `Secure` only over HTTPS. Changing the salt invalidates every session.
- **OAuth2** via Google and GitHub.
- **Bearer tokens** (API tokens table) for programmatic access.
All three pass through `pkg/server/auth/auth_middleware.go`, which offers `AuthUserRequired`, `AuthTokenRequired` and `TryAuth`. Authorization is separate: `auth.PrivilegesRequired("<area>.<action>")` wraps individual routes in `pkg/server/router.go`. Repeated failed logins are throttled.
### Key Integrations
- **LLM Providers**: OpenAI, Anthropic, Gemini, AWS Bedrock, Ollama, DeepSeek, GLM, Kimi, Qwen, and custom HTTP endpoints — configured via environment variables or the Settings UI
- **Search**: DuckDuckGo, Google, Tavily, Traversaal, Perplexity, Searxng
- **Databases**: PostgreSQL + pgvector (required), Neo4j (optional, for knowledge graph)
- **Observability**: OpenTelemetry → VictoriaMetrics + Loki + Jaeger → Grafana; Langfuse for LLM analytics
- **LLM Providers**: OpenAI, Anthropic, Gemini, AWS Bedrock, Ollama, DeepSeek, GLM, Kimi, Qwen, MiniMax, Mistral, xAI, and custom OpenAI-compatible endpoints. The authoritative list is `providerRegistry` in `backend/pkg/providers/registry.go` — check it before enumerating providers anywhere else.
- **Search**: DuckDuckGo, Google, Tavily, Firecrawl, Traversaal, Perplexity, Searxng, Sploitus and an internal browser-backed engine, all behind the single `web_search` tool. Authoritative list: `buildSearchEngines` in `backend/pkg/tools/web_search.go`.
- **Databases**: PostgreSQL + pgvector (required); Neo4j (optional) behind the Graphiti service, reached over HTTP.
- **Observability**: OpenTelemetry → VictoriaMetrics + Loki + Jaeger → Grafana; Langfuse for LLM analytics.
### Adding a New LLM Provider
## Code Generation
1. Create `backend/pkg/providers/<name>/<name>.go` implementing the `provider.Provider` interface.
2. Add a new `Provider<Name> ProviderType` constant and `DefaultProviderName<Name>` in `pkg/providers/provider/provider.go`.
3. Register the provider in `pkg/providers/providers.go` (`DefaultProviderConfig`, `NewProvider`, `buildProviderFromConfig`, `GetProvider`).
4. Add the new type to the `Valid()` whitelist in `pkg/server/models/providers.go` — **without this step, the REST API returns 422 Unprocessable Entity**.
5. Add the env var key to `pkg/config/config.go` (e.g., `<NAME>_API_KEY`, `<NAME>_SERVER_URL`).
6. Add the new `PROVIDER_TYPE` enum value via a goose migration in `backend/migrations/sql/`.
7. Add the provider icon in `frontend/src/components/icons/<name>.tsx` and register it in `frontend/src/components/icons/provider-icon.tsx`.
8. Update the GraphQL schema/types and frontend settings page if needed.
The output of the generators below is committed — regenerate and commit in the same change. When a codegen input changes, `.github/workflows/ci.yml` regenerates `frontend/src/graphql/types.ts` and fails if the committed file differs; it does not check the gqlgen, sqlc or swag output, so a stale one compiles and merges unnoticed.
### Code Generation
| Change | Command (from) | Writes |
|---|---|---|
| `backend/pkg/graph/schema.graphqls` | `go run github.com/99designs/gqlgen --config ./gqlgen/gqlgen.yml` (`backend/`) | `pkg/graph/generated.go`, `pkg/graph/model/`, resolver stubs in `pkg/graph/schema.resolvers.go` |
| `backend/sqlc/models/*.sql`, a migration | `sqlc generate` (`backend/sqlc/`) — needs a **live** PostgreSQL in `DATABASE_URL` | `backend/pkg/database/` |
| REST handler annotations | `swag init -g ../../pkg/server/router.go -o pkg/server/docs/ --parseDependency --parseInternal --parseDepth 2 -d cmd/pentagi` (`backend/`) | `pkg/server/docs/` |
| `frontend/graphql-schema.graphql` (the operations file) or the backend schema | `pnpm run graphql:generate` (`frontend/`) | `frontend/src/graphql/types.ts` |
When modifying `backend/pkg/graph/schema.graphqls`, re-run the gqlgen command to regenerate resolver stubs. When modifying REST handler annotations, re-run swag to update Swagger docs. When modifying `frontend/src/graphql/*.graphql` query files, re-run `npm run graphql:generate` to update TypeScript types.
A backend schema change therefore needs **both** gqlgen and the frontend codegen.
### Utility Binaries
## Adding a New LLM Provider
The backend contains helper binaries for development/testing:
- `cmd/ctester/` — tests container execution
- `cmd/ftester/` — tests LLM function/tool calling
- `cmd/etester/` — tests embedding providers
- `cmd/installer/` — interactive TUI wizard for guided deployment setup (configures `.env`, Docker Compose, DB, search engines, etc.)
Order matters — types before the door, because the door's constructor names them. Copy the last provider added (`mistral`, `xai`) rather than an old one.
1. **Types.** In `pkg/providers/provider/provider.go`: the `Provider<Name>` and `DefaultProviderName<Name>` constants, the entry in `AllProviderTypes`, and the classification in `ReasoningProvider()`.
2. **Config.** `<NAME>_API_KEY` / `<NAME>_SERVER_URL` / `<NAME>_PROVIDER` in `pkg/config/config.go` (the third carries the gateway's model prefix), mirrored in `.env.example`, `docker-compose.yml` and the `clearConfigEnv` list in `config_test.go`. Add every credential field to `GetSecretPatterns()` — values listed there are masked out of logs and agent transcripts.
3. **Migration.** A goose migration that rebuilds the `PROVIDER_TYPE` enum with the new value and re-points `providers.type`, `flows.model_provider_type` and `assistants.model_provider_type`; Postgres will not extend that enum in place. Then regenerate `pkg/database/` with sqlc.
4. **Catalogue and door.** `pkg/providers/<name>/` with `config.yml`, `models.yml` and a `<name>.go` exporting `DefaultProviderConfig`, `BuildProviderConfig`, `DefaultModels` and `New`. An OpenAI-shaped vendor does not implement the interface by hand — `New` returns `openaicompat.New(openaicompat.Spec{…})`.
5. **Three tables, three edits**: `providerRegistry` (`registry.go`), `bundledCatalogs` (`catalog.go`), `doorEndpoints` (`routing.go`). Miss one and a guard test in `pkg/providers` fails.
6. **Installer.** The screen id, menu row, screen construction and strings under `cmd/installer/wizard/`. Nothing fails the build if you skip it; the wizard simply never offers the provider.
7. **GraphQL.** The `ProviderType` enum value plus fields in `ProvidersModelsList`, `ProvidersReadinessStatus` and `DefaultProvidersConfig`; re-run gqlgen and extend the per-type switches in `schema.resolvers.go`.
8. **Frontend.** `providerLabels` in `pages/settings/settings-providers.tsx` (a `Record<ProviderType, …>`, so it will not compile without the new key), the icon in `components/icons/` registered in `provider-icon.tsx`, the fields in `frontend/graphql-schema.graphql`, then `pnpm run graphql:generate`, and the e2e cassette in `e2e/mocks/cassettes/settings-providers.ts`.
9. **Docs.** The section every other provider has in `README.md`, `backend/docs/config.md` and `backend/docs/database.md`. `TestCatalog_ReadmeProviderSectionsMatchTheShippedConfig` in `pkg/providers/catalog_test.go` reads `README.md` — a provider or model missing from it turns that test red.
Embeddings are a separate axis (`EMBEDDING_PROVIDER`, `pkg/providers/embeddings/`): adding a chat door does not add an embedder.
## Adding a New Search Engine
Engines are primitives under `backend/pkg/tools/searchers/`, orchestrated by the single `web_search` tool. Agents never call an engine directly — they call `web_search` with an intent `mode`.
1. `searchers/<name>.go` implementing `searchers.Searcher`: constructor, `IsAvailable()`, `Engine()`, and a `Handle(ctx, Request)` returning **typed** errors (`searchers.Retryable` / `searchers.Fatal` / `searchers.ErrNotConfigured`, or `searchers.ClassifyHTTPStatus`). Never swallow an error into a result string. `searchers` must not import `pkg/tools`.
2. Config fields in `pkg/config/config.go`, plus `.env.example`, `docker-compose.yml`, the `envDefault` assertions in `config_test.go`, and `GetSecretPatterns()` for every credential.
3. Construct it in `buildSearchEngines` and place its id in the `fallbackStrategy` chains in `web_search.go` — the only place per-mode priority lives. An id in a chain with no entry in the engines map is skipped silently at runtime, not at compile time.
4. Attribution, if the engine needs a **new** `SearchengineType`: a goose migration rebuilding the enum, the constant in `pkg/database/models.go`, **and** the value in both the constant block and the `Valid()` switch in `pkg/server/models/searchlogs.go`. Reusing an existing value needs none of it.
5. `<name>_test.go` in `searchers/` (the shared MITM proxy harness is in `fixtures_test.go`), and orchestrator coverage in `web_search_test.go` if behaviour changes.
6. The installer wizard (`cmd/installer/wizard/`: the config field, the `GetVar`/`SetVar` pair, the descriptions and masked/critical lists, the labels, the form field) and `cmd/ftester` if you want to drive the engine in isolation.
7. The prose that enumerates engines: `pkg/templates/prompts/searcher.tmpl` (what the agent is told exists), `backend/docs/config.md`, and `README.md`.
No frontend change is needed: it treats `SearchLog.engine` as an opaque string.
## Utility Binaries
- `cmd/ctester/` — provider conformance tester: runs the case suite against one provider (`-type`), filtered by agent role and group, and writes a report. `-check-routing` checks catalogue routing only.
- `cmd/ftester/` — exercises LLM function/tool calling, including one search engine at a time.
- `cmd/etester/` — embedding tester and pgvector store maintenance. `flush` and `reindex` act on the real database in `DATABASE_URL` and are destructive.
- `cmd/installer/` — interactive TUI wizard for guided deployment (writes `.env`, compose files, DB and search settings). Its embedded files are generated: see `go generate` above.
+74
View File
@@ -0,0 +1,74 @@
# License Compliance Guide
## Overview
PentAGI is **MIT licensed** and all dependencies use MIT-compatible licenses.
## For Developers
### Adding New Dependencies
When adding new dependencies, ensure they use compatible licenses:
#### Approved Licenses
- MIT
- Apache-2.0
- BSD-2-Clause, BSD-3-Clause
- ISC
- MPL-2.0 (if used without modification)
- 0BSD (public domain)
#### Incompatible Licenses
- GPL, LGPL, AGPL (without special exception)
- CC-BY-SA (for code, OK for data)
- Proprietary/Commercial licenses
### Before Merging PR
1. Update dependencies:
```bash
cd backend && go mod tidy
cd ../frontend && pnpm install
```
2. Generate license reports:
```bash
./scripts/generate-licenses.sh
```
This script automatically collects license information from all dependencies and saves them to the `licenses/` directory. See [licenses/README.md](licenses/README.md) for details.
3. Scan for issues:
```bash
osv-scanner scan --experimental-licenses="MIT,Apache-2.0,BSD-2-Clause,BSD-3-Clause,ISC,MPL-2.0" backend
osv-scanner scan --experimental-licenses="MIT,Apache-2.0,BSD-2-Clause,BSD-3-Clause,ISC,MPL-2.0" frontend
```
### License Verification Tools
- **osv-scanner** - Security and license scanning (recommended)
- **license-checker** - npm license verification
- **go-licenses** - Go module license extraction (install: `go install github.com/google/go-licenses@latest`)
- **go list** - Go module inspection
## For Docker Builds
License reports are automatically generated during Docker builds:
- Backend reports in `/opt/pentagi/licenses/backend/`
- `dependencies.txt` - List of all Go modules
- `licenses.csv` - Detailed license information (generated by go-licenses)
- Frontend reports in `/opt/pentagi/licenses/frontend/`
- `dependencies.json` - Complete npm dependency tree
- `licenses.json` - Detailed license data
- `licenses.csv` - License summary
## Testing Your Changes
Frontend changes are covered by unit tests (`cd frontend && pnpm test`) and
end-to-end tests that run fully offline — no backend, keys, or secrets needed,
including on fork PRs. See [frontend/docs/e2e.md](frontend/docs/e2e.md) for the
one-time bootstrap, running locally, and debugging a red CI run.
## Questions?
Contact: **info@pentagi.com** or **info@vxcontrol.com**
+138
View File
@@ -0,0 +1,138 @@
# Contributors
This document recognizes all individuals who have contributed to PentAGI. Their work across 370+ commits over 18 months has shaped this project into what it is today.
## Core Team
### Project Lead & Backend Development
- [@asdek](https://github.com/asdek) (Dmitry Nagibin) - Architecture, backend infrastructure, agent system, provider integrations, observability, and project coordination
### Frontend Development
- [@sirozha](https://github.com/sirozha) (Sergey Kozyrenko) - React UI implementation, settings interfaces, GraphQL integration, and frontend architecture
### Backend Development
- [@zavgorodnii](https://github.com/zavgorodnii) (Andrei Zavgorodnii) - Graphiti integration, patch refiner, knowledge graph implementation
---
## External Contributors
We are deeply grateful to the following individuals for their contributions to PentAGI:
### Feature Contributors
#### [@mason5052](https://github.com/mason5052) (Mason Kim)
**Contributions:** Significant testing infrastructure improvements and bug fixes
- Added comprehensive unit test coverage across multiple packages ([PR#199](https://github.com/vxcontrol/pentagi/pull/199), [PR#198](https://github.com/vxcontrol/pentagi/pull/198), [PR#200](https://github.com/vxcontrol/pentagi/pull/200), [PR#201](https://github.com/vxcontrol/pentagi/pull/201), [PR#202](https://github.com/vxcontrol/pentagi/pull/202), [PR#214](https://github.com/vxcontrol/pentagi/pull/214), [PR#213](https://github.com/vxcontrol/pentagi/pull/213))
- Test coverage for: config, version, terminal, server response, embeddings, graph context, executor helpers, custom JSON types ([PR#170](https://github.com/vxcontrol/pentagi/pull/170)), context registry ([PR#171](https://github.com/vxcontrol/pentagi/pull/171)), executor terminal utilities ([PR#172](https://github.com/vxcontrol/pentagi/pull/172)), search tools ([PR#153](https://github.com/vxcontrol/pentagi/pull/153))
- Test coverage for LLM providers (DeepSeek, GLM, Kimi, Qwen) ([PR#189](https://github.com/vxcontrol/pentagi/pull/189))
- Fixed critical bugs:
- Detached command context isolation ([PR#179](https://github.com/vxcontrol/pentagi/pull/179))
- Agent chain iteration cap and repeating detector ([PR#178](https://github.com/vxcontrol/pentagi/pull/178), [PR#180](https://github.com/vxcontrol/pentagi/pull/180))
- HTTP client global mutation in search tools ([PR#151](https://github.com/vxcontrol/pentagi/pull/151))
- Browser graceful screenshot failure handling ([PR#150](https://github.com/vxcontrol/pentagi/pull/150))
- Silent error handling in GetTool ([PR#152](https://github.com/vxcontrol/pentagi/pull/152))
- OAuth callback missing return ([PR#127](https://github.com/vxcontrol/pentagi/pull/127))
- OAuth state field validation ([PR#125](https://github.com/vxcontrol/pentagi/pull/125), [PR#120](https://github.com/vxcontrol/pentagi/pull/120))
- Langfuse TLS configuration respect ([PR#132](https://github.com/vxcontrol/pentagi/pull/132))
- CA private key cleanup in entrypoint ([PR#168](https://github.com/vxcontrol/pentagi/pull/168))
- Google search options unused ([PR#167](https://github.com/vxcontrol/pentagi/pull/167))
- Resource leaks and unbounded allocation in tools ([PR#141](https://github.com/vxcontrol/pentagi/pull/141))
- Debug console.log removal ([PR#141](https://github.com/vxcontrol/pentagi/pull/141))
- Swagger missing quote ([PR#140](https://github.com/vxcontrol/pentagi/pull/140))
- Terminal typo correction ([PR#164](https://github.com/vxcontrol/pentagi/pull/164))
- Documentation improvements: fixed typos and grammar issues ([PR#121](https://github.com/vxcontrol/pentagi/pull/121))
#### [@niuqun2003](https://github.com/niuqun2003) (niuqun2003)
**Contributions:** Chinese LLM provider ecosystem integration ([PR#154](https://github.com/vxcontrol/pentagi/pull/154))
- Added support for DeepSeek, GLM, Kimi, and Qwen LLM providers
- Implemented provider configurations and API integrations
#### [@Priyanka-2725](https://github.com/Priyanka-2725) (Priyanka Singh)
**Contributions:** AWS Bedrock provider improvements, Sploitus inegration implementation and bug fixes
- Fixed Bedrock toolConfig runtime failures ([PR#166](https://github.com/vxcontrol/pentagi/pull/166))
- Implemented better exploit finding capabilities by Sploitus ([PR#133](https://github.com/vxcontrol/pentagi/pull/133))
- Fixed terminal command handling logic ([PR#124](https://github.com/vxcontrol/pentagi/pull/124))
#### [@Alex-wuhu](https://github.com/Alex-wuhu) (Alex)
**Contributions:** Novita AI integration ([PR#162](https://github.com/vxcontrol/pentagi/pull/162))
- Added Novita AI as optional LLM provider
- Updated Novita models configuration
#### [@efe-arv](https://github.com/efe-arv) (Efe Büken)
**Contributions:** HTTP client timeout configuration ([PR#205](https://github.com/vxcontrol/pentagi/pull/205))
- Added configurable timeout to HTTP client for improved reliability
#### [@manusjs](https://github.com/manusjs) (manusjs)
**Contributions:** Bedrock tool configuration fix ([PR#196](https://github.com/vxcontrol/pentagi/pull/196))
- Fixed Bedrock to always include toolConfig when messages contain toolUse/toolResult blocks
#### [@stoykovstoyk](https://github.com/stoykovstoyk) (Stoyko Stoykov)
**Contributions:** SearXNG meta search engine integration ([PR#53](https://github.com/vxcontrol/pentagi/pull/53))
- Added SearXNG as a search engine option
- Implemented tool integration for meta search capabilities
#### [@kaikreuzer](https://github.com/kaikreuzer) (Kai Kreuzer)
**Contributions:** AWS credentials support ([PR#90](https://github.com/vxcontrol/pentagi/pull/90))
- Added support for temporary AWS credentials
- Enhanced AWS session token handling
#### [@mrigankad](https://github.com/mrigankad) (Mriganka Dey)
**Contributions:** Security and bug fixes ([PR#104](https://github.com/vxcontrol/pentagi/pull/104))
- Various security improvements and bug fixes across the codebase
#### [@salmanmkc](https://github.com/salmanmkc) (Salman Chishti)
**Contributions:** GitHub Actions modernization
- Upgraded GitHub Actions to latest versions ([PR#112](https://github.com/vxcontrol/pentagi/pull/112))
- Upgraded GitHub Actions for Node 24 compatibility ([PR#111](https://github.com/vxcontrol/pentagi/pull/111))
### Bug Fixes & Improvements
#### [@Vaibhavee89](https://github.com/Vaibhavee89) (Vaibhavee Singh)
**Contributions:** Documentation enhancement
- Added external network access configuration guide to README
#### [@PeterDaveHello](https://github.com/PeterDaveHello) (Peter Dave Hello)
**Contributions:** Dockerfile optimization ([PR#50](https://github.com/vxcontrol/pentagi/pull/50))
- Removed unnecessary cleanup steps in Dockerfile for improved build efficiency
#### [@s-b-repo](https://github.com/s-b-repo) (S.B)
**Contributions:** Security improvements
- Implemented file size limit and path escaping for enhanced security
- Fixed typo in executor.go ('Incoming')
#### [@SkyFlyingMouse](https://github.com/SkyFlyingMouse) (SkyFlyingMouse)
**Contributions:** Code quality ([PR#128](https://github.com/vxcontrol/pentagi/pull/128))
- Fixed Docker client constant name typo in backend
#### [@haosenwang1018](https://github.com/haosenwang1018) (Sense_wang)
**Contributions:** Development environment ([PR#163](https://github.com/vxcontrol/pentagi/pull/163))
- Expanded .gitignore with IDE and OS patterns for cleaner repository
#### [@hhktony](https://github.com/hhktony) (Tony Xu)
**Contributions:** Documentation ([PR#32](https://github.com/vxcontrol/pentagi/pull/32))
- README.md improvements and clarifications
---
## Acknowledgments
This project exists because of the collective effort of everyone listed above. From major feature implementations to small bug fixes, every contribution has made PentAGI better.
---
## How to Contribute
Interested in contributing to PentAGI? We welcome contributions of all kinds:
- Bug reports and fixes
- New features and enhancements
- Documentation improvements
- Testing and QA
- Code reviews
Please see our [CONTRIBUTING.md](CONTRIBUTING.md) guide for more information.
---
**Note:** Due to repository history rewriting on March 29, 2026, to resolve licensing matters, individual commit history is no longer visible in GitHub's interface. This document preserves the record of all contributions made during the project's development from January 2025 to March 2026.
+80 -16
View File
@@ -3,23 +3,26 @@
# ========================================
# Stage 1: Frontend Application Build
# ========================================
FROM node:23-slim AS frontend-compiler
FROM node:24.17.0-slim AS frontend-compiler
# Production build configuration
ENV NODE_ENV=production
ENV VITE_BUILD_MEMORY_LIMIT=4096
ENV NODE_OPTIONS="--max-old-space-size=4096"
ENV PNPM_HOME="/usr/local/share/pnpm"
ENV PATH="$PNPM_HOME/bin:$PNPM_HOME:$PATH"
WORKDIR /app/ui
# Install build essentials
# Install build essentials and enable pnpm via corepack
RUN apt-get update && apt-get install -y \
ca-certificates \
tzdata \
gcc \
g++ \
make \
git
git \
&& corepack enable
# GraphQL schema for code generation
COPY ./backend/pkg/graph/schema.graphqls ../backend/pkg/graph/
@@ -27,12 +30,18 @@ COPY ./backend/pkg/graph/schema.graphqls ../backend/pkg/graph/
# Application source code
COPY frontend/ .
# Install dependencies with package manager detection for SBOM
RUN --mount=type=cache,target=/root/.npm \
npm ci --include=dev
# Install dependencies
RUN --mount=type=cache,target=/root/.local/share/pnpm/store \
pnpm install --frozen-lockfile
# Generate license report for frontend dependencies
RUN pnpm add -g license-checker && \
mkdir -p /licenses/frontend && \
license-checker --production --json > /licenses/frontend/licenses.json && \
license-checker --production --csv > /licenses/frontend/licenses.csv
# Build frontend with optimizations and parallel processing
RUN npm run build -- \
RUN pnpm run build -- \
--mode production \
--minify esbuild \
--outDir dist \
@@ -43,11 +52,16 @@ RUN npm run build -- \
# ========================================
# Stage 2: Backend Services Compilation
# ========================================
FROM golang:1.24-bookworm AS api-builder
FROM golang:1.26-bookworm AS api-builder
# Version injection arguments
ARG PACKAGE_VER=develop
# "ce" is not a release number, so GetBinaryVersion reads it as "no release" and reports
# the edition alone. The default is a word rather than the empty string because
# scripts/check-version-rule.sh requires the builder to stamp something: an empty
# PackageVer reaching the binary is the one case it must never mistake for a release.
ARG PACKAGE_VER=ce
ARG PACKAGE_REV=
ARG PACKAGE_EDITION=ce
# Static binary compilation settings
ENV CGO_ENABLED=0
@@ -71,12 +85,22 @@ COPY backend/ .
RUN --mount=type=cache,target=/go/pkg/mod \
go mod download && go mod verify
# Install go-licenses tool for license extraction
RUN --mount=type=cache,target=/go/pkg/mod \
go install github.com/google/go-licenses@latest
# Generate license reports for backend dependencies
RUN mkdir -p /licenses/backend && \
go list -m all > /licenses/backend/dependencies.txt && \
GOROOT=$(go env GOROOT) GOTOOLCHAIN=auto go-licenses csv ./cmd/pentagi > /licenses/backend/licenses.csv 2>/dev/null || true
# Compile main application binary with embedded version metadata
RUN go build -trimpath \
-ldflags "\
-X pentagi/pkg/version.PackageName=pentagi \
-X pentagi/pkg/version.PackageVer=${PACKAGE_VER} \
-X pentagi/pkg/version.PackageRev=${PACKAGE_REV}" \
-X pentagi/pkg/version.PackageRev=${PACKAGE_REV} \
-X pentagi/pkg/version.Edition=${PACKAGE_EDITION}" \
-o /pentagi ./cmd/pentagi
# Build ctester utility
@@ -84,7 +108,8 @@ RUN go build -trimpath \
-ldflags "\
-X pentagi/pkg/version.PackageName=ctester \
-X pentagi/pkg/version.PackageVer=${PACKAGE_VER} \
-X pentagi/pkg/version.PackageRev=${PACKAGE_REV}" \
-X pentagi/pkg/version.PackageRev=${PACKAGE_REV} \
-X pentagi/pkg/version.Edition=${PACKAGE_EDITION}" \
-o /ctester ./cmd/ctester
# Build ftester utility
@@ -92,7 +117,8 @@ RUN go build -trimpath \
-ldflags "\
-X pentagi/pkg/version.PackageName=ftester \
-X pentagi/pkg/version.PackageVer=${PACKAGE_VER} \
-X pentagi/pkg/version.PackageRev=${PACKAGE_REV}" \
-X pentagi/pkg/version.PackageRev=${PACKAGE_REV} \
-X pentagi/pkg/version.Edition=${PACKAGE_EDITION}" \
-o /ftester ./cmd/ftester
# Build etester utility
@@ -100,13 +126,14 @@ RUN go build -trimpath \
-ldflags "\
-X pentagi/pkg/version.PackageName=etester \
-X pentagi/pkg/version.PackageVer=${PACKAGE_VER} \
-X pentagi/pkg/version.PackageRev=${PACKAGE_REV}" \
-X pentagi/pkg/version.PackageRev=${PACKAGE_REV} \
-X pentagi/pkg/version.Edition=${PACKAGE_EDITION}" \
-o /etester ./cmd/etester
# ========================================
# Stage 3: Production Runtime Environment
# ========================================
FROM alpine:3.23.3
FROM alpine:3.23.5
# Establish non-privileged execution context with docker socket access
RUN addgroup -g 998 docker && \
@@ -137,22 +164,39 @@ COPY --from=api-builder /ctester /opt/pentagi/bin/ctester
COPY --from=api-builder /ftester /opt/pentagi/bin/ftester
COPY --from=api-builder /etester /opt/pentagi/bin/etester
COPY --from=frontend-compiler /app/ui/dist /opt/pentagi/fe
COPY --from=api-builder /licenses/backend /opt/pentagi/licenses/backend
COPY --from=frontend-compiler /licenses/frontend /opt/pentagi/licenses/frontend
# Copy provider configuration files
COPY examples/configs/atlas.provider.yml /opt/pentagi/conf/
COPY examples/configs/azure-openai.provider.yml /opt/pentagi/conf/
COPY examples/configs/bedrock-glm-flash.provider.yml /opt/pentagi/conf/
COPY examples/configs/custom-openai.provider.yml /opt/pentagi/conf/
COPY examples/configs/deepinfra.provider.yml /opt/pentagi/conf/
COPY examples/configs/deepseek.provider.yml /opt/pentagi/conf/
COPY examples/configs/hcnsec.provider.yml /opt/pentagi/conf/
COPY examples/configs/moonshot.provider.yml /opt/pentagi/conf/
COPY examples/configs/novita.provider.yml /opt/pentagi/conf/
COPY examples/configs/nvidia-glm-5.1.provider.yml /opt/pentagi/conf/
COPY examples/configs/ollama-cloud.provider.yml /opt/pentagi/conf/
COPY examples/configs/ollama-llama318b-instruct.provider.yml /opt/pentagi/conf/
COPY examples/configs/ollama-llama318b.provider.yml /opt/pentagi/conf/
COPY examples/configs/ollama-qwen332b-fp16-tc.provider.yml /opt/pentagi/conf/
COPY examples/configs/ollama-qwq32b-fp16-tc.provider.yml /opt/pentagi/conf/
COPY examples/configs/opencode.provider.yml /opt/pentagi/conf/
COPY examples/configs/openrouter.provider.yml /opt/pentagi/conf/
COPY examples/configs/novita.provider.yml /opt/pentagi/conf/
COPY examples/configs/vllm-qwen3.5-27b-fp8.provider.yml /opt/pentagi/conf/
COPY examples/configs/orcarouter.provider.yml /opt/pentagi/conf/
COPY examples/configs/vllm-mixed.provider.yml /opt/pentagi/conf/
COPY examples/configs/vllm-qwen3.5-27b-fp8-no-think.provider.yml /opt/pentagi/conf/
COPY examples/configs/vllm-qwen3.5-27b-fp8.provider.yml /opt/pentagi/conf/
COPY examples/configs/vllm-qwen3.6-27b-fp8-no-think.provider.yml /opt/pentagi/conf/
COPY examples/configs/vllm-qwen3.6-27b-fp8.provider.yml /opt/pentagi/conf/
COPY examples/configs/vllm-qwen3.8-27b-fp8-no-think.provider.yml /opt/pentagi/conf/
COPY examples/configs/vllm-qwen3.8-27b-fp8.provider.yml /opt/pentagi/conf/
COPY examples/configs/vllm-qwen3.6-35b-a3b-fp8-no-think.provider.yml /opt/pentagi/conf/
COPY examples/configs/vllm-qwen3.6-35b-a3b-fp8.provider.yml /opt/pentagi/conf/
COPY examples/configs/vllm-qwen332b-fp16.provider.yml /opt/pentagi/conf/
COPY examples/configs/xai.provider.yml /opt/pentagi/conf/
COPY LICENSE /opt/pentagi/LICENSE
COPY NOTICE /opt/pentagi/NOTICE
@@ -167,6 +211,26 @@ USER pentagi
ENTRYPOINT ["/opt/pentagi/bin/entrypoint.sh", "/opt/pentagi/bin/pentagi"]
# Mirrors GetBinaryVersion in backend/pkg/version: "<edition>", "<edition>.h<rev>",
# "<ver>-<edition>" or "<ver>-<edition>.h<rev>". The "h" keeps the revision an
# alphanumeric semver identifier. The binary is stamped from the same args in
# the builder stage, so pass them and nothing else: PACKAGE_VERSION_FULL is where this
# expression puts its result, and overriding it labels the image with a string the binary
# never says.
#
# PACKAGE_VER is a release number. The words "develop", "ce" and "ee" are not valid values
# for it: an ARG default can branch on empty but cannot compare strings, so this expression
# would read one as a release and label the image ce-ce where the binary reports ce. Leave
# PACKAGE_VER empty for a build with no release behind it — scripts/version.sh and
# scripts/version.ps1 clear a tag of that name, the CI jobs do not, and
# scripts/check-version-rule.sh measures the agreement for a release tag or no tag.
ARG PACKAGE_VER
ARG PACKAGE_REV
ARG PACKAGE_EDITION=ce
ARG VER_PART=${PACKAGE_VER:+${PACKAGE_VER}-}${PACKAGE_EDITION}
ARG PACKAGE_VERSION_FULL=${VER_PART}${PACKAGE_REV:+.h${PACKAGE_REV}}
LABEL com.pentagi.version="${PACKAGE_VERSION_FULL}"
# Image Metadata
LABEL org.opencontainers.image.source="https://github.com/vxcontrol/pentagi"
LABEL org.opencontainers.image.description="Fully autonomous AI Agents system capable of performing complex penetration testing tasks"
+1373 -499
View File
File diff suppressed because it is too large. Load diff
+37
View File
@@ -0,0 +1,37 @@
version: "2"
linters:
settings:
staticcheck:
# golangci-lint's own default set, minus QF1001. The -ST10xx entries are the
# defaults themselves: dropping them re-enables those checks.
checks:
- all
- -QF1001
- -ST1000
- -ST1003
- -ST1016
- -ST1020
- -ST1021
- -ST1022
errcheck:
exclude-functions:
- (*github.com/jinzhu/gorm.DB).AddError
- (net/http.ResponseWriter).Write
exclusions:
# strict, not lax: lax treats any "Code generated by" line as a marker, which
# swallows pkg/graph/schema.resolvers.go — gqlgen writes that header but keeps
# our resolver implementations across regeneration, so it is our code.
generated: strict
presets:
- std-error-handling
paths:
# Fern generates this package but omits the DO NOT EDIT header there, so
# `generated` cannot recognise it. Regenerating overwrites any edit.
- pkg/observability/langfuse/api/internal
warn-unused: true
issues:
max-issues-per-linter: 0
max-same-issues: 0
+137 -48
View File
@@ -5,11 +5,13 @@ import (
"flag"
"fmt"
"log"
"net/http"
"os"
"strings"
"time"
"pentagi/pkg/config"
"pentagi/pkg/providers"
"pentagi/pkg/providers/anthropic"
"pentagi/pkg/providers/bedrock"
"pentagi/pkg/providers/custom"
@@ -17,13 +19,16 @@ import (
"pentagi/pkg/providers/gemini"
"pentagi/pkg/providers/glm"
"pentagi/pkg/providers/kimi"
"pentagi/pkg/providers/minimax"
"pentagi/pkg/providers/mistral"
"pentagi/pkg/providers/ollama"
"pentagi/pkg/providers/openai"
"pentagi/pkg/providers/pconfig"
"pentagi/pkg/providers/provider"
"pentagi/pkg/providers/qwen"
"pentagi/pkg/providers/tester"
"pentagi/pkg/providers/tester/testdata"
"pentagi/pkg/providers/tester/cases"
"pentagi/pkg/providers/xai"
"pentagi/pkg/version"
"github.com/joho/godotenv"
@@ -32,7 +37,7 @@ import (
func main() {
envFile := flag.String("env", ".env", "Path to environment file")
providerType := flag.String("type", "custom", "Provider type [custom, openai, anthropic, gemini, bedrock, ollama, deepseek, glm, kimi, qwen]")
providerType := flag.String("type", "custom", "Provider type [custom, openai, anthropic, gemini, bedrock, ollama, deepseek, glm, kimi, qwen, minimax, mistral, xai]")
providerName := flag.String("name", "", "Provider name using as PROVDER_NAME/MODEL_NAME while building provider config")
configPath := flag.String("config", "", "Path to provider config file")
testsPath := flag.String("tests", "", "Path to custom tests YAML file")
@@ -41,6 +46,8 @@ func main() {
testGroups := flag.String("groups", "all", "Comma-separated test groups to run")
workers := flag.Int("workers", 4, "Number of workers to use")
verbose := flag.Bool("verbose", false, "Enable verbose output")
checkRouting := flag.Bool("check-routing", false,
"Ask each door which models it serves and report catalogue entries it did not name")
flag.Parse()
logrus.Infof("Starting PentAGI Provider Configuration Tester %s", version.GetBinaryVersion())
@@ -62,6 +69,11 @@ func main() {
cfg.LLMServerProvider = *providerName
}
if *checkRouting {
reportRouting(providers.CheckRouting(cfg, &http.Client{Timeout: 15 * time.Second}))
return
}
prv, err := createProvider(*providerType, cfg)
if err != nil {
log.Fatalf("Error creating provider: %v", err)
@@ -82,11 +94,11 @@ func main() {
testOptions = append(testOptions, tester.WithGroups(selectedGroups...))
} else {
// Include all available groups when "all" is specified
allGroups := []testdata.TestGroup{
testdata.TestGroupBasic,
testdata.TestGroupAdvanced,
testdata.TestGroupJSON,
testdata.TestGroupKnowledge,
allGroups := []cases.TestGroup{
cases.TestGroupBasic,
cases.TestGroupAdvanced,
cases.TestGroupJSON,
cases.TestGroupKnowledge,
}
testOptions = append(testOptions, tester.WithGroups(allGroups...))
}
@@ -115,10 +127,10 @@ func main() {
if *reportPath != "" {
if err := WriteReportToFile(agentResults, *reportPath); err != nil {
log.Printf("Error writing report: %v", err)
} else {
fmt.Printf("Report written to %s\n", *reportPath)
log.Fatalf("Error writing report: %v", err)
}
fmt.Printf("Report written to %s\n", *reportPath)
}
}
@@ -129,7 +141,7 @@ func createProvider(providerType string, cfg *config.Config) (provider.Provider,
if err != nil {
return nil, fmt.Errorf("error creating custom provider config: %w", err)
}
return custom.New(cfg, providerConfig)
return custom.New(cfg, provider.DefaultProviderNameCustom, providerConfig, providers.EnrichCatalogCapabilities)
case "openai":
if cfg.OpenAIKey == "" {
@@ -139,50 +151,47 @@ func createProvider(providerType string, cfg *config.Config) (provider.Provider,
if err != nil {
return nil, fmt.Errorf("error creating openai provider config: %w", err)
}
return openai.New(cfg, providerConfig)
return openai.New(cfg, provider.DefaultProviderNameOpenAI, providerConfig)
case "anthropic":
if cfg.AnthropicAPIKey == "" {
return nil, fmt.Errorf("Anthropic API key is not set")
}
providerConfig, err := anthropic.DefaultProviderConfig()
if err != nil {
return nil, fmt.Errorf("error creating anthropic provider config: %w", err)
}
return anthropic.New(cfg, providerConfig)
return anthropic.New(cfg, provider.DefaultProviderNameAnthropic, providerConfig)
case "gemini":
if cfg.GeminiAPIKey == "" {
return nil, fmt.Errorf("Gemini API key is not set")
return nil, fmt.Errorf("API key for Gemini is not set")
}
providerConfig, err := gemini.DefaultProviderConfig()
if err != nil {
return nil, fmt.Errorf("error creating gemini provider config: %w", err)
}
return gemini.New(cfg, providerConfig)
return gemini.New(cfg, provider.DefaultProviderNameGemini, providerConfig)
case "bedrock":
if !cfg.BedrockDefaultAuth && cfg.BedrockBearerToken == "" &&
(cfg.BedrockAccessKey == "" || cfg.BedrockSecretKey == "") {
return nil, fmt.Errorf("Bedrock requires authentication: set " +
return nil, fmt.Errorf("authentication for Bedrock is not set: provide " +
"BEDROCK_DEFAULT_AUTH=true, BEDROCK_BEARER_TOKEN, or " +
"BEDROCK_ACCESS_KEY_ID+BEDROCK_SECRET_ACCESS_KEY")
}
providerConfig, err := bedrock.DefaultProviderConfig()
providerConfig, err := bedrock.DefaultProviderConfig(cfg)
if err != nil {
return nil, fmt.Errorf("error creating bedrock provider config: %w", err)
}
return bedrock.New(cfg, providerConfig)
return bedrock.New(cfg, provider.DefaultProviderNameBedrock, providerConfig)
case "ollama":
if cfg.OllamaServerURL == "" {
return nil, fmt.Errorf("Ollama server URL is not set")
return nil, fmt.Errorf("server URL for Ollama is not set")
}
providerConfig, err := ollama.DefaultProviderConfig(cfg)
if err != nil {
return nil, fmt.Errorf("error creating ollama provider config: %w", err)
}
return ollama.New(cfg, providerConfig)
return ollama.New(cfg, provider.DefaultProviderNameOllama, providerConfig)
case "deepseek":
if cfg.DeepSeekAPIKey == "" {
@@ -192,7 +201,7 @@ func createProvider(providerType string, cfg *config.Config) (provider.Provider,
if err != nil {
return nil, fmt.Errorf("error creating deepseek provider config: %w", err)
}
return deepseek.New(cfg, providerConfig)
return deepseek.New(cfg, provider.DefaultProviderNameDeepSeek, providerConfig)
case "glm":
if cfg.GLMAPIKey == "" {
@@ -202,27 +211,57 @@ func createProvider(providerType string, cfg *config.Config) (provider.Provider,
if err != nil {
return nil, fmt.Errorf("error creating glm provider config: %w", err)
}
return glm.New(cfg, providerConfig)
return glm.New(cfg, provider.DefaultProviderNameGLM, providerConfig)
case "kimi":
if cfg.KimiAPIKey == "" {
return nil, fmt.Errorf("Kimi Moonshot AI API key is not set")
return nil, fmt.Errorf("API key for Kimi Moonshot AI is not set")
}
providerConfig, err := kimi.DefaultProviderConfig()
if err != nil {
return nil, fmt.Errorf("error creating kimi provider config: %w", err)
}
return kimi.New(cfg, providerConfig)
return kimi.New(cfg, provider.DefaultProviderNameKimi, providerConfig)
case "qwen":
if cfg.QwenAPIKey == "" {
return nil, fmt.Errorf("Qwen Alibaba Cloud API key is not set")
return nil, fmt.Errorf("API key for Qwen Alibaba Cloud is not set")
}
providerConfig, err := qwen.DefaultProviderConfig()
if err != nil {
return nil, fmt.Errorf("error creating qwen provider config: %w", err)
}
return qwen.New(cfg, providerConfig)
return qwen.New(cfg, provider.DefaultProviderNameQwen, providerConfig)
case "minimax":
if cfg.MiniMaxAPIKey == "" {
return nil, fmt.Errorf("MiniMax API key is not set")
}
providerConfig, err := minimax.DefaultProviderConfig()
if err != nil {
return nil, fmt.Errorf("error creating minimax provider config: %w", err)
}
return minimax.New(cfg, provider.DefaultProviderNameMiniMax, providerConfig)
case "mistral":
if cfg.MistralAPIKey == "" {
return nil, fmt.Errorf("mistral API key is not set")
}
providerConfig, err := mistral.DefaultProviderConfig()
if err != nil {
return nil, fmt.Errorf("error creating mistral provider config: %w", err)
}
return mistral.New(cfg, provider.DefaultProviderNameMistral, providerConfig)
case "xai":
if cfg.XAIAPIKey == "" {
return nil, fmt.Errorf("xAI API key is not set")
}
providerConfig, err := xai.DefaultProviderConfig()
if err != nil {
return nil, fmt.Errorf("error creating xai provider config: %w", err)
}
return xai.New(cfg, provider.DefaultProviderNameXAI, providerConfig)
default:
return nil, fmt.Errorf("unsupported provider type: %s", providerType)
@@ -259,13 +298,13 @@ func parseAgentTypes(agentStrings []string) []pconfig.ProviderOptionsType {
return agentTypes
}
func parseTestGroups(groupStrings []string) []testdata.TestGroup {
var groups []testdata.TestGroup
validGroups := map[string]testdata.TestGroup{
"basic": testdata.TestGroupBasic,
"advanced": testdata.TestGroupAdvanced,
"json": testdata.TestGroupJSON,
"knowledge": testdata.TestGroupKnowledge,
func parseTestGroups(groupStrings []string) []cases.TestGroup {
var groups []cases.TestGroup
validGroups := map[string]cases.TestGroup{
"basic": cases.TestGroupBasic,
"advanced": cases.TestGroupAdvanced,
"json": cases.TestGroupJSON,
"knowledge": cases.TestGroupKnowledge,
}
for _, groupStr := range groupStrings {
@@ -324,24 +363,38 @@ func convertToAgentResults(results tester.ProviderTestResults, prv provider.Prov
var totalLatency time.Duration
for _, testResult := range agentTestResults {
oldResult := TestResult{
Name: testResult.Name,
Type: string(testResult.Type),
Success: testResult.Success,
Error: testResult.Error,
Streaming: testResult.Streaming,
Reasoning: testResult.Reasoning,
LatencyMs: testResult.Latency.Milliseconds(),
Name: testResult.Name,
Type: string(testResult.Type),
Capability: string(testResult.Capability),
Success: testResult.Success,
Unsupported: testResult.Unsupported,
ContentFiltered: testResult.ContentFiltered,
Error: testResult.Error,
StopReason: testResult.StopReason,
Streaming: testResult.Streaming,
Reasoning: testResult.Reasoning,
LatencyMs: testResult.Latency.Milliseconds(),
}
if testResult.Group == testdata.TestGroupBasic {
switch {
case testResult.Capability != "":
result.CapabilityTests = append(result.CapabilityTests, oldResult)
case testResult.Group == cases.TestGroupBasic:
result.BasicTests = append(result.BasicTests, oldResult)
} else {
default:
result.AdvancedTests = append(result.AdvancedTests, oldResult)
}
if testResult.Unsupported {
continue
}
result.TotalTests++
if testResult.Success {
switch {
case testResult.Success:
result.TotalSuccess++
case testResult.ContentFiltered:
result.TotalFiltered++
}
if testResult.Reasoning {
result.Reasoning = true
@@ -359,10 +412,46 @@ func convertToAgentResults(results tester.ProviderTestResults, prv provider.Prov
return agentResults
}
func loadCustomTests(path string) (*testdata.TestRegistry, error) {
func loadCustomTests(path string) (*cases.TestRegistry, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("failed to read tests file: %w", err)
}
return testdata.LoadRegistryFromYAML(data)
return cases.LoadRegistryFromYAML(data)
}
func reportRouting(checks []providers.RoutingCheck) {
fmt.Println("Catalogue routing")
fmt.Println("=================================================")
var checked, missing, prefixed int
for _, check := range checks {
if !check.Checked {
fmt.Printf(" %-10s %3d shipped NOT CHECKED: %s\n", check.Door, check.Shipped, check.Skipped)
continue
}
checked++
missing += len(check.Missing)
prefixed += len(check.PrefixedOnly)
endpoint := check.Endpoint
if check.Prefix != "" {
endpoint += " as " + check.Prefix + "/<model>"
}
fmt.Printf(" %-10s %3d shipped %d not callable by %s\n",
check.Door, check.Shipped, len(check.Missing)+len(check.PrefixedOnly), endpoint)
for _, name := range check.Missing {
fmt.Printf(" %s\n", name)
}
for _, name := range check.PrefixedOnly {
fmt.Printf(" %s listed only behind a prefix\n", name)
}
}
fmt.Println("=================================================")
fmt.Printf("%d of %d doors answered; %d catalogue entries absent, %d listed only behind a prefix\n",
checked, len(checks), missing, prefixed)
if checked < len(checks) {
fmt.Println("a door that did not answer proves nothing about its catalogue")
}
}
+44
View File
@@ -0,0 +1,44 @@
package main
import (
"testing"
"pentagi/pkg/providers/pconfig"
"pentagi/pkg/providers/provider"
"pentagi/pkg/providers/tester"
"pentagi/pkg/providers/tester/cases"
)
type namedModelProvider struct{ provider.Provider }
func (namedModelProvider) Model(pconfig.ProviderOptionsType) string { return "probe-model" }
func TestMain_ConvertToAgentResults_KeepsStopReasonsAndCountsFilteredFailures(t *testing.T) {
results := tester.ProviderTestResults{
Simple: tester.AgentTestResults{
{Name: "refused call", Group: cases.TestGroupBasic, StopReason: "content_filter"},
{Name: "moderated", Group: cases.TestGroupAdvanced, ContentFiltered: true},
{Name: "broken", Group: cases.TestGroupAdvanced},
{Name: "fine", Group: cases.TestGroupBasic, Success: true},
},
}
converted := convertToAgentResults(results, namedModelProvider{})
if len(converted) != 1 {
t.Fatalf("converted = %+v, want one agent", converted)
}
agent := converted[0]
if len(agent.BasicTests) != 2 || agent.BasicTests[0].StopReason != "content_filter" {
t.Errorf("basic tests = %+v, want the runner's stop reason kept on the refused call", agent.BasicTests)
}
if agent.TotalFiltered != 1 {
t.Errorf("TotalFiltered = %d, want 1: a stop reason alone is not the vendor's filter", agent.TotalFiltered)
}
if agent.TotalTests != 4 || agent.TotalSuccess != 1 {
t.Errorf("tally = %d/%d, want 1/4: a filtered case is still a failure", agent.TotalSuccess, agent.TotalTests)
}
if len(agent.AdvancedTests) != 2 || !agent.AdvancedTests[0].ContentFiltered || agent.AdvancedTests[1].ContentFiltered {
t.Errorf("advanced tests = %+v, want the mark on the moderated one only", agent.AdvancedTests)
}
}
+28 -14
View File
@@ -4,26 +4,40 @@ import "time"
// TestResult represents the result of a single test for CLI compatibility
type TestResult struct {
Name string
Type string
Success bool
Error error
Streaming bool
Reasoning bool
LatencyMs int64
Response string
Expected string
Name string
Type string
Capability string
Success bool
// Unsupported means the case could not exercise what it asks for on this
// configuration (a typed capability refusal, or an output limit the library
// changed before the vendor), and Error says why. It does not count against
// TotalSuccess/TotalTests.
Unsupported bool
ContentFiltered bool
Error error
StopReason string
Streaming bool
Reasoning bool
LatencyMs int64
Response string
Expected string
}
// AgentTestResult collects test results for each agent type for CLI compatibility
type AgentTestResult struct {
AgentType string
ModelName string
Reasoning bool
BasicTests []TestResult
AdvancedTests []TestResult
AgentType string
ModelName string
Reasoning bool
BasicTests []TestResult
AdvancedTests []TestResult
// CapabilityTests holds results for capability-gated tests (adaptive
// thinking, reasoning off, structured output) kept separate from
// Basic/AdvancedTests so the report can call out "does this optional
// capability work" without it affecting the primary pass/fail tally.
CapabilityTests []TestResult
TotalSuccess int
TotalTests int
TotalFiltered int
AverageLatency time.Duration
SkippedAdvanced bool
SkippedReason string
+176 -58
View File
@@ -1,8 +1,11 @@
package main
import (
"errors"
"fmt"
"io"
"os"
"strings"
"text/tabwriter"
"time"
)
@@ -24,8 +27,8 @@ func PrintAgentResults(result AgentTestResult) {
name = fmt.Sprintf("Streaming %s", name)
}
fmt.Printf("[%s] %s (%.3fs)\n", status, name, float64(test.LatencyMs)/1000)
if !test.Success && test.Error != nil {
fmt.Printf(" Error: %v\n", test.Error)
if note := failureText(test); !test.Success && note != "" {
fmt.Printf(" Error: %s\n", note)
}
}
}
@@ -43,8 +46,8 @@ func PrintAgentResults(result AgentTestResult) {
name = fmt.Sprintf("Streaming %s", name)
}
fmt.Printf("[%s] %s (%.3fs)\n", status, name, float64(test.LatencyMs)/1000)
if !test.Success && test.Error != nil {
fmt.Printf(" Error: %v\n", test.Error)
if note := failureText(test); !test.Success && note != "" {
fmt.Printf(" Error: %s\n", note)
}
}
} else if result.SkippedAdvanced {
@@ -52,8 +55,34 @@ func PrintAgentResults(result AgentTestResult) {
fmt.Printf(" %s\n", result.SkippedReason)
}
// Capability tests section (adaptive thinking / reasoning off / structured
// output): only present when the model was actually classified as
// supporting the capability, so its absence here means "not applicable to
// this model", not "not tested".
if len(result.CapabilityTests) > 0 {
fmt.Println("\nCapability Tests:")
for _, test := range result.CapabilityTests {
status := "✓"
switch {
case test.Unsupported:
status = "⊘"
case !test.Success:
status = "✗"
}
fmt.Printf("[%s] %s (%s) (%.3fs)\n", status, test.Name, test.Capability, float64(test.LatencyMs)/1000)
if test.Unsupported {
fmt.Printf(" Not supported by this model/provider: %v\n", test.Error)
} else if note := failureText(test); !test.Success && note != "" {
fmt.Printf(" Error: %s\n", note)
}
}
}
// Summary
successRate := float64(result.TotalSuccess) / float64(result.TotalTests) * 100
var successRate float64
if result.TotalTests > 0 {
successRate = float64(result.TotalSuccess) / float64(result.TotalTests) * 100
}
fmt.Printf("\nSummary: %d/%d (%.2f%%) successful tests\n",
result.TotalSuccess, result.TotalTests, successRate)
fmt.Printf("Average latency: %.3fs\n", result.AverageLatency.Seconds())
@@ -69,13 +98,17 @@ func PrintSummaryReport(results []AgentTestResult) {
fmt.Fprintln(w, "Agent\tModel\tReasoning\tSuccess Rate\tAvg Latency\t")
fmt.Fprintln(w, "-----\t-----\t----------\t-----------\t-----------\t")
var totalSuccess, totalTests int
var totalSuccess, totalTests, totalFiltered int
var totalLatency time.Duration
for _, result := range results {
success := result.TotalSuccess
total := result.TotalTests
successRate := float64(success) / float64(total) * 100
totalFiltered += result.TotalFiltered
var successRate float64
if total > 0 {
successRate = float64(success) / float64(total) * 100
}
fmt.Fprintf(w, "%s\t%s\t%t\t%d/%d (%.2f%%)\t%.3fs\t\n",
result.AgentType,
result.ModelName,
@@ -96,42 +129,74 @@ func PrintSummaryReport(results []AgentTestResult) {
overallSuccessRate := float64(totalSuccess) / float64(totalTests) * 100
overallAvgLatency := totalLatency / time.Duration(totalTests)
fmt.Printf("\nTotal: %d/%d (%.2f%%) successful tests\n", totalSuccess, totalTests, overallSuccessRate)
if totalFiltered > 0 {
fmt.Printf("Refused by a vendor's content filter: %d of the failed tests\n", totalFiltered)
}
fmt.Printf("Overall average latency: %.3fs\n", overallAvgLatency.Seconds())
}
}
type errWriter struct {
dst io.Writer
err error
}
func (ew *errWriter) Write(p []byte) (int, error) {
if ew.err != nil {
return 0, ew.err
}
n, err := ew.dst.Write(p)
ew.err = err
return n, err
}
// WriteReportToFile writes the test results to a report file in Markdown format
func WriteReportToFile(results []AgentTestResult, filePath string) error {
file, err := os.Create(filePath)
if err != nil {
return err
}
defer file.Close()
return writeReport(file, results)
}
func writeReport(dst io.WriteCloser, results []AgentTestResult) (err error) {
defer func() {
err = errors.Join(err, dst.Close())
}()
w := &errWriter{dst: dst}
// Write header
file.WriteString("# LLM Agent Testing Report\n\n")
file.WriteString(fmt.Sprintf("Generated: %s\n\n", time.Now().UTC().Format(time.RFC1123)))
_, _ = io.WriteString(w, "# LLM Agent Testing Report\n\n")
fmt.Fprintf(w, "Generated: %s\n\n", time.Now().UTC().Format(time.RFC1123))
// Create a table for overall results
file.WriteString("## Overall Results\n\n")
file.WriteString("| Agent | Model | Reasoning | Success Rate | Average Latency |\n")
file.WriteString("|-------|-------|-----------|--------------|-----------------|\n")
_, _ = io.WriteString(w, "## Overall Results\n\n")
_, _ = io.WriteString(w, "| Agent | Model | Reasoning | Success Rate | Average Latency |\n")
_, _ = io.WriteString(w, "|-------|-------|-----------|--------------|-----------------|\n")
var totalSuccess, totalTests int
var totalSuccess, totalTests, totalFiltered int
var totalLatency time.Duration
for _, result := range results {
success := result.TotalSuccess
total := result.TotalTests
successRate := float64(success) / float64(total) * 100
file.WriteString(fmt.Sprintf("| %s | %s | %t | %d/%d (%.2f%%) | %.3fs |\n",
totalFiltered += result.TotalFiltered
var successRate float64
if total > 0 {
successRate = float64(success) / float64(total) * 100
}
fmt.Fprintf(w, "| %s | %s | %t | %d/%d (%.2f%%) | %.3fs |\n",
result.AgentType,
result.ModelName,
result.Reasoning,
success,
total,
successRate,
result.AverageLatency.Seconds()))
result.AverageLatency.Seconds())
totalSuccess += success
totalTests += total
@@ -142,85 +207,138 @@ func WriteReportToFile(results []AgentTestResult, filePath string) error {
if totalTests > 0 {
overallSuccessRate := float64(totalSuccess) / float64(totalTests) * 100
overallAvgLatency := totalLatency / time.Duration(totalTests)
file.WriteString(fmt.Sprintf("\n**Total**: %d/%d (%.2f%%) successful tests\n",
totalSuccess, totalTests, overallSuccessRate))
file.WriteString(fmt.Sprintf("**Overall average latency**: %.3fs\n\n", overallAvgLatency.Seconds()))
fmt.Fprintf(w, "\n**Total**: %d/%d (%.2f%%) successful tests\n",
totalSuccess, totalTests, overallSuccessRate)
if totalFiltered > 0 {
fmt.Fprintf(w, "**Refused by a vendor's content filter**: %d of the failed tests\n", totalFiltered)
}
fmt.Fprintf(w, "**Overall average latency**: %.3fs\n\n", overallAvgLatency.Seconds())
}
// Write detailed results for each agent
file.WriteString("## Detailed Results\n\n")
_, _ = io.WriteString(w, "## Detailed Results\n\n")
for _, result := range results {
file.WriteString(fmt.Sprintf("### %s (%s)\n\n", result.AgentType, result.ModelName))
fmt.Fprintf(w, "### %s (%s)\n\n", result.AgentType, result.ModelName)
// Basic tests
if len(result.BasicTests) > 0 {
file.WriteString("#### Basic Tests\n\n")
file.WriteString("| Test | Result | Latency | Error |\n")
file.WriteString("|------|--------|---------|-------|\n")
_, _ = io.WriteString(w, "#### Basic Tests\n\n")
_, _ = io.WriteString(w, "| Test | Result | Latency | Error |\n")
_, _ = io.WriteString(w, "|------|--------|---------|-------|\n")
for _, test := range result.BasicTests {
status := "✅ Pass"
errorMsg := ""
if !test.Success {
status = "❌ Fail"
if test.Error != nil {
errorMsg = TruncateString(EscapeMarkdown(test.Error.Error()), 150)
}
}
status, errorMsg := rowStatus(test)
name := test.Name
if test.Streaming {
name = fmt.Sprintf("Streaming %s", name)
}
file.WriteString(fmt.Sprintf("| %s | %s | %.3fs | %s |\n",
fmt.Fprintf(w, "| %s | %s | %.3fs | %s |\n",
name,
status,
float64(test.LatencyMs)/1000,
errorMsg))
errorMsg)
}
file.WriteString("\n")
_, _ = io.WriteString(w, "\n")
}
// Advanced tests
if len(result.AdvancedTests) > 0 {
file.WriteString("#### Advanced Tests\n\n")
file.WriteString("| Test | Result | Latency | Error |\n")
file.WriteString("|------|--------|---------|-------|\n")
_, _ = io.WriteString(w, "#### Advanced Tests\n\n")
_, _ = io.WriteString(w, "| Test | Result | Latency | Error |\n")
_, _ = io.WriteString(w, "|------|--------|---------|-------|\n")
for _, test := range result.AdvancedTests {
status := "✅ Pass"
errorMsg := ""
if !test.Success {
status = "❌ Fail"
if test.Error != nil {
errorMsg = TruncateString(EscapeMarkdown(test.Error.Error()), 150)
}
}
status, errorMsg := rowStatus(test)
name := test.Name
if test.Streaming {
name = fmt.Sprintf("Streaming %s", name)
}
file.WriteString(fmt.Sprintf("| %s | %s | %.3fs | %s |\n",
fmt.Fprintf(w, "| %s | %s | %.3fs | %s |\n",
name,
status,
float64(test.LatencyMs)/1000,
errorMsg))
errorMsg)
}
file.WriteString("\n")
_, _ = io.WriteString(w, "\n")
} else if result.SkippedAdvanced {
file.WriteString("#### Advanced Tests\n\n")
file.WriteString(fmt.Sprintf("*%s*\n\n", result.SkippedReason))
_, _ = io.WriteString(w, "#### Advanced Tests\n\n")
fmt.Fprintf(w, "*%s*\n\n", result.SkippedReason)
}
// Capability tests (adaptive thinking / reasoning off / structured
// output) - absent entirely for a model not classified as supporting
// the capability at all, distinguished from "attempted but rejected"
// (Unsupported) and from a genuine failure.
if len(result.CapabilityTests) > 0 {
_, _ = io.WriteString(w, "#### Capability Tests\n\n")
_, _ = io.WriteString(w, "| Test | Capability | Result | Latency | Note |\n")
_, _ = io.WriteString(w, "|------|------------|--------|---------|------|\n")
for _, test := range result.CapabilityTests {
status, note := rowStatus(test)
fmt.Fprintf(w, "| %s | %s | %s | %.3fs | %s |\n",
test.Name,
test.Capability,
status,
float64(test.LatencyMs)/1000,
note)
}
_, _ = io.WriteString(w, "\n")
}
// Summary
successRate := float64(result.TotalSuccess) / float64(result.TotalTests) * 100
file.WriteString(fmt.Sprintf("**Summary**: %d/%d (%.2f%%) successful tests\n\n",
result.TotalSuccess, result.TotalTests, successRate))
file.WriteString(fmt.Sprintf("**Average latency**: %.3fs\n\n", result.AverageLatency.Seconds()))
file.WriteString("---\n\n")
var successRate float64
if result.TotalTests > 0 {
successRate = float64(result.TotalSuccess) / float64(result.TotalTests) * 100
}
fmt.Fprintf(w, "**Summary**: %d/%d (%.2f%%) successful tests\n\n",
result.TotalSuccess, result.TotalTests, successRate)
if result.TotalFiltered > 0 {
fmt.Fprintf(w, "**Refused by the vendor's content filter**: %d of the failed tests\n\n", result.TotalFiltered)
}
fmt.Fprintf(w, "**Average latency**: %.3fs\n\n", result.AverageLatency.Seconds())
_, _ = io.WriteString(w, "---\n\n")
}
return nil
return w.err
}
func rowStatus(test TestResult) (status, note string) {
switch {
case test.Unsupported:
if test.Error != nil {
note = TruncateString(EscapeMarkdown(test.Error.Error()), 150)
}
return "⊘ Not Supported", note
case test.Success:
return "✅ Pass", ""
default:
return failureStatus(test), TruncateString(EscapeMarkdown(failureText(test)), 150)
}
}
func failureStatus(test TestResult) string {
if test.ContentFiltered {
return "⛔ Filtered"
}
return "❌ Fail"
}
func failureText(test TestResult) string {
var text string
if test.Error != nil {
text = test.Error.Error()
}
if test.StopReason != "" && !strings.Contains(text, test.StopReason) {
if text != "" {
text += "; "
}
text += "stop reason: " + test.StopReason
}
return text
}
+249
View File
@@ -0,0 +1,249 @@
package main
import (
"errors"
"flag"
"io"
"io/fs"
"os"
"path/filepath"
"regexp"
"strings"
"testing"
"time"
)
var updateGolden = flag.Bool("update", false, "rewrite testdata/report.golden from the current output")
var generatedLine = regexp.MustCompile(`(?m)^Generated: .*$`)
func sampleResults() []AgentTestResult {
return []AgentTestResult{
{
AgentType: "assistant",
ModelName: "gpt-4o",
Reasoning: true,
BasicTests: []TestResult{
{Name: "simple call", Success: true, LatencyMs: 1200},
{Name: "streamed call", Success: true, Streaming: true, LatencyMs: 900},
{Name: "bad call", Error: errors.New("rate limited | try again"), LatencyMs: 300},
},
AdvancedTests: []TestResult{
{Name: "tool call", Success: true, LatencyMs: 2500},
{Name: "refused call", Error: errors.New("the model returned no answer"), StopReason: "content_filter", ContentFiltered: true, LatencyMs: 400},
},
CapabilityTests: []TestResult{
{Name: "adaptive thinking", Capability: "reasoning", Success: true, LatencyMs: 1500},
{Name: "structured output", Capability: "schema", Unsupported: true, Error: errors.New("not supported")},
{Name: "reasoning off", Capability: "reasoning", Error: errors.New("gateway timeout"), LatencyMs: 800},
},
TotalSuccess: 4,
TotalTests: 5,
TotalFiltered: 1,
AverageLatency: 1400 * time.Millisecond,
},
{
AgentType: "installer",
ModelName: "claude-sonnet",
BasicTests: []TestResult{{Name: "simple call", Success: true, LatencyMs: 700}},
TotalSuccess: 1,
TotalTests: 1,
AverageLatency: 700 * time.Millisecond,
SkippedAdvanced: true,
SkippedReason: "advanced tests skipped for this model",
},
{
AgentType: "empty",
ModelName: "none",
},
}
}
func TestReport_WriteReportToFile_KeepsTheReportShape(t *testing.T) {
path := filepath.Join(t.TempDir(), "report.md")
if err := WriteReportToFile(sampleResults(), path); err != nil {
t.Fatalf("WriteReportToFile: %v", err)
}
written, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read back: %v", err)
}
got := generatedLine.ReplaceAll(written, []byte("Generated: <stamped>"))
golden := filepath.Join("testdata", "report.golden")
if *updateGolden {
if err := os.MkdirAll("testdata", 0o755); err != nil {
t.Fatalf("mkdir testdata: %v", err)
}
if err := os.WriteFile(golden, got, 0o644); err != nil {
t.Fatalf("write golden: %v", err)
}
return
}
want, err := os.ReadFile(golden)
if err != nil {
t.Fatalf("read golden: %v", err)
}
if string(got) != string(want) {
t.Errorf("report changed shape;\n--- got ---\n%s\n--- want ---\n%s", got, want)
}
}
func TestReport_WriteReportToFile_FailsForAPathThatCannotBeCreated(t *testing.T) {
path := filepath.Join(t.TempDir(), "no-such-dir", "report.md")
if err := WriteReportToFile(sampleResults(), path); !errors.Is(err, fs.ErrNotExist) {
t.Errorf("writing into a missing directory returned %v, want a not-exist error", err)
}
}
type shortWriter struct {
limit int
written int
closed bool
}
func (w *shortWriter) Write(p []byte) (int, error) {
room := w.limit - w.written
if room <= 0 {
return 0, errors.New("no space left on device")
}
if len(p) <= room {
w.written += len(p)
return len(p), nil
}
w.written = w.limit
return room, errors.New("no space left on device")
}
func (w *shortWriter) Close() error {
w.closed = true
return nil
}
type failingCloser struct {
io.Writer
}
func (failingCloser) Close() error {
return errors.New("flush on close failed")
}
type flakyWriter struct {
failOn int
calls int
}
func (w *flakyWriter) Write(p []byte) (int, error) {
w.calls++
if w.calls == w.failOn {
return 0, errors.New("device busy")
}
return len(p), nil
}
func (w *flakyWriter) Close() error {
return nil
}
func TestReport_WriteReport_FailsWhenTheDestinationFails(t *testing.T) {
short := &shortWriter{limit: 200}
tests := []struct {
name string
dst io.WriteCloser
wantErr string
after func(t *testing.T)
}{
{
name: "a destination that runs out of room",
dst: short,
wantErr: "no space left on device",
after: func(t *testing.T) {
if short.written != 200 {
t.Errorf("wrote %d bytes, expected the writer to stop at its limit", short.written)
}
if !short.closed {
t.Error("the destination was not closed")
}
},
},
{name: "a close that fails", dst: failingCloser{Writer: io.Discard}, wantErr: "flush on close failed"},
{name: "a write that fails and then recovers", dst: &flakyWriter{failOn: 3}, wantErr: "device busy"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := writeReport(tt.dst, sampleResults())
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
t.Errorf("a report that was not fully written returned %v, want an error naming %q", err, tt.wantErr)
}
if tt.after != nil {
tt.after(t)
}
})
}
}
func TestReport_FailureText_NamesWhyTheModelStopped(t *testing.T) {
for _, tc := range []struct {
label string
test TestResult
want string
}{
{"error and stop reason", TestResult{Error: errors.New("no answer"), StopReason: "content_filter"},
"no answer; stop reason: content_filter"},
{"stop reason alone", TestResult{StopReason: "refusal"}, "stop reason: refusal"},
{"an error that already names it", TestResult{Error: errors.New(`stop reason "length"`), StopReason: "length"},
`stop reason "length"`},
{"neither", TestResult{}, ""},
} {
t.Run(tc.label, func(t *testing.T) {
if got := failureText(tc.test); got != tc.want {
t.Errorf("failureText = %q, want %q", got, tc.want)
}
})
}
}
type bufferCloser struct{ strings.Builder }
func (*bufferCloser) Close() error { return nil }
func TestReport_RowStatus_ShowsAnUnsupportedCaseWithItsReason(t *testing.T) {
results := []AgentTestResult{{
AgentType: "coder",
ModelName: "claude-haiku-4-5",
BasicTests: []TestResult{{
Name: "Answer Stops At The Output Limit",
Success: true,
Unsupported: true,
Error: errors.New("the output limit the case asks for did not reach the vendor"),
}},
}}
var out bufferCloser
if err := writeReport(&out, results); err != nil {
t.Fatalf("writeReport: %v", err)
}
if !strings.Contains(out.String(), "| Answer Stops At The Output Limit | ⊘ Not Supported |") {
t.Errorf("the case must read as not supported, not as a pass:\n%s", out.String())
}
if !strings.Contains(out.String(), "did not reach the vendor") {
t.Errorf("the report must carry the reason:\n%s", out.String())
}
}
+77
View File
@@ -0,0 +1,77 @@
# LLM Agent Testing Report
Generated: <stamped>
## Overall Results
| Agent | Model | Reasoning | Success Rate | Average Latency |
|-------|-------|-----------|--------------|-----------------|
| assistant | gpt-4o | true | 4/5 (80.00%) | 1.400s |
| installer | claude-sonnet | false | 1/1 (100.00%) | 0.700s |
| empty | none | false | 0/0 (0.00%) | 0.000s |
**Total**: 5/6 (83.33%) successful tests
**Refused by a vendor's content filter**: 1 of the failed tests
**Overall average latency**: 1.283s
## Detailed Results
### assistant (gpt-4o)
#### Basic Tests
| Test | Result | Latency | Error |
|------|--------|---------|-------|
| simple call | ✅ Pass | 1.200s | |
| Streaming streamed call | ✅ Pass | 0.900s | |
| bad call | ❌ Fail | 0.300s | rate limited \| try again |
#### Advanced Tests
| Test | Result | Latency | Error |
|------|--------|---------|-------|
| tool call | ✅ Pass | 2.500s | |
| refused call | ⛔ Filtered | 0.400s | the model returned no answer; stop reason: content\_filter |
#### Capability Tests
| Test | Capability | Result | Latency | Note |
|------|------------|--------|---------|------|
| adaptive thinking | reasoning | ✅ Pass | 1.500s | |
| structured output | schema | ⊘ Not Supported | 0.000s | not supported |
| reasoning off | reasoning | ❌ Fail | 0.800s | gateway timeout |
**Summary**: 4/5 (80.00%) successful tests
**Refused by the vendor's content filter**: 1 of the failed tests
**Average latency**: 1.400s
---
### installer (claude-sonnet)
#### Basic Tests
| Test | Result | Latency | Error |
|------|--------|---------|-------|
| simple call | ✅ Pass | 0.700s | |
#### Advanced Tests
*advanced tests skipped for this model*
**Summary**: 1/1 (100.00%) successful tests
**Average latency**: 0.700s
---
### empty (none)
**Summary**: 0/0 (0.00%) successful tests
**Average latency**: 0.000s
---
+5 -3
View File
@@ -12,10 +12,12 @@ func TruncateString(s string, maxLength int) string {
s = strings.ReplaceAll(s, "\n", " ")
s = strings.ReplaceAll(s, "\r", " ")
s = strings.ReplaceAll(s, "\t", " ")
if len(s) <= maxLength {
runes := []rune(s)
if len(runes) <= maxLength {
return s
}
return s[:maxLength-3] + "..."
return string(runes[:maxLength-3]) + "..."
}
// EscapeMarkdown escapes special characters in markdown
@@ -46,7 +48,7 @@ func EscapeMarkdown(text string) string {
result := text
for _, r := range replacements {
result = strings.Replace(result, r.from, r.to, -1)
result = strings.ReplaceAll(result, r.from, r.to)
}
return result
+33
View File
@@ -0,0 +1,33 @@
package main
import (
"testing"
"unicode/utf8"
)
func TestUtils_TruncateString_CutsWholeCharacters(t *testing.T) {
tests := []struct {
name string
input string
maxLength int
want string
}{
{name: "short enough is untouched", input: "ok", maxLength: 10, want: "ok"},
{name: "ascii is cut with an ellipsis", input: "abcdefghij", maxLength: 8, want: "abcde..."},
{name: "a multibyte answer keeps whole characters", input: "провайдер ответил", maxLength: 8, want: "прова..."},
{name: "the boundary itself is not cut", input: "провайд", maxLength: 7, want: "провайд"},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got := TruncateString(tc.input, tc.maxLength)
if got != tc.want {
t.Errorf("TruncateString(%q, %d) = %q, want %q", tc.input, tc.maxLength, got, tc.want)
}
if !utf8.ValidString(got) {
t.Errorf("the report line carries a broken character: %q", got)
}
})
}
}
+1 -1
View File
@@ -24,7 +24,7 @@ func (t *Tester) flush() error {
if err != nil {
return fmt.Errorf("failed to start transaction: %w", err)
}
defer tx.Rollback(t.ctx)
defer func() { _ = tx.Rollback(t.ctx) }()
result, err := tx.Exec(t.ctx, fmt.Sprintf("DELETE FROM %s", t.embeddingTableName))
if err != nil {
+24 -3
View File
@@ -2,6 +2,7 @@ package main
import (
"context"
"database/sql"
"flag"
"log"
"os"
@@ -10,12 +11,14 @@ import (
"time"
"pentagi/pkg/config"
"pentagi/pkg/database"
"pentagi/pkg/providers/embeddings"
"pentagi/pkg/terminal"
"pentagi/pkg/version"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/joho/godotenv"
_ "github.com/lib/pq"
"github.com/sirupsen/logrus"
)
@@ -62,14 +65,32 @@ func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Initialize database connection pool
// Create this tenant's schema and repoint DATABASE_URL at it before any
// consumer reads the DSN. No-op when TENANT_ID is empty.
if err := database.EnsureTenantSchema(ctx, cfg); err != nil {
log.Fatalf("Tenant schema initialization failed: %v", err)
}
// Verify search_path on a short-lived database/sql connection before the
// long-lived pgxpool is opened — same guard the main server uses.
verifyDB, err := sql.Open("postgres", cfg.DatabaseURL)
if err != nil {
log.Fatalf("Unable to open database for schema verification: %v", err)
}
verifyDB.SetMaxOpenConns(1)
if err := database.VerifySearchPath(ctx, verifyDB, cfg); err != nil {
verifyDB.Close()
log.Fatalf("Tenant schema verification failed: %v", err)
}
verifyDB.Close()
poolConfig, err := pgxpool.ParseConfig(cfg.DatabaseURL)
if err != nil {
log.Fatalf("Unable to parse database URL: %v", err)
}
poolConfig.MaxConns = 10
poolConfig.MinConns = 2
poolConfig.MaxConns = min(int32(cfg.DBVectorMaxConns), 10)
poolConfig.MinConns = min(int32(cfg.DBMaxIdleConns), 2, poolConfig.MaxConns)
poolConfig.MaxConnLifetime = time.Hour
poolConfig.MaxConnIdleTime = 30 * time.Minute
-1
View File
@@ -90,7 +90,6 @@ func validateSearchOptions(opts *SearchOptions) error {
return nil
}
// ParseSearchArgs parses command line arguments specific for search
func parseSearchArgs(args []string) (*SearchOptions, error) {
if len(args) == 0 {
return nil, fmt.Errorf("no arguments provided")
+21 -14
View File
@@ -29,7 +29,7 @@ import (
func main() {
envFile := flag.String("env", ".env", "Path to environment file")
providerName := flag.String("provider", "custom", "Provider name (openai, anthropic, gemini, bedrock, ollama, deepseek, glm, kimi, qwen, custom)")
providerName := flag.String("provider", "custom", "Provider name (openai, anthropic, gemini, bedrock, ollama, deepseek, glm, kimi, qwen, minimax, custom)")
flowID := flag.Int64("flow", 0, "Flow ID for testing functions that require it (0 means using mocks)")
userID := flag.Int64("user", 0, "User ID for testing functions that require it (1 is default admin user)")
taskID := flag.Int64("task", 0, "Task ID for testing functions with default unset")
@@ -63,21 +63,11 @@ func main() {
if err != nil && !errors.Is(err, obs.ErrNotConfigured) {
log.Fatalf("Unable to create langfuse client: %v\n", err)
}
defer func() {
if lfclient != nil {
lfclient.ForceFlush(context.Background())
}
}()
otelclient, err := obs.NewTelemetryClient(ctx, cfg)
if err != nil && !errors.Is(err, obs.ErrNotConfigured) {
log.Fatalf("Unable to create telemetry client: %v\n", err)
}
defer func() {
if otelclient != nil {
otelclient.ForceFlush(context.Background())
}
}()
obs.InitObserver(ctx, lfclient, otelclient, []logrus.Level{
logrus.DebugLevel,
@@ -85,17 +75,34 @@ func main() {
logrus.WarnLevel,
logrus.ErrorLevel,
})
// Drain telemetry on exit, bounded — an unreachable collector must not hang
// the tester on the SDK's per-provider timeouts.
defer func() {
drainCtx, cancelDrain := context.WithTimeout(context.Background(), 5*time.Second)
defer cancelDrain()
_ = obs.Observer.Drain(drainCtx)
}()
// Create this tenant's schema and repoint DATABASE_URL at it before any
// consumer reads the DSN. No-op when TENANT_ID is empty.
if err := database.EnsureTenantSchema(ctx, cfg); err != nil {
log.Fatalf("Tenant schema initialization failed: %v", err)
}
// Initialize database connection
db, err := sql.Open("postgres", cfg.DatabaseURL)
if err != nil {
log.Fatalf("Unable to open database: %v", err)
}
defer db.Close()
db.SetMaxOpenConns(10)
db.SetMaxIdleConns(2)
db.SetMaxOpenConns(min(cfg.DBMaxOpenConns, 10))
db.SetMaxIdleConns(min(cfg.DBMaxIdleConns, 2))
db.SetConnMaxLifetime(time.Hour)
if err := database.VerifySearchPath(ctx, db, cfg); err != nil {
log.Fatalf("Tenant schema verification failed: %v", err)
}
queries := database.New(db)
terminal.PrintHeader("Function Tester (ftester)")
+114 -12
View File
@@ -3,8 +3,10 @@ package mocks
import (
"context"
"encoding/json"
"fmt"
"pentagi/pkg/database"
"pentagi/pkg/graph/model"
"pentagi/pkg/terminal"
"pentagi/pkg/tools"
)
@@ -16,27 +18,33 @@ type ProxyProviders interface {
GetSearchLogProvider() tools.SearchLogProvider
GetTermLogProvider() tools.TermLogProvider
GetVectorStoreLogProvider() tools.VectorStoreLogProvider
GetToolCallLogProvider() tools.ToolCallLogProvider
GetKnowledgeProvider() tools.KnowledgeProvider
}
// proxyProviders contains all the proxy implementations for various providers
type proxyProviders struct {
screenshot *proxyScreenshotProvider
agentLog *proxyAgentLogProvider
msgLog *proxyMsgLogProvider
searchLog *proxySearchLogProvider
termLog *proxyTermLogProvider
vectorStoreLog *proxyVectorStoreLogProvider
screenshot *proxyScreenshotProvider
agentLog *proxyAgentLogProvider
msgLog *proxyMsgLogProvider
searchLog *proxySearchLogProvider
termLog *proxyTermLogProvider
vectorStoreLog *proxyVectorStoreLogProvider
toolCallLog *proxyToolCallLogProvider
knowledgeProvider *proxyKnowledgeProvider
}
// NewProxyProviders creates a new set of proxy providers
func NewProxyProviders() ProxyProviders {
return &proxyProviders{
screenshot: &proxyScreenshotProvider{},
agentLog: &proxyAgentLogProvider{},
msgLog: &proxyMsgLogProvider{},
searchLog: &proxySearchLogProvider{},
termLog: &proxyTermLogProvider{},
vectorStoreLog: &proxyVectorStoreLogProvider{},
screenshot: &proxyScreenshotProvider{},
agentLog: &proxyAgentLogProvider{},
msgLog: &proxyMsgLogProvider{},
searchLog: &proxySearchLogProvider{},
termLog: &proxyTermLogProvider{},
vectorStoreLog: &proxyVectorStoreLogProvider{},
toolCallLog: &proxyToolCallLogProvider{},
knowledgeProvider: &proxyKnowledgeProvider{},
}
}
@@ -64,6 +72,14 @@ func (p *proxyProviders) GetVectorStoreLogProvider() tools.VectorStoreLogProvide
return p.vectorStoreLog
}
func (p *proxyProviders) GetToolCallLogProvider() tools.ToolCallLogProvider {
return p.toolCallLog
}
func (p *proxyProviders) GetKnowledgeProvider() tools.KnowledgeProvider {
return p.knowledgeProvider
}
// proxyScreenshotProvider is a proxy implementation of ScreenshotProvider
type proxyScreenshotProvider struct{}
@@ -225,6 +241,17 @@ func (p *proxyTermLogProvider) PutMsg(
return 0, nil
}
func (p *proxyTermLogProvider) ContainerNotRunning(ctx context.Context, containerID int64, _, _ *int64) error {
terminal.PrintInfo("Container reported not running:")
terminal.PrintKeyValueFormat("Container ID", "%d", containerID)
return nil
}
func (p *proxyTermLogProvider) ContainerRunning(ctx context.Context, containerID int64, _, _ *int64) error {
return nil
}
// proxyVectorStoreLogProvider is a proxy implementation of VectorStoreLogProvider
type proxyVectorStoreLogProvider struct{}
@@ -259,3 +286,78 @@ func (p *proxyVectorStoreLogProvider) PutLog(
return 0, nil
}
// proxyToolCallLogProvider is a proxy implementation of ToolCallLogProvider
type proxyToolCallLogProvider struct{}
// PutLog implements the ToolCallLogProvider interface
func (p *proxyToolCallLogProvider) PutLog(ctx context.Context, callID string, name string, args json.RawMessage, taskID *int64, subtaskID *int64) (int64, error) {
terminal.PrintInfo("Tool call log saved:")
terminal.PrintKeyValue("Call ID", callID)
terminal.PrintKeyValue("Name", name)
terminal.PrintKeyValue("Args", string(args))
if taskID != nil {
terminal.PrintKeyValueFormat("Task ID", "%d", *taskID)
}
if subtaskID != nil {
terminal.PrintKeyValueFormat("Subtask ID", "%d", *subtaskID)
}
return 0, nil
}
// UpdateLogSuccess implements the ToolCallLogProvider interface
func (p *proxyToolCallLogProvider) UpdateLogSuccess(ctx context.Context, id int64, result string, durationSeconds float64) error {
terminal.PrintInfo("Tool call log success updated:")
terminal.PrintKeyValueFormat("ID", "%d", id)
terminal.PrintKeyValue("Result", result)
terminal.PrintKeyValueFormat("Duration Seconds", "%f", durationSeconds)
return nil
}
// UpdateLogFailed implements the ToolCallLogProvider interface
func (p *proxyToolCallLogProvider) UpdateLogFailed(ctx context.Context, id int64, result string, durationSeconds float64) error {
terminal.PrintInfo("Tool call log failed updated:")
terminal.PrintKeyValueFormat("ID", "%d", id)
terminal.PrintKeyValue("Result", result)
terminal.PrintKeyValueFormat("Duration Seconds", "%f", durationSeconds)
return nil
}
// proxyKnowledgeProvider is a proxy implementation of KnowledgeProvider
type proxyKnowledgeProvider struct{}
// KnowledgeDocumentCreated implements the KnowledgeProvider interface
func (p *proxyKnowledgeProvider) KnowledgeDocumentCreated(ctx context.Context, doc *model.KnowledgeDocument) {
terminal.PrintInfo("Knowledge document created:")
terminal.PrintKeyValue("ID", doc.ID)
terminal.PrintKeyValue("Type", string(doc.DocType))
terminal.PrintKeyValue("Content", doc.Content)
terminal.PrintKeyValue("Question", doc.Question)
if doc.Description != nil {
terminal.PrintKeyValue("Description", *doc.Description)
}
if doc.FlowID != nil {
terminal.PrintKeyValueFormat("Flow ID", "%d", *doc.FlowID)
}
if doc.TaskID != nil {
terminal.PrintKeyValueFormat("Task ID", "%d", *doc.TaskID)
}
if doc.SubtaskID != nil {
terminal.PrintKeyValueFormat("Subtask ID", "%d", *doc.SubtaskID)
}
if doc.GuideType != nil {
terminal.PrintKeyValue("Guide Type", string(*doc.GuideType))
}
if doc.AnswerType != nil {
terminal.PrintKeyValue("Answer Type", string(*doc.AnswerType))
}
if doc.CodeLang != nil {
terminal.PrintKeyValue("Code Lang", *doc.CodeLang)
}
terminal.PrintKeyValueFormat("Part Size", "%d", doc.PartSize)
terminal.PrintKeyValueFormat("Total Size", "%d", doc.TotalSize)
terminal.PrintKeyValue("Manual", fmt.Sprintf("%t", doc.Manual))
terminal.PrintKeyValueFormat("User ID", "%d", doc.UserID)
}
+127 -63
View File
@@ -40,11 +40,15 @@ func MockResponse(funcName string, args json.RawMessage) (string, error) {
terminal.PrintMock("File operation:")
terminal.PrintKeyValue("Operation", string(fileArgs.Action))
terminal.PrintKeyValue("Path", fileArgs.Path)
terminal.PrintKeyValue("Path", fileArgs.Path.String())
if fileArgs.Action == tools.ReadFile {
switch fileArgs.Action {
case tools.ReadFile:
resultObj = fmt.Sprintf("Mock content of file: %s\nThis is a sample content that would be read from the file.\nIt contains multiple lines to simulate a real file.", fileArgs.Path)
} else {
case tools.EditFile:
terminal.PrintKeyValue("Diff", fileArgs.Diff.String())
resultObj = fmt.Sprintf("Applied 1 diff hunk(s) to %s (mock)", fileArgs.Path)
default:
resultObj = fmt.Sprintf("file %s written successfully", fileArgs.Path)
}
@@ -79,9 +83,9 @@ func MockResponse(funcName string, args json.RawMessage) (string, error) {
var builder strings.Builder
for i := 1; i <= min(searchArgs.MaxResults.Int(), 5); i++ {
builder.WriteString(fmt.Sprintf("# %d. Mock Google Result %d for '%s'\n\n", i, i, searchArgs.Query))
builder.WriteString(fmt.Sprintf("## URL\nhttps://example.com/result%d\n\n", i))
builder.WriteString(fmt.Sprintf("## Snippet\n\nThis is a detailed mock snippet for search result %d that matches your query '%s'. It contains relevant information that would be returned by the real Google search API.\n\n", i, searchArgs.Query))
fmt.Fprintf(&builder, "# %d. Mock Google Result %d for '%s'\n\n", i, i, searchArgs.Query)
fmt.Fprintf(&builder, "## URL\nhttps://example.com/result%d\n\n", i)
fmt.Fprintf(&builder, "## Snippet\n\nThis is a detailed mock snippet for search result %d that matches your query '%s'. It contains relevant information that would be returned by the real Google search API.\n\n", i, searchArgs.Query)
}
resultObj = builder.String()
@@ -97,9 +101,9 @@ func MockResponse(funcName string, args json.RawMessage) (string, error) {
var builder strings.Builder
for i := 1; i <= min(searchArgs.MaxResults.Int(), 5); i++ {
builder.WriteString(fmt.Sprintf("# %d. Mock DuckDuckGo Result %d for '%s'\n\n", i, i, searchArgs.Query))
builder.WriteString(fmt.Sprintf("## URL\nhttps://example.com/duckduckgo/result%d\n\n", i))
builder.WriteString(fmt.Sprintf("## Description\n\nThis is a detailed mock description for search result %d that matches your query '%s'. DuckDuckGo would provide this kind of anonymous search result.\n\n", i, searchArgs.Query))
fmt.Fprintf(&builder, "# %d. Mock DuckDuckGo Result %d for '%s'\n\n", i, i, searchArgs.Query)
fmt.Fprintf(&builder, "## URL\nhttps://example.com/duckduckgo/result%d\n\n", i)
fmt.Fprintf(&builder, "## Description\n\nThis is a detailed mock description for search result %d that matches your query '%s'. DuckDuckGo would provide this kind of anonymous search result.\n\n", i, searchArgs.Query)
if i < min(searchArgs.MaxResults.Int(), 5) {
builder.WriteString("---\n\n")
@@ -119,15 +123,73 @@ func MockResponse(funcName string, args json.RawMessage) (string, error) {
var builder strings.Builder
builder.WriteString("# Answer\n\n")
builder.WriteString(fmt.Sprintf("This is a comprehensive answer to your query '%s' that would be generated by Tavily AI. It synthesizes information from multiple sources to provide you with the most relevant information.\n\n", searchArgs.Query))
fmt.Fprintf(&builder, "This is a comprehensive answer to your query '%s' that would be generated by Tavily AI. It synthesizes information from multiple sources to provide you with the most relevant information.\n\n", searchArgs.Query)
builder.WriteString("# Links\n\n")
for i := 1; i <= min(searchArgs.MaxResults.Int(), 3); i++ {
builder.WriteString(fmt.Sprintf("## %d. Mock Tavily Result %d\n\n", i, i))
builder.WriteString(fmt.Sprintf("* URL https://example.com/tavily/result%d\n", i))
builder.WriteString(fmt.Sprintf("* Match score %.3f\n\n", 0.95-float64(i-1)*0.1))
builder.WriteString(fmt.Sprintf("### Short content\n\nHere is a brief summary of the content from this search result related to '%s'.\n\n", searchArgs.Query))
builder.WriteString(fmt.Sprintf("### Content\n\nThis is the full detailed content that would be retrieved from the URL. It contains comprehensive information about '%s' that helps answer your query with specific facts and data points that would be relevant to your search.\n\n", searchArgs.Query))
fmt.Fprintf(&builder, "## %d. Mock Tavily Result %d\n\n", i, i)
fmt.Fprintf(&builder, "* URL https://example.com/tavily/result%d\n", i)
fmt.Fprintf(&builder, "* Match score %.3f\n\n", 0.95-float64(i-1)*0.1)
fmt.Fprintf(&builder, "### Short content\n\nHere is a brief summary of the content from this search result related to '%s'.\n\n", searchArgs.Query)
fmt.Fprintf(&builder, "### Content\n\nThis is the full detailed content that would be retrieved from the URL. It contains comprehensive information about '%s' that helps answer your query with specific facts and data points that would be relevant to your search.\n\n", searchArgs.Query)
}
resultObj = builder.String()
case tools.WebSearchToolName:
var searchArgs tools.WebSearchAction
if err := json.Unmarshal(args, &searchArgs); err != nil {
return "", fmt.Errorf("error unmarshaling web_search arguments: %w", err)
}
mode := strings.ToLower(strings.TrimSpace(searchArgs.Mode.String()))
if mode == "" {
mode = "answer"
}
n := searchArgs.MaxResults.Int()
if n < 1 || n > 3 {
n = 3
}
terminal.PrintMock("web_search:")
terminal.PrintKeyValue("Query", searchArgs.Query)
terminal.PrintKeyValue("Mode", mode)
var builder strings.Builder
fmt.Fprintf(&builder, "# Mock web_search result (mode=%s)\n\n", mode)
fmt.Fprintf(&builder, "The web_search orchestrator would pick the best available engine for mode '%s', retry transient failures, and fall back across providers automatically.\n\n", mode)
switch mode {
case "links":
builder.WriteString("# Links\n\n")
for i := 1; i <= n; i++ {
fmt.Fprintf(&builder, "## %d. Mock result %d\n\n* URL https://example.com/web_search/result%d\n\n### Snippet\n\nBrief snippet about '%s'.\n\n", i, i, i, searchArgs.Query)
}
case "exploit":
fmt.Fprintf(&builder, "# Exploits\n\n## 1. Mock exploit for '%s'\n\n* URL https://sploitus.com/exploit/mock\n* CVSS 9.8\n\n", searchArgs.Query)
default: // answer / research
fmt.Fprintf(&builder, "# Answer\n\nThis is a synthesized mock answer to '%s' that web_search would return in mode '%s', combining multiple sources.\n", searchArgs.Query, mode)
}
resultObj = builder.String()
case tools.FirecrawlToolName:
var searchArgs tools.SearchAction
if err := json.Unmarshal(args, &searchArgs); err != nil {
return "", fmt.Errorf("error unmarshaling search arguments: %w", err)
}
terminal.PrintMock("Firecrawl search:")
terminal.PrintKeyValue("Query", searchArgs.Query)
terminal.PrintKeyValueFormat("Max results", "%d", searchArgs.MaxResults.Int())
var builder strings.Builder
builder.WriteString("# Links\n\n")
for i := 1; i <= min(searchArgs.MaxResults.Int(), 3); i++ {
fmt.Fprintf(&builder, "## %d. Mock Firecrawl Result %d\n\n", i, i)
fmt.Fprintf(&builder, "* URL https://example.com/firecrawl/result%d\n\n", i)
fmt.Fprintf(&builder, "### Short content\n\nHere is a brief description of the content from this search result related to '%s'.\n\n", searchArgs.Query)
fmt.Fprintf(&builder, "### Raw content for %d. Mock Firecrawl Result %d\n\nThis is the full scraped markdown content that Firecrawl would retrieve from the URL. It contains comprehensive information about '%s' that helps answer your query with specific facts and data points relevant to your search.\n\n", i, i, searchArgs.Query)
}
resultObj = builder.String()
@@ -144,11 +206,11 @@ func MockResponse(funcName string, args json.RawMessage) (string, error) {
var builder strings.Builder
builder.WriteString("# Answer\n\n")
builder.WriteString(fmt.Sprintf("Here is the Traversaal answer to your query '%s'. Traversaal provides concise answers based on web information with relevant links for further exploration.\n\n", searchArgs.Query))
fmt.Fprintf(&builder, "Here is the Traversaal answer to your query '%s'. Traversaal provides concise answers based on web information with relevant links for further exploration.\n\n", searchArgs.Query)
builder.WriteString("# Links\n\n")
for i := 1; i <= min(searchArgs.MaxResults.Int(), 5); i++ {
builder.WriteString(fmt.Sprintf("%d. https://example.com/traversaal/resource%d\n", i, i))
fmt.Fprintf(&builder, "%d. https://example.com/traversaal/resource%d\n", i, i)
}
resultObj = builder.String()
@@ -165,13 +227,13 @@ func MockResponse(funcName string, args json.RawMessage) (string, error) {
var builder strings.Builder
builder.WriteString("# Answer\n\n")
builder.WriteString(fmt.Sprintf("This is a detailed research report from Perplexity AI about '%s'. Perplexity provides comprehensive answers by synthesizing information from various sources and augmenting it with AI analysis.\n\n", searchArgs.Query))
fmt.Fprintf(&builder, "This is a detailed research report from Perplexity AI about '%s'. Perplexity provides comprehensive answers by synthesizing information from various sources and augmenting it with AI analysis.\n\n", searchArgs.Query)
builder.WriteString("The query you've asked about requires examining multiple perspectives and sources. Based on recent information, here's a thorough analysis of the topic with key insights and developments.\n\n")
builder.WriteString("First, it's important to understand the background of this subject. Several authoritative sources indicate that this is an evolving area with recent developments. The most current research suggests that...\n\n")
builder.WriteString("\n\n# Citations\n\n")
for i := 1; i <= min(searchArgs.MaxResults.Int(), 3); i++ {
builder.WriteString(fmt.Sprintf("%d. https://example.com/perplexity/citation%d\n", i, i))
fmt.Fprintf(&builder, "%d. https://example.com/perplexity/citation%d\n", i, i)
}
resultObj = builder.String()
@@ -189,23 +251,23 @@ func MockResponse(funcName string, args json.RawMessage) (string, error) {
terminal.PrintMock("Sploitus search:")
terminal.PrintKeyValue("Query", sploitusArgs.Query)
terminal.PrintKeyValue("Exploit type", exploitType)
terminal.PrintKeyValue("Sort", sploitusArgs.Sort)
terminal.PrintKeyValue("Exploit type", exploitType.String())
terminal.PrintKeyValue("Sort", sploitusArgs.Sort.String())
terminal.PrintKeyValueFormat("Max results", "%d", sploitusArgs.MaxResults.Int())
var builder strings.Builder
builder.WriteString("# Sploitus Search Results\n\n")
builder.WriteString(fmt.Sprintf("**Query:** `%s` \n", sploitusArgs.Query))
builder.WriteString(fmt.Sprintf("**Type:** %s \n", exploitType))
builder.WriteString(fmt.Sprintf("**Total matches on Sploitus:** %d\n\n", 200))
fmt.Fprintf(&builder, "**Query:** `%s` \n", sploitusArgs.Query)
fmt.Fprintf(&builder, "**Type:** %s \n", exploitType)
fmt.Fprintf(&builder, "**Total matches on Sploitus:** %d\n\n", 200)
builder.WriteString("---\n\n")
maxResults := min(sploitusArgs.MaxResults.Int(), 3)
if exploitType == "tools" {
builder.WriteString(fmt.Sprintf("## Security Tools (showing up to %d)\n\n", maxResults))
fmt.Fprintf(&builder, "## Security Tools (showing up to %d)\n\n", maxResults)
for i := 1; i <= maxResults; i++ {
builder.WriteString(fmt.Sprintf("### %d. SQLMap - Automated SQL Injection Tool\n\n", i))
fmt.Fprintf(&builder, "### %d. SQLMap - Automated SQL Injection Tool\n\n", i)
builder.WriteString("**URL:** https://github.com/sqlmapproject/sqlmap \n")
builder.WriteString("**Download:** https://github.com/sqlmapproject/sqlmap \n")
builder.WriteString("**Source Type:** kitploit \n")
@@ -213,7 +275,7 @@ func MockResponse(funcName string, args json.RawMessage) (string, error) {
builder.WriteString("\n---\n\n")
}
} else {
builder.WriteString(fmt.Sprintf("## Exploits (showing up to %d)\n\n", maxResults))
fmt.Fprintf(&builder, "## Exploits (showing up to %d)\n\n", maxResults)
builder.WriteString("### 1. SSTI-to-RCE-Python-Eval-Bypass\n\n")
builder.WriteString("**URL:** https://github.com/Rohitberiwala/SSTI-to-RCE-Python-Eval-Bypass \n")
@@ -261,14 +323,14 @@ func MockResponse(funcName string, args json.RawMessage) (string, error) {
var builder strings.Builder
builder.WriteString("# Search Results\n\n")
builder.WriteString(fmt.Sprintf("This is a mock response from the Searxng meta search engine for query '%s'. In a real implementation, this would return actual search results aggregated from multiple search engines with customizable categories, language settings, and safety filters.\n\n", searchArgs.Query))
fmt.Fprintf(&builder, "This is a mock response from the Searxng meta search engine for query '%s'. In a real implementation, this would return actual search results aggregated from multiple search engines with customizable categories, language settings, and safety filters.\n\n", searchArgs.Query)
builder.WriteString("## Results\n\n")
for i := 1; i <= min(searchArgs.MaxResults.Int(), 5); i++ {
builder.WriteString(fmt.Sprintf("%d. **Mock Result %d** - Mock title about %s\n", i, i, searchArgs.Query))
builder.WriteString(fmt.Sprintf(" URL: https://example.com/searxng/result%d\n", i))
builder.WriteString(fmt.Sprintf(" Source: Mock Engine %d\n", i))
builder.WriteString(fmt.Sprintf(" Content: This is a mock content snippet that would appear in a real Searxng search result. It contains relevant information about '%s' that helps answer your query.\n\n", searchArgs.Query))
fmt.Fprintf(&builder, "%d. **Mock Result %d** - Mock title about %s\n", i, i, searchArgs.Query)
fmt.Fprintf(&builder, " URL: https://example.com/searxng/result%d\n", i)
fmt.Fprintf(&builder, " Source: Mock Engine %d\n", i)
fmt.Fprintf(&builder, " Content: This is a mock content snippet that would appear in a real Searxng search result. It contains relevant information about '%s' that helps answer your query.\n\n", searchArgs.Query)
}
builder.WriteString("## Quick Answers\n\n")
@@ -276,9 +338,9 @@ func MockResponse(funcName string, args json.RawMessage) (string, error) {
builder.WriteString("- Related search: You might also be interested in searching for related terms.\n\n")
builder.WriteString("## Related Searches\n\n")
builder.WriteString(fmt.Sprintf("- %s alternatives\n", searchArgs.Query))
builder.WriteString(fmt.Sprintf("- %s tutorial\n", searchArgs.Query))
builder.WriteString(fmt.Sprintf("- %s vs other search engines\n", searchArgs.Query))
fmt.Fprintf(&builder, "- %s alternatives\n", searchArgs.Query)
fmt.Fprintf(&builder, "- %s tutorial\n", searchArgs.Query)
fmt.Fprintf(&builder, "- %s vs other search engines\n", searchArgs.Query)
resultObj = builder.String()
@@ -363,15 +425,15 @@ func MockResponse(funcName string, args json.RawMessage) (string, error) {
var builder strings.Builder
builder.WriteString("# Match score 0.92\n\n")
if searchMemoryArgs.TaskID != nil {
builder.WriteString(fmt.Sprintf("# Task ID %d\n\n", searchMemoryArgs.TaskID.Int64()))
fmt.Fprintf(&builder, "# Task ID %d\n\n", searchMemoryArgs.TaskID.Int64())
}
if searchMemoryArgs.SubtaskID != nil {
builder.WriteString(fmt.Sprintf("# Subtask ID %d\n\n", searchMemoryArgs.SubtaskID.Int64()))
fmt.Fprintf(&builder, "# Subtask ID %d\n\n", searchMemoryArgs.SubtaskID.Int64())
}
builder.WriteString("# Tool Name 'terminal'\n\n")
builder.WriteString("# Tool Description\n\nCalls a terminal command in blocking mode with hard limit timeout 1200 seconds and optimum timeout 60 seconds\n\n")
builder.WriteString("# Tool Description\n\nCalls a terminal command in blocking mode. Use timeout=0 or a negative value to apply the configured server default timeout. Explicit positive values are accepted up to 10800 seconds (3 hours); values outside this range are replaced by the server default\n\n")
builder.WriteString("# Chunk\n\n")
builder.WriteString(fmt.Sprintf("This is a memory chunk related to your questions '%s'. It contains information about previous commands, outputs, and relevant context that was stored in the vector database.\n\n", questionsText))
fmt.Fprintf(&builder, "This is a memory chunk related to your questions '%s'. It contains information about previous commands, outputs, and relevant context that was stored in the vector database.\n\n", questionsText)
builder.WriteString("---------------------------\n")
builder.WriteString("# Match score 0.85\n\n")
builder.WriteString("# Tool Name 'file'\n\n")
@@ -392,15 +454,16 @@ func MockResponse(funcName string, args json.RawMessage) (string, error) {
for i, q := range searchGuideArgs.Questions {
terminal.PrintKeyValueFormat(fmt.Sprintf("Question %d", i+1), "%s", q)
}
terminal.PrintKeyValue("Guide type", searchGuideArgs.Type)
terminal.PrintKeyValue("Guide type", searchGuideArgs.Type.String())
questionsText := strings.Join(searchGuideArgs.Questions, " | ")
if searchGuideArgs.Type == "pentest" {
switch searchGuideArgs.Type {
case "pentest":
resultObj = fmt.Sprintf("# Original Guide Type: pentest\n\n# Original Guide Questions\n\n%s\n\n## Penetration Testing Guide\n\nThis guide provides a step-by-step approach for conducting a penetration test on the target system.\n\n### 1. Reconnaissance\n- Gather information about the target using OSINT tools\n- Identify potential entry points and attack surfaces\n\n### 2. Scanning\n- Use tools like Nmap to scan for open ports and services\n- Identify vulnerabilities using automated scanners\n\n### 3. Exploitation\n- Attempt to exploit identified vulnerabilities\n- Document successful attack vectors\n\n### 4. Post-Exploitation\n- Maintain access and explore the system\n- Identify sensitive data and potential lateral movement paths\n\n### 5. Reporting\n- Document all findings with proof of concept\n- Provide remediation recommendations\n\n", questionsText)
} else if searchGuideArgs.Type == "install" {
case "install":
resultObj = fmt.Sprintf("# Original Guide Type: install\n\n# Original Guide Questions\n\n%s\n\n## Installation Guide\n\n### Prerequisites\n- Operating System: Linux/macOS/Windows\n- Required dependencies: [list]\n\n### Installation Steps\n1. Download the software from the official repository\n ```bash\n git clone https://github.com/example/software.git\n ```\n\n2. Navigate to the project directory\n ```bash\n cd software\n ```\n\n3. Install dependencies\n ```bash\n npm install\n ```\n\n4. Build the project\n ```bash\n npm run build\n ```\n\n5. Verify installation\n ```bash\n npm test\n ```\n\n### Troubleshooting\n- Common issue 1: [solution]\n- Common issue 2: [solution]\n\n", questionsText)
} else {
default:
resultObj = fmt.Sprintf("# Original Guide Type: %s\n\n# Original Guide Questions\n\n%s\n\n## Guide Content\n\nThis is a comprehensive guide for the requested type '%s'. It contains detailed instructions, best practices, and examples tailored to your specific questions.\n\n### Section 1: Getting Started\n[Detailed content would be here]\n\n### Section 2: Main Procedures\n[Step-by-step instructions would be here]\n\n### Section 3: Advanced Techniques\n[Advanced content would be here]\n\n### Section 4: Troubleshooting\n[Common issues and solutions would be here]\n\n", searchGuideArgs.Type, questionsText, searchGuideArgs.Type)
}
@@ -411,7 +474,7 @@ func MockResponse(funcName string, args json.RawMessage) (string, error) {
}
terminal.PrintMock("Store guide:")
terminal.PrintKeyValue("Type", storeGuideArgs.Type)
terminal.PrintKeyValue("Type", storeGuideArgs.Type.String())
terminal.PrintKeyValueFormat("Guide length", "%d chars", len(storeGuideArgs.Guide))
terminal.PrintKeyValue("Guide question", storeGuideArgs.Question)
@@ -428,7 +491,7 @@ func MockResponse(funcName string, args json.RawMessage) (string, error) {
for i, q := range searchAnswerArgs.Questions {
terminal.PrintKeyValueFormat(fmt.Sprintf("Question %d", i+1), "%s", q)
}
terminal.PrintKeyValue("Answer type", searchAnswerArgs.Type)
terminal.PrintKeyValue("Answer type", searchAnswerArgs.Type.String())
questionsText := strings.Join(searchAnswerArgs.Questions, " | ")
@@ -445,7 +508,7 @@ func MockResponse(funcName string, args json.RawMessage) (string, error) {
}
terminal.PrintMock("Store answer:")
terminal.PrintKeyValue("Type", storeAnswerArgs.Type)
terminal.PrintKeyValue("Type", storeAnswerArgs.Type.String())
terminal.PrintKeyValueFormat("Answer length", "%d chars", len(storeAnswerArgs.Answer))
terminal.PrintKeyValue("Question", storeAnswerArgs.Question)
@@ -462,17 +525,18 @@ func MockResponse(funcName string, args json.RawMessage) (string, error) {
for i, q := range searchCodeArgs.Questions {
terminal.PrintKeyValueFormat(fmt.Sprintf("Question %d", i+1), "%s", q)
}
terminal.PrintKeyValue("Language", searchCodeArgs.Lang)
terminal.PrintKeyValue("Language", searchCodeArgs.Lang.String())
questionsText := strings.Join(searchCodeArgs.Questions, " | ")
var mockCode string
if searchCodeArgs.Lang == "python" {
switch searchCodeArgs.Lang {
case "python":
mockCode = "def example_function(param1, param2='default'):\n \"\"\"This is an example Python function that demonstrates a pattern.\n \n Args:\n param1: The first parameter\n param2: The second parameter with default value\n \n Returns:\n The processed result\n \"\"\"\n result = {}\n \n # Process the parameters\n if param1 is not None:\n result['param1'] = param1\n \n # Additional processing\n if param2 != 'default':\n result['param2'] = param2\n \n return result\n\n# Example usage\nif __name__ == '__main__':\n output = example_function('test', 'custom')\n print(output)"
} else if searchCodeArgs.Lang == "javascript" || searchCodeArgs.Lang == "js" {
case "javascript", "js":
mockCode = "/**\n * Example JavaScript function that demonstrates a pattern\n * @param {Object} options - Configuration options\n * @param {string} options.name - The name parameter\n * @param {number} [options.count=1] - Optional count parameter\n * @returns {Object} The processed result\n */\nfunction exampleFunction(options) {\n const { name, count = 1 } = options;\n \n // Input validation\n if (!name) {\n throw new Error('Name is required');\n }\n \n // Process the data\n const result = {\n processedName: name.toUpperCase(),\n repeatedCount: Array(count).fill(name).join(', ')\n };\n \n return result;\n}\n\n// Example usage\nconst output = exampleFunction({ name: 'test', count: 3 });\nconsole.log(output);"
} else {
mockCode = fmt.Sprintf("// Example code in %s language\n// This is a mock code snippet that would be returned from the vector database\n\n// Main function definition\nfunction exampleFunction(param) {\n // Initialization\n const result = [];\n \n // Processing logic\n for (let i = 0; i < param.length; i++) {\n result.push(processItem(param[i]));\n }\n \n return result;\n}\n\n// Helper function\nfunction processItem(item) {\n return item.transform();\n}", searchCodeArgs.Lang)
default:
mockCode = fmt.Sprintf("// Example code in %s language\n// This is a mock code snippet that would be returned from the vector database\n\n// Main function definition\nfunction exampleFunction(param) {\n // Initialization\n const result = [];\n \n // Processing logic\n for (let i = 0; i < param.length; i++) {\n result.push(processItem(param[i]));\n }\n \n return result;\n}\n\n// Helper function\nfunction processItem(item) {\n return item.transform();\n}", searchCodeArgs.Lang.String())
}
resultObj = fmt.Sprintf("# Original Code Questions\n\n%s\n\n# Original Code Description\n\nThis code sample demonstrates the implementation pattern for handling the specific scenarios you asked about. It includes proper error handling, input validation, and follows best practices for %s.\n\n```%s\n%s\n```\n\n", questionsText, searchCodeArgs.Lang, searchCodeArgs.Lang, mockCode)
@@ -484,7 +548,7 @@ func MockResponse(funcName string, args json.RawMessage) (string, error) {
}
terminal.PrintMock("Store code:")
terminal.PrintKeyValue("Language", storeCodeArgs.Lang)
terminal.PrintKeyValue("Language", storeCodeArgs.Lang.String())
terminal.PrintKeyValueFormat("Code length", "%d chars", len(storeCodeArgs.Code))
terminal.PrintKeyValue("Question", storeCodeArgs.Question)
terminal.PrintKeyValue("Description", storeCodeArgs.Description)
@@ -498,7 +562,7 @@ func MockResponse(funcName string, args json.RawMessage) (string, error) {
}
terminal.PrintMock("Graphiti Search:")
terminal.PrintKeyValue("Search Type", searchArgs.SearchType)
terminal.PrintKeyValue("Search Type", searchArgs.SearchType.String())
terminal.PrintKeyValue("Query", searchArgs.Query)
var builder strings.Builder
@@ -506,7 +570,7 @@ func MockResponse(funcName string, args json.RawMessage) (string, error) {
switch searchArgs.SearchType {
case "recent_context":
builder.WriteString("# Recent Context\n\n")
builder.WriteString(fmt.Sprintf("**Query:** %s\n\n", searchArgs.Query))
fmt.Fprintf(&builder, "**Query:** %s\n\n", searchArgs.Query)
builder.WriteString("**Time Window:** 2025-01-19T10:00:00Z to 2025-01-19T18:00:00Z\n\n")
builder.WriteString("## Recently Discovered Entities\n\n")
builder.WriteString("1. **Target Server** (score: 0.95)\n")
@@ -520,7 +584,7 @@ func MockResponse(funcName string, args json.RawMessage) (string, error) {
case "successful_tools":
builder.WriteString("# Successful Tools & Techniques\n\n")
builder.WriteString(fmt.Sprintf("**Query:** %s\n\n", searchArgs.Query))
fmt.Fprintf(&builder, "**Query:** %s\n\n", searchArgs.Query)
builder.WriteString("## Successful Executions\n\n")
builder.WriteString("1. **pentester_agent** (score: 0.96)\n")
builder.WriteString(" - Description: Executed nmap scan\n")
@@ -531,7 +595,7 @@ func MockResponse(funcName string, args json.RawMessage) (string, error) {
case "episode_context":
builder.WriteString("# Episode Context Results\n\n")
builder.WriteString(fmt.Sprintf("**Query:** %s\n\n", searchArgs.Query))
fmt.Fprintf(&builder, "**Query:** %s\n\n", searchArgs.Query)
builder.WriteString("## Relevant Agent Activity\n\n")
builder.WriteString("1. **pentester_agent** (relevance: 0.94)\n")
builder.WriteString(" - Time: 2025-01-19T14:30:00Z\n")
@@ -543,7 +607,7 @@ func MockResponse(funcName string, args json.RawMessage) (string, error) {
case "entity_relationships":
builder.WriteString("# Entity Relationship Search Results\n\n")
builder.WriteString(fmt.Sprintf("**Query:** %s\n\n", searchArgs.Query))
fmt.Fprintf(&builder, "**Query:** %s\n\n", searchArgs.Query)
builder.WriteString("## Center Node: Target Server\n")
builder.WriteString("- UUID: mock-uuid-center-123\n")
builder.WriteString("- Summary: Main target system identified during reconnaissance\n\n")
@@ -564,8 +628,8 @@ func MockResponse(funcName string, args json.RawMessage) (string, error) {
case "temporal_window":
builder.WriteString("# Temporal Search Results\n\n")
builder.WriteString(fmt.Sprintf("**Query:** %s\n\n", searchArgs.Query))
builder.WriteString(fmt.Sprintf("**Time Window:** %s to %s\n\n", searchArgs.TimeStart, searchArgs.TimeEnd))
fmt.Fprintf(&builder, "**Query:** %s\n\n", searchArgs.Query)
fmt.Fprintf(&builder, "**Time Window:** %s to %s\n\n", searchArgs.TimeStart, searchArgs.TimeEnd)
builder.WriteString("## Facts & Relationships\n\n")
builder.WriteString("1. **Vulnerability Discovery** (score: 0.93)\n")
builder.WriteString(" - Fact: Target System HAS_VULNERABILITY CVE-2021-41773\n")
@@ -583,7 +647,7 @@ func MockResponse(funcName string, args json.RawMessage) (string, error) {
case "diverse_results":
builder.WriteString("# Diverse Search Results\n\n")
builder.WriteString(fmt.Sprintf("**Query:** %s\n\n", searchArgs.Query))
fmt.Fprintf(&builder, "**Query:** %s\n\n", searchArgs.Query)
builder.WriteString("## Communities (Context Clusters)\n\n")
builder.WriteString("1. **Reconnaissance Phase** (MMR score: 0.94)\n")
builder.WriteString(" - Summary: All activities related to initial reconnaissance and scanning\n\n")
@@ -597,7 +661,7 @@ func MockResponse(funcName string, args json.RawMessage) (string, error) {
case "entity_by_label":
builder.WriteString("# Entity Inventory Search\n\n")
builder.WriteString(fmt.Sprintf("**Query:** %s\n\n", searchArgs.Query))
fmt.Fprintf(&builder, "**Query:** %s\n\n", searchArgs.Query)
builder.WriteString("## Matching Entities\n\n")
builder.WriteString("1. **SQL Injection Vulnerability** (score: 0.96)\n")
builder.WriteString(" - UUID: mock-uuid-sqli\n")
@@ -611,8 +675,8 @@ func MockResponse(funcName string, args json.RawMessage) (string, error) {
builder.WriteString("- **Exploit Success** (score: 0.94): SQL Injection was successfully exploited to dump database\n")
default:
builder.WriteString(fmt.Sprintf("# Mock Graphiti Search Results\n\nSearch type '%s' mock not fully implemented.\n", searchArgs.SearchType))
builder.WriteString(fmt.Sprintf("Query: %s\n\nThis would return relevant results from the temporal knowledge graph.", searchArgs.Query))
fmt.Fprintf(&builder, "# Mock Graphiti Search Results\n\nSearch type '%s' mock not fully implemented.\n", searchArgs.SearchType)
fmt.Fprintf(&builder, "Query: %s\n\nThis would return relevant results from the temporal knowledge graph.", searchArgs.Query)
}
resultObj = builder.String()
+38 -3
View File
@@ -45,6 +45,23 @@ var describeFuncInfo = FunctionInfo{
},
}
// internalFuncInfo describes the ftester-only "internal" engine (the internal
// browser-analytics engine — the opt-in alternative to Tavily). It is NOT a registered
// agent tool (agents call web_search), so — like "describe" — it is special-cased here
// instead of coming from the tool registry. It takes the same SearchAction arguments as
// the other search engines.
var internalFuncInfo = FunctionInfo{
Name: "internal",
Description: "Internal browser-analytics engine (ftester debug): discovers links, scrapes each page, " +
"and summarizes the result — the opt-in alternative to Tavily. Requires WEB_SEARCH_INTERNAL_ENABLED=true, " +
"a configured scraper, and at least one available link engine.",
Arguments: []ArgumentInfo{
{Name: "query", Type: "string", Description: "Search query (English)", Required: true},
{Name: "max_results", Type: "integer", Description: "Maximum number of results (1-10; default 5)", Required: true},
{Name: "message", Type: "string", Description: "Engagement-log message", Required: true},
},
}
// GetAvailableFunctions returns all available functions with their descriptions
func GetAvailableFunctions() []FunctionInfo {
funcInfos := []FunctionInfo{}
@@ -63,7 +80,7 @@ func GetAvailableFunctions() []FunctionInfo {
}
// Add custom ftester functions
funcInfos = append(funcInfos, describeFuncInfo)
funcInfos = append(funcInfos, describeFuncInfo, internalFuncInfo)
return funcInfos
}
@@ -74,6 +91,9 @@ func GetFunctionInfo(funcName string) (FunctionInfo, error) {
if funcName == "describe" {
return describeFuncInfo, nil
}
if funcName == "internal" {
return internalFuncInfo, nil
}
definitions := tools.GetRegistryDefinitions()
@@ -238,8 +258,21 @@ func ParseFunctionArgs(funcName string, args []string) (any, error) {
// Check if there's a value for the argument
if i+1 < len(args) && !strings.HasPrefix(args[i+1], "-") {
// Next arg is the value
parsedArgs[argName] = args[i+1]
value := args[i+1]
i++ // Skip the value in the next iteration
if argInfo.Type == "array" {
// Array arguments (e.g. []string) can't be passed as a single CLI value,
// so each occurrence of the flag appends one element to the resulting slice.
// This lets the user fill in at least one element via the command line.
if existing, ok := parsedArgs[argName].([]string); ok {
parsedArgs[argName] = append(existing, value)
} else {
parsedArgs[argName] = []string{value}
}
} else {
parsedArgs[argName] = value
}
} else {
// Boolean flag (no value)
parsedArgs[argName] = true
@@ -293,10 +326,13 @@ func getStructTypeForFunction(funcName string) (reflect.Type, error) {
tools.GoogleToolName: &tools.SearchAction{},
tools.DuckDuckGoToolName: &tools.SearchAction{},
tools.TavilyToolName: &tools.SearchAction{},
tools.FirecrawlToolName: &tools.SearchAction{},
tools.TraversaalToolName: &tools.SearchAction{},
tools.PerplexityToolName: &tools.SearchAction{},
tools.SearxngToolName: &tools.SearchAction{},
tools.SploitusToolName: &tools.SploitusAction{},
tools.WebSearchToolName: &tools.WebSearchAction{},
"internal": &tools.SearchAction{}, // internal analytics engine (ftester-only, debug)
tools.MemoristToolName: &tools.MemoristAction{},
tools.SearchInMemoryToolName: &tools.SearchInMemoryAction{},
tools.SearchGuideToolName: &tools.SearchGuideAction{},
@@ -331,7 +367,6 @@ func getStructTypeForFunction(funcName string) (reflect.Type, error) {
return reflect.TypeOf(structType).Elem(), nil
}
// IsToolAvailableForCall checks if a tool is available for call from the command line
func isToolAvailableForCall(toolName string) bool {
toolsMapping := tools.GetToolsByType()
availableTools := map[string]struct{}{}
+57
View File
@@ -0,0 +1,57 @@
package worker
import (
"testing"
"pentagi/pkg/tools"
)
// TestParseFunctionArgs_SearchInMemory_QuestionsArray verifies the CLI-args mode
// still works for the "questions" field after it moved from []string to the more
// lenient tools.Strings type: repeated "-questions" flags must still build a real
// JSON array that unmarshals cleanly (the primary/common path of Strings.UnmarshalJSON).
func TestParseFunctionArgs_SearchInMemory_QuestionsArray(t *testing.T) {
result, err := ParseFunctionArgs(tools.SearchInMemoryToolName, []string{
"-questions", "first query",
"-questions", "second query",
"-message", "test run",
})
if err != nil {
t.Fatalf("ParseFunctionArgs() unexpected error: %v", err)
}
action, ok := result.(*tools.SearchInMemoryAction)
if !ok {
t.Fatalf("ParseFunctionArgs() returned %T, want *tools.SearchInMemoryAction", result)
}
if len(action.Questions) != 2 {
t.Fatalf("Questions length = %d, want 2 (got: %v)", len(action.Questions), []string(action.Questions))
}
if action.Questions[0] != "first query" || action.Questions[1] != "second query" {
t.Errorf("Questions = %v, want [first query second query]", []string(action.Questions))
}
if action.Message != "test run" {
t.Errorf("Message = %q, want %q", action.Message, "test run")
}
}
// TestParseFunctionArgs_SearchInMemory_SingleQuestion verifies a single -questions
// flag (one array element) still round-trips correctly.
func TestParseFunctionArgs_SearchInMemory_SingleQuestion(t *testing.T) {
result, err := ParseFunctionArgs(tools.SearchInMemoryToolName, []string{
"-questions", "only query",
})
if err != nil {
t.Fatalf("ParseFunctionArgs() unexpected error: %v", err)
}
action, ok := result.(*tools.SearchInMemoryAction)
if !ok {
t.Fatalf("ParseFunctionArgs() returned %T, want *tools.SearchInMemoryAction", result)
}
if len(action.Questions) != 1 || action.Questions[0] != "only query" {
t.Fatalf("Questions = %v, want [only query]", []string(action.Questions))
}
}
+103 -48
View File
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
"time"
"pentagi/cmd/ftester/mocks"
"pentagi/pkg/config"
@@ -14,6 +15,7 @@ import (
"pentagi/pkg/providers/embeddings"
"pentagi/pkg/terminal"
"pentagi/pkg/tools"
"pentagi/pkg/tools/searchers"
"github.com/sirupsen/logrus"
"github.com/vxcontrol/cloud/anonymizer"
@@ -36,6 +38,49 @@ func (at *agentTool) IsAvailable() bool {
return at.handler != nil
}
// searcherTool adapts a single searchers.Searcher to the tools.Tool interface so the
// ftester can exercise one engine against its real API by name (e.g. `ftester -flow N
// tavily`). Production agents never take this path — they call web_search, which
// orchestrates the engines — but per-engine access is valuable for debugging a single
// provider's live integration and response parsing in isolation.
type searcherTool struct {
searcher searchers.Searcher
}
func (s *searcherTool) IsAvailable() bool { return s.searcher.IsAvailable() }
func (s *searcherTool) Handle(ctx context.Context, name string, args json.RawMessage) (string, error) {
req, err := searchRequestFromArgs(name, args)
if err != nil {
return "", err
}
return s.searcher.Handle(ctx, req)
}
// searchRequestFromArgs builds the engine-agnostic searchers.Request from a single
// engine's LLM-facing arguments. Sploitus carries extra exploit fields; every other
// engine uses SearchAction.
func searchRequestFromArgs(name string, args json.RawMessage) (searchers.Request, error) {
if name == tools.SploitusToolName {
var a tools.SploitusAction
if err := json.Unmarshal(args, &a); err != nil {
return searchers.Request{}, fmt.Errorf("failed to unmarshal %s args: %w", name, err)
}
return searchers.Request{
Query: a.Query,
MaxResults: a.MaxResults.Int(),
ExploitType: a.ExploitType.String(),
Sort: a.Sort.String(),
}, nil
}
var a tools.SearchAction
if err := json.Unmarshal(args, &a); err != nil {
return searchers.Request{}, fmt.Errorf("failed to unmarshal %s args: %w", name, err)
}
return searchers.Request{Query: a.Query, MaxResults: a.MaxResults.Int()}, nil
}
// toolExecutor holds the necessary data for creating and managing tools
type toolExecutor struct {
flowExecutor tools.FlowToolsExecutor
@@ -45,8 +90,10 @@ type toolExecutor struct {
dockerClient docker.DockerClient
handlers providers.FlowProviderHandlers
store *pgvector.Store
embedder embeddings.Embedder
graphitiClient *graphiti.Client
proxies mocks.ProxyProviders
userID int64
flowID int64
taskID *int64
subtaskID *int64
@@ -60,7 +107,7 @@ func newToolExecutor(
dockerClient docker.DockerClient,
handlers providers.FlowProviderHandlers,
proxies mocks.ProxyProviders,
flowID int64,
userID, flowID int64,
taskID, subtaskID *int64,
embedder embeddings.Embedder,
graphitiClient *graphiti.Client,
@@ -71,6 +118,7 @@ func newToolExecutor(
context.Background(),
pgvector.WithConnectionURL(cfg.DatabaseURL),
pgvector.WithEmbedder(embedder),
pgvector.WithCollectionName("langchain"),
)
if err != nil {
logrus.WithError(err).Error("failed to create pgvector store")
@@ -100,8 +148,10 @@ func newToolExecutor(
dockerClient: dockerClient,
handlers: handlers,
store: store,
embedder: embedder,
graphitiClient: graphitiClient,
proxies: proxies,
userID: userID,
flowID: flowID,
taskID: taskID,
subtaskID: subtaskID,
@@ -133,8 +183,10 @@ func (te *toolExecutor) GetTool(ctx context.Context, funcName string) (tools.Too
te.subtaskID,
containerID,
containerLID,
te.cfg.TenantPrefix(),
te.dockerClient,
te.proxies.GetTermLogProvider(),
time.Duration(te.cfg.TerminalToolTimeout)*time.Second,
), nil
case tools.FileToolName:
@@ -145,8 +197,10 @@ func (te *toolExecutor) GetTool(ctx context.Context, funcName string) (tools.Too
te.subtaskID,
containerID,
containerLID,
te.cfg.TenantPrefix(),
te.dockerClient,
te.proxies.GetTermLogProvider(),
time.Duration(te.cfg.TerminalToolTimeout)*time.Second,
), nil
case tools.BrowserToolName:
@@ -160,107 +214,107 @@ func (te *toolExecutor) GetTool(ctx context.Context, funcName string) (tools.Too
te.proxies.GetScreenshotProvider(),
), nil
case tools.GoogleToolName:
return tools.NewGoogleTool(
case tools.WebSearchToolName:
// The unified web_search orchestrator, as production agents use it. A nil page
// fetcher disables the optional internal analytics engine, which is out of
// scope for the function tester.
return tools.NewWebSearchTool(
te.cfg,
te.flowID,
te.taskID,
te.subtaskID,
te.proxies.GetSearchLogProvider(),
te.GetSummarizer(),
nil,
), nil
// Individual engines: not used by agents (they call web_search), but exposed here
// so a developer can test one provider's real API in isolation. Each searcher is
// wrapped in searcherTool to bridge the searchers.Searcher → tools.Tool interface.
case tools.GoogleToolName:
return &searcherTool{searcher: searchers.NewGoogle(te.cfg)}, nil
case tools.DuckDuckGoToolName:
return tools.NewDuckDuckGoTool(
te.cfg,
te.flowID,
te.taskID,
te.subtaskID,
te.proxies.GetSearchLogProvider(),
), nil
return &searcherTool{searcher: searchers.NewDuckDuckGo(te.cfg)}, nil
case tools.TavilyToolName:
return tools.NewTavilyTool(
te.cfg,
te.flowID,
te.taskID,
te.subtaskID,
te.proxies.GetSearchLogProvider(),
te.GetSummarizer(),
), nil
return &searcherTool{searcher: searchers.NewTavily(te.cfg, searchers.SummarizeHandler(te.GetSummarizer()))}, nil
case tools.FirecrawlToolName:
return &searcherTool{searcher: searchers.NewFirecrawl(te.cfg, searchers.SummarizeHandler(te.GetSummarizer()))}, nil
case tools.TraversaalToolName:
return tools.NewTraversaalTool(
te.cfg,
te.flowID,
te.taskID,
te.subtaskID,
te.proxies.GetSearchLogProvider(),
), nil
return &searcherTool{searcher: searchers.NewTraversaal(te.cfg)}, nil
case tools.PerplexityToolName:
return tools.NewPerplexityTool(
te.cfg,
te.flowID,
te.taskID,
te.subtaskID,
te.proxies.GetSearchLogProvider(),
te.GetSummarizer(),
), nil
return &searcherTool{searcher: searchers.NewPerplexity(te.cfg, searchers.SummarizeHandler(te.GetSummarizer()))}, nil
case tools.SearxngToolName:
return tools.NewSearxngTool(
te.cfg,
te.flowID,
te.taskID,
te.subtaskID,
te.proxies.GetSearchLogProvider(),
te.GetSummarizer(),
), nil
return &searcherTool{searcher: searchers.NewSearxng(te.cfg, searchers.SummarizeHandler(te.GetSummarizer()))}, nil
case tools.SploitusToolName:
return tools.NewSploitusTool(
te.cfg,
te.flowID,
te.taskID,
te.subtaskID,
te.proxies.GetSearchLogProvider(),
), nil
return &searcherTool{searcher: searchers.NewSploitus(te.cfg)}, nil
case "internal":
// The internal browser-analytics engine — the opt-in alternative to Tavily.
// Not an agent-facing tool (agents call web_search); exposed here so it can be
// exercised in isolation. Requires WEB_SEARCH_INTERNAL_ENABLED=true, a configured
// scraper (SCRAPER_PUBLIC_URL / SCRAPER_PRIVATE_URL), and at least one available
// link engine (e.g. google/duckduckgo) — otherwise IsAvailable() is false.
fetcher := tools.NewBrowserPageFetcher(te.flowID, te.taskID, te.subtaskID, te.cfg, te.proxies.GetScreenshotProvider())
return &searcherTool{searcher: tools.NewInternalEngine(te.cfg, te.GetSummarizer(), fetcher)}, nil
case tools.SearchInMemoryToolName:
return tools.NewMemoryTool(
te.flowID,
te.replacer,
te.store,
te.proxies.GetVectorStoreLogProvider(),
), nil
case tools.SearchGuideToolName:
return tools.NewGuideTool(
te.userID,
te.flowID,
te.taskID,
te.subtaskID,
te.replacer,
te.store,
te.embedder,
te.db,
te.cfg.EmbeddingMaxTextBytes,
te.proxies.GetVectorStoreLogProvider(),
te.proxies.GetKnowledgeProvider(),
), nil
case tools.SearchAnswerToolName:
return tools.NewSearchTool(
te.userID,
te.flowID,
te.taskID,
te.subtaskID,
te.replacer,
te.store,
te.embedder,
te.db,
te.cfg.EmbeddingMaxTextBytes,
te.proxies.GetVectorStoreLogProvider(),
te.proxies.GetKnowledgeProvider(),
), nil
case tools.SearchCodeToolName:
return tools.NewCodeTool(
te.userID,
te.flowID,
te.taskID,
te.subtaskID,
te.replacer,
te.store,
te.embedder,
te.db,
te.cfg.EmbeddingMaxTextBytes,
te.proxies.GetVectorStoreLogProvider(),
te.proxies.GetKnowledgeProvider(),
), nil
case tools.GraphitiSearchToolName:
@@ -268,6 +322,7 @@ func (te *toolExecutor) GetTool(ctx context.Context, funcName string) (tools.Too
te.flowID,
te.taskID,
te.subtaskID,
te.cfg.GroupID(te.flowID),
te.graphitiClient,
), nil
+88 -17
View File
@@ -106,6 +106,30 @@ func InteractiveFillArgs(ctx context.Context, funcName string, taskID, subtaskID
break
}
case "array":
var items []string
for {
itemTitle := fmt.Sprintf("%s item #%d (leave empty to finish)", title, len(items)+1)
strValue, err := terminal.InteractivePromptContext(ctx, itemTitle, os.Stdin)
if err != nil {
return nil, fmt.Errorf("input cancelled for '%s': %w", arg.Name, err)
}
if strValue == "" {
if len(items) == 0 && arg.Required {
terminal.PrintError("At least one value is required")
continue
}
break
}
items = append(items, strValue)
}
if len(items) > 0 {
value = items
}
default: // string and other types
strValue, err := terminal.InteractivePromptContext(ctx, title, os.Stdin)
if err != nil {
@@ -142,7 +166,9 @@ func InteractiveFillArgs(ctx context.Context, funcName string, taskID, subtaskID
return structValue, nil
}
// fillStructFromMap fills a structure with data from a map
// fillStructFromMap fills a structure with data from a map. Every conversion
// uses a safe (two-value) type assertion so a mismatch between the collected
// value and the field's Go type returns a clear error instead of panicking.
func fillStructFromMap(structPtr any, data map[string]any) error {
val := reflect.ValueOf(structPtr).Elem()
@@ -160,23 +186,68 @@ func fillStructFromMap(structPtr any, data map[string]any) error {
fieldName = fieldName[:comma]
}
if value, ok := data[fieldName]; ok {
fieldValue := val.Field(i)
if fieldValue.CanSet() {
switch fieldValue.Kind() {
case reflect.String:
fieldValue.SetString(value.(string))
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
fieldValue.SetInt(int64(value.(int)))
case reflect.Bool:
fieldValue.SetBool(value.(bool))
case reflect.Struct:
// For special types that may be in the tools package
// This is a simplified version that may require refinement
// depending on specific types
fmt.Printf("Complex structure field detected: %s\n", fieldName)
}
value, ok := data[fieldName]
if !ok {
continue
}
fieldValue := val.Field(i)
if !fieldValue.CanSet() {
continue
}
switch fieldValue.Kind() {
case reflect.String:
strValue, ok := value.(string)
if !ok {
return fmt.Errorf("unexpected type for argument '%s': expected string, got %T", fieldName, value)
}
fieldValue.SetString(strValue)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
intValue, ok := value.(int)
if !ok {
return fmt.Errorf("unexpected type for argument '%s': expected int, got %T", fieldName, value)
}
fieldValue.SetInt(int64(intValue))
case reflect.Bool:
boolValue, ok := value.(bool)
if !ok {
return fmt.Errorf("unexpected type for argument '%s': expected bool, got %T", fieldName, value)
}
fieldValue.SetBool(boolValue)
case reflect.Slice:
if fieldValue.Type().Elem().Kind() != reflect.String {
return fmt.Errorf("unsupported slice element type for argument '%s': %s", fieldName, fieldValue.Type().Elem().Kind())
}
// Build the slice explicitly against the field's own type (e.g.
// tools.Strings, not a plain []string) rather than relying on Go's
// slice-assignability rules, so this keeps working correctly even
// if the field is a named type with custom (un)marshaling.
var items []string
switch v := value.(type) {
case []string:
items = v
case string:
items = []string{v}
default:
return fmt.Errorf("unexpected type for argument '%s': expected []string or string, got %T", fieldName, value)
}
converted := reflect.MakeSlice(fieldValue.Type(), len(items), len(items))
for idx, item := range items {
converted.Index(idx).SetString(item)
}
fieldValue.Set(converted)
case reflect.Struct:
// For special types that may be in the tools package
// This is a simplified version that may require refinement
// depending on specific types
fmt.Printf("Complex structure field detected: %s\n", fieldName)
}
}
@@ -0,0 +1,73 @@
package worker
import (
"strings"
"testing"
"pentagi/pkg/tools"
)
func TestFillStructFromMap_StringsField_FromSlice(t *testing.T) {
action := &tools.SearchInMemoryAction{}
err := fillStructFromMap(action, map[string]any{
"questions": []string{"query one", "query two"},
"message": "test",
})
if err != nil {
t.Fatalf("fillStructFromMap() unexpected error: %v", err)
}
if len(action.Questions) != 2 || action.Questions[0] != "query one" || action.Questions[1] != "query two" {
t.Fatalf("Questions = %v, want [query one query two]", []string(action.Questions))
}
if action.Message != "test" {
t.Fatalf("Message = %q, want %q", action.Message, "test")
}
}
func TestFillStructFromMap_StringsField_FromSingleString(t *testing.T) {
action := &tools.SearchInMemoryAction{}
err := fillStructFromMap(action, map[string]any{
"questions": "single question",
})
if err != nil {
t.Fatalf("fillStructFromMap() unexpected error: %v", err)
}
if len(action.Questions) != 1 || action.Questions[0] != "single question" {
t.Fatalf("Questions = %v, want [single question]", []string(action.Questions))
}
}
func TestFillStructFromMap_TypeMismatch_ReturnsClearError_NotPanic(t *testing.T) {
t.Run("string field given int", func(t *testing.T) {
action := &tools.SearchInMemoryAction{}
// The whole point of this test: a mismatched type must return an
// error, not panic with "interface conversion: interface {} is X, not Y".
err := fillStructFromMap(action, map[string]any{"message": 42})
assertContainsError(t, err, "expected string")
})
t.Run("int field given string", func(t *testing.T) {
// MaxResults is a non-pointer tools.Int64 field (Kind() == Int64).
action := &tools.SploitusAction{}
err := fillStructFromMap(action, map[string]any{"max_results": "not-a-number"})
assertContainsError(t, err, "expected int")
})
t.Run("slice field given bool", func(t *testing.T) {
action := &tools.SearchInMemoryAction{}
err := fillStructFromMap(action, map[string]any{"questions": true})
assertContainsError(t, err, "expected []string or string")
})
}
func assertContainsError(t *testing.T, err error, want string) {
t.Helper()
if err == nil {
t.Fatal("expected an error for mismatched argument type, got nil")
}
if !strings.Contains(err.Error(), want) {
t.Errorf("error = %q, want it to contain %q", err.Error(), want)
}
}
+23 -16
View File
@@ -66,7 +66,7 @@ func NewTester(
functions := &tools.Functions{}
// Initialize tools flowExecutor
flowExecutor, err := tools.NewFlowToolsExecutor(db, cfg, dockerClient, functions, flowID)
flowExecutor, err := tools.NewFlowToolsExecutor(db, cfg, dockerClient, functions, userID, flowID)
if err != nil {
return nil, fmt.Errorf("failed to create flow tools executor: %w", err)
}
@@ -81,12 +81,14 @@ func NewTester(
flowExecutor.SetSearchLogProvider(proxies.GetSearchLogProvider())
flowExecutor.SetTermLogProvider(proxies.GetTermLogProvider())
flowExecutor.SetVectorStoreLogProvider(proxies.GetVectorStoreLogProvider())
flowExecutor.SetToolCallLogProvider(proxies.GetToolCallLogProvider())
flowExecutor.SetKnowledgeProvider(proxies.GetKnowledgeProvider())
flowExecutor.SetGraphitiClient(providerController.GraphitiClient())
// Initialize tool executor
toolExecutor, err := newToolExecutor(
flowExecutor, cfg, db, dockerClient, nil, proxies,
flowID, taskID, subtaskID, providerController.Embedder(),
userID, flowID, taskID, subtaskID, providerController.Embedder(),
providerController.GraphitiClient(),
)
if err != nil {
@@ -144,23 +146,28 @@ func (t *tester) initFlowProviderController() error {
// Setup Langfuse observability to track the execution lifecycle
// This is critical for debugging and monitoring flow performance
// We use trace context to connect this execution with earlier/later runs
traceMetadata := langfuse.Metadata{
"flow_id": flow.ID,
"user_id": flow.UserID,
"user_email": user.Mail,
"user_name": user.Name,
"user_hash": user.Hash,
"user_role": user.RoleName,
"provider_name": flow.ModelProviderName,
"provider_type": flow.ModelProviderType,
}
if t.cfg.HasTenant() {
traceMetadata["tenant_id"] = t.cfg.TenantID
}
ctx, observation := obs.Observer.NewObservation(t.ctx,
langfuse.WithObservationTraceID(flow.TraceID.String),
langfuse.WithObservationTraceContext(
langfuse.WithTraceName(fmt.Sprintf("%d flow worker", flow.ID)),
langfuse.WithTraceUserID(user.Mail),
langfuse.WithTraceTags([]string{"controller"}),
langfuse.WithTraceSessionID(fmt.Sprintf("flow-%d", flow.ID)),
langfuse.WithTraceMetadata(langfuse.Metadata{
"flow_id": flow.ID,
"user_id": flow.UserID,
"user_email": user.Mail,
"user_name": user.Name,
"user_hash": user.Hash,
"user_role": user.RoleName,
"provider_name": flow.ModelProviderName,
"provider_type": flow.ModelProviderType,
}),
langfuse.WithTraceName(fmt.Sprintf("%s%d flow worker", t.cfg.TenantLabel(), flow.ID)),
langfuse.WithTraceUserID(t.cfg.TenantUserID(user.Mail)),
langfuse.WithTraceTags(t.cfg.TenantTags("controller")),
langfuse.WithTraceSessionID(t.cfg.ScopedName(fmt.Sprintf("flow-%d", flow.ID))),
langfuse.WithTraceMetadata(traceMetadata),
),
)
+77 -140
View File
@@ -11,7 +11,7 @@ import (
"pentagi/cmd/installer/state"
"pentagi/pkg/version"
"github.com/docker/docker/client"
"github.com/moby/moby/client"
)
var (
@@ -20,37 +20,50 @@ var (
)
const (
DockerComposeFile = "docker-compose.yml"
GraphitiComposeFile = "docker-compose-graphiti.yml"
LangfuseComposeFile = "docker-compose-langfuse.yml"
ObservabilityComposeFile = "docker-compose-observability.yml"
ExampleCustomConfigLLMFile = "example.custom.provider.yml"
ExampleOllamaConfigLLMFile = "example.ollama.provider.yml"
PentagiScriptFile = "/usr/local/bin/pentagi"
PentagiContainerName = "pentagi"
GraphitiContainerName = "graphiti"
Neo4jContainerName = "neo4j"
LangfuseWorkerContainerName = "langfuse-worker"
LangfuseWebContainerName = "langfuse-web"
GrafanaContainerName = "grafana"
OpenTelemetryContainerName = "otel"
DefaultImage = "debian:latest"
DefaultImageForPentest = "vxcontrol/kali-linux"
DefaultGraphitiEndpoint = "http://graphiti:8000"
DefaultLangfuseEndpoint = "http://langfuse-web:3000"
DefaultObservabilityEndpoint = "otelcol:8148"
DefaultLangfuseOtelEndpoint = "http://otelcol:4318"
DefaultUpdateServerEndpoint = "https://update.pentagi.com"
UpdatesCheckEndpoint = "/api/v1/updates/check"
MinFreeMemGB = 0.5
MinFreeMemGBForPentagi = 0.5
MinFreeMemGBForGraphiti = 2.0
MinFreeMemGBForLangfuse = 1.5
MinFreeMemGBForObservability = 1.5
MinFreeDiskGB = 5.0
MinFreeDiskGBForComponents = 10.0
MinFreeDiskGBPerComponents = 2.0
MinFreeDiskGBForWorkerImages = 25.0
DockerComposeFile = "docker-compose.yml"
GraphitiComposeFile = "docker-compose-graphiti.yml"
LangfuseComposeFile = "docker-compose-langfuse.yml"
ObservabilityComposeFile = "docker-compose-observability.yml"
ExampleCustomConfigLLMFile = "example.custom.provider.yml"
ExampleOllamaConfigLLMFile = "example.ollama.provider.yml"
PentagiScriptFile = "/usr/local/bin/pentagi"
PentagiContainerName = "pentagi"
ScraperContainerName = "scraper"
PgvectorContainerName = "pgvector"
PgexporterContainerName = "pgexporter"
GraphitiContainerName = "graphiti"
Neo4jContainerName = "neo4j"
LangfuseWorkerContainerName = "langfuse-worker"
LangfuseWebContainerName = "langfuse-web"
LangfusePostgresContainerName = "langfuse-postgres"
LangfuseClickhouseContainerName = "langfuse-clickhouse"
LangfuseRedisContainerName = "langfuse-redis"
LangfuseMinioContainerName = "langfuse-minio"
GrafanaContainerName = "grafana"
OpenTelemetryContainerName = "otel"
VictoriaMetricsContainerName = "victoriametrics"
LokiContainerName = "loki"
JaegerContainerName = "jaeger"
NodeExporterContainerName = "node-exporter"
CadvisorContainerName = "cadvisor"
ClickstoreContainerName = "clickstore"
DefaultImage = "debian:latest"
DefaultImageForPentest = "vxcontrol/kali-linux"
DefaultGraphitiEndpoint = "http://graphiti:8000"
DefaultLangfuseEndpoint = "http://langfuse-web:3000"
DefaultObservabilityEndpoint = "otelcol:8148"
DefaultLangfuseOtelEndpoint = "http://otelcol:4318"
DefaultUpdateServerEndpoint = "https://update.pentagi.com"
DefaultSupportServerEndpoint = "https://support.pentagi.com"
MinFreeMemGB = 0.5
MinFreeMemGBForPentagi = 0.5
MinFreeMemGBForGraphiti = 2.0
MinFreeMemGBForLangfuse = 1.5
MinFreeMemGBForObservability = 1.5
MinFreeDiskGB = 5.0
MinFreeDiskGBForComponents = 10.0
MinFreeDiskGBPerComponents = 2.0
MinFreeDiskGBForWorkerImages = 25.0
)
var (
@@ -113,6 +126,19 @@ type CheckResult struct {
DockerErrorType DockerErrorType `json:"docker_error_type" yaml:"docker_error_type"`
EnvDirWritable bool `json:"env_dir_writable" yaml:"env_dir_writable"`
// StackUpdates is the update server's answer in full: per stack, what version is
// offered, what the release says, and which artefacts would actually change. The
// per-stack booleans above are the same verdict reduced to what the menus need.
StackUpdates []StackUpdate `json:"stack_updates,omitempty" yaml:"stack_updates,omitempty"`
// UpdateFailure explains why there is no answer, and is nil when there is one. It
// replaces guessing from UpdateServerAccessible: "unreachable", "quota spent" and
// "not allowed for this license" need different things from the user.
UpdateFailure *UpdateCheckFailure `json:"update_failure,omitempty" yaml:"update_failure,omitempty"`
// InstalledComponents is what the last check observed on this machine. Verifying an
// update afterwards needs it, and keeping it here means the verification reads facts
// the check already gathered instead of interrogating Docker a second time.
InstalledComponents []InstalledComponent `json:"installed_components,omitempty" yaml:"installed_components,omitempty"`
// handler controls how information is gathered. If nil, skip gathering
handler CheckHandler
}
@@ -397,9 +423,12 @@ func (h *defaultCheckHandler) GatherPentagiInfo(ctx context.Context, c *CheckRes
envDir := filepath.Dir(h.appState.GetEnvPath())
dockerComposeFile := filepath.Join(envDir, DockerComposeFile)
// The bedrock example is deliberately not asked for: a stack extracted without it
// would count as not extracted, and extraction overwrites the examples the user
// edited when the update is forced. Verification of an extracted stack writes it.
c.PentagiExtracted = checkFileExists(dockerComposeFile) &&
checkFileExists(ExampleCustomConfigLLMFile) &&
checkFileExists(ExampleOllamaConfigLLMFile)
checkFileExists(filepath.Join(envDir, ExampleCustomConfigLLMFile)) &&
checkFileExists(filepath.Join(envDir, ExampleOllamaConfigLLMFile))
c.PentagiScriptInstalled = checkFileExists(PentagiScriptFile)
if h.dockerClient != nil {
@@ -423,7 +452,14 @@ func (h *defaultCheckHandler) GatherGraphitiInfo(ctx context.Context, c *CheckRe
graphitiURL := getEnvVar(h.appState, "GRAPHITI_URL", "")
c.GraphitiConnected = graphitiEnabled == "true" && graphitiURL != ""
c.GraphitiExternal = graphitiURL != DefaultGraphitiEndpoint
// Gated on Connected, and not for tidiness. "External" means somebody else
// operates this stack, which is only a statement about a stack that exists:
// an unset URL is not the default URL, so the bare comparison reports a stack
// nobody has configured as externally hosted. Every consumer of this field
// already begins with `Connected &&`, so the guard changes no decision — what
// it changes is what the field SAYS, in the TUI and on the wire, where a
// released installer has been claiming a Graphiti that does not exist.
c.GraphitiExternal = c.GraphitiConnected && graphitiURL != DefaultGraphitiEndpoint
envDir := filepath.Dir(h.appState.GetEnvPath())
graphitiComposeFile := filepath.Join(envDir, GraphitiComposeFile)
@@ -454,7 +490,9 @@ func (h *defaultCheckHandler) GatherLangfuseInfo(ctx context.Context, c *CheckRe
secretKey := getEnvVar(h.appState, "LANGFUSE_SECRET_KEY", "")
c.LangfuseConnected = baseURL != "" && projectID != "" && publicKey != "" && secretKey != ""
c.LangfuseExternal = baseURL != DefaultLangfuseEndpoint
// See the note on GraphitiExternal: without the guard an unconfigured stack
// reports itself as externally hosted.
c.LangfuseExternal = c.LangfuseConnected && baseURL != DefaultLangfuseEndpoint
envDir := filepath.Dir(h.appState.GetEnvPath())
langfuseFile := filepath.Join(envDir, LangfuseComposeFile)
@@ -481,7 +519,9 @@ func (h *defaultCheckHandler) GatherObservabilityInfo(ctx context.Context, c *Ch
otelHost := getEnvVar(h.appState, "OTEL_HOST", "")
c.ObservabilityConnected = otelHost != ""
c.ObservabilityExternal = otelHost != DefaultObservabilityEndpoint
// See the note on GraphitiExternal: without the guard an unconfigured stack
// reports itself as externally hosted.
c.ObservabilityExternal = c.ObservabilityConnected && otelHost != DefaultObservabilityEndpoint
envDir := filepath.Dir(h.appState.GetEnvPath())
obsFile := filepath.Join(envDir, ObservabilityComposeFile)
@@ -550,109 +590,6 @@ func (h *defaultCheckHandler) GatherSystemInfo(ctx context.Context, c *CheckResu
return nil
}
func (h *defaultCheckHandler) GatherUpdatesInfo(ctx context.Context, c *CheckResult) error {
h.mx.Lock()
defer h.mx.Unlock()
proxyURL := getProxyURL(h.appState)
updateServerURL := getEnvVar(h.appState, "UPDATE_SERVER_URL", DefaultUpdateServerEndpoint)
request := CheckUpdatesRequest{
InstallerOsType: runtime.GOOS,
InstallerVersion: InstallerVersion,
GraphitiConnected: c.GraphitiConnected,
GraphitiExternal: c.GraphitiExternal,
GraphitiInstalled: c.GraphitiInstalled,
LangfuseConnected: c.LangfuseConnected,
LangfuseExternal: c.LangfuseExternal,
LangfuseInstalled: c.LangfuseInstalled,
ObservabilityConnected: c.ObservabilityConnected,
ObservabilityExternal: c.ObservabilityExternal,
ObservabilityInstalled: c.ObservabilityInstalled,
}
// get PentAGI container image info
if h.dockerClient != nil && c.PentagiInstalled {
if imageInfo := getContainerImageInfo(ctx, h.dockerClient, PentagiContainerName); imageInfo != nil {
request.PentagiImageName = &imageInfo.Name
request.PentagiImageTag = &imageInfo.Tag
request.PentagiImageHash = &imageInfo.Hash
}
}
// get Worker image info from environment
if h.workerClient != nil {
defaultImage := getEnvVar(h.appState, "DOCKER_DEFAULT_IMAGE_FOR_PENTEST", DefaultImageForPentest)
if imageInfo := getImageInfo(ctx, h.workerClient, defaultImage); imageInfo != nil {
request.WorkerImageName = &imageInfo.Name
request.WorkerImageTag = &imageInfo.Tag
request.WorkerImageHash = &imageInfo.Hash
}
}
// get Graphiti image info if installed locally
if h.dockerClient != nil && c.GraphitiConnected && !c.GraphitiExternal && c.GraphitiInstalled {
if graphitiInfo := getContainerImageInfo(ctx, h.dockerClient, GraphitiContainerName); graphitiInfo != nil {
request.GraphitiImageName = &graphitiInfo.Name
request.GraphitiImageTag = &graphitiInfo.Tag
request.GraphitiImageHash = &graphitiInfo.Hash
}
if neo4jInfo := getContainerImageInfo(ctx, h.dockerClient, Neo4jContainerName); neo4jInfo != nil {
request.Neo4jImageName = &neo4jInfo.Name
request.Neo4jImageTag = &neo4jInfo.Tag
request.Neo4jImageHash = &neo4jInfo.Hash
}
}
// get Langfuse image info if installed locally
if h.dockerClient != nil && c.LangfuseConnected && !c.LangfuseExternal && c.LangfuseInstalled {
if workerInfo := getContainerImageInfo(ctx, h.dockerClient, LangfuseWorkerContainerName); workerInfo != nil {
request.LangfuseWorkerImageName = &workerInfo.Name
request.LangfuseWorkerImageTag = &workerInfo.Tag
request.LangfuseWorkerImageHash = &workerInfo.Hash
}
if webInfo := getContainerImageInfo(ctx, h.dockerClient, LangfuseWebContainerName); webInfo != nil {
request.LangfuseWebImageName = &webInfo.Name
request.LangfuseWebImageTag = &webInfo.Tag
request.LangfuseWebImageHash = &webInfo.Hash
}
}
// get Grafana and OpenTelemetry image info if observability installed locally
if h.dockerClient != nil && c.ObservabilityConnected && !c.ObservabilityExternal && c.ObservabilityInstalled {
if grafanaInfo := getContainerImageInfo(ctx, h.dockerClient, GrafanaContainerName); grafanaInfo != nil {
request.GrafanaImageName = &grafanaInfo.Name
request.GrafanaImageTag = &grafanaInfo.Tag
request.GrafanaImageHash = &grafanaInfo.Hash
}
if otelInfo := getContainerImageInfo(ctx, h.dockerClient, OpenTelemetryContainerName); otelInfo != nil {
request.OpenTelemetryImageName = &otelInfo.Name
request.OpenTelemetryImageTag = &otelInfo.Tag
request.OpenTelemetryImageHash = &otelInfo.Hash
}
}
response := checkUpdatesServer(ctx, updateServerURL, proxyURL, request)
if response != nil {
c.UpdateServerAccessible = true
c.InstallerIsUpToDate = response.InstallerIsUpToDate
c.PentagiIsUpToDate = response.PentagiIsUpToDate
c.GraphitiIsUpToDate = response.GraphitiIsUpToDate
c.LangfuseIsUpToDate = response.LangfuseIsUpToDate
c.ObservabilityIsUpToDate = response.ObservabilityIsUpToDate
c.WorkerIsUpToDate = response.WorkerIsUpToDate
} else {
c.UpdateServerAccessible = false
c.InstallerIsUpToDate = false
c.PentagiIsUpToDate = false
c.GraphitiIsUpToDate = false
c.LangfuseIsUpToDate = false
c.ObservabilityIsUpToDate = false
}
return nil
}
func Gather(ctx context.Context, appState state.State) (CheckResult, error) {
if appState == nil {
return CheckResult{}, ErrAppStateNotInitialized
@@ -0,0 +1,111 @@
package checker
import (
"os"
"path/filepath"
"sync"
"testing"
"pentagi/cmd/installer/loader"
)
// Drives GatherGraphitiInfo, GatherLangfuseInfo and GatherObservabilityInfo on one configuration.
func TestChecker_NeverClaimsExternalForAStackThatIsNotConnected(t *testing.T) {
envPath := filepath.Join(t.TempDir(), ".env")
tests := []struct {
name string
vars map[string]loader.EnvVar
connected, external bool
}{
{"nothing configured", map[string]loader.EnvVar{}, false, false},
{"configured against somebody else's endpoint", map[string]loader.EnvVar{
"GRAPHITI_ENABLED": {Value: "true"},
"GRAPHITI_URL": {Value: "https://graphiti.example.com"},
"LANGFUSE_BASE_URL": {Value: "https://langfuse.example.com"},
"LANGFUSE_PROJECT_ID": {Value: "p"},
"LANGFUSE_PUBLIC_KEY": {Value: "pk"},
"LANGFUSE_SECRET_KEY": {Value: "sk"},
"OTEL_HOST": {Value: "otel.example.com:4317"},
}, true, true},
{"configured against the bundled endpoint", map[string]loader.EnvVar{
"GRAPHITI_ENABLED": {Value: "true"},
"GRAPHITI_URL": {Value: DefaultGraphitiEndpoint},
"LANGFUSE_BASE_URL": {Value: DefaultLangfuseEndpoint},
"LANGFUSE_PROJECT_ID": {Value: "p"},
"LANGFUSE_PUBLIC_KEY": {Value: "pk"},
"LANGFUSE_SECRET_KEY": {Value: "sk"},
"OTEL_HOST": {Value: DefaultObservabilityEndpoint},
}, true, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
handler := &defaultCheckHandler{mx: &sync.Mutex{}, appState: &mockState{vars: tt.vars, envPath: envPath}}
got := &CheckResult{}
for _, err := range []error{
handler.GatherGraphitiInfo(t.Context(), got),
handler.GatherLangfuseInfo(t.Context(), got),
handler.GatherObservabilityInfo(t.Context(), got),
} {
if err != nil {
t.Fatalf("gather: %v", err)
}
}
for stack, flags := range map[string][2]bool{
"graphiti": {got.GraphitiConnected, got.GraphitiExternal},
"langfuse": {got.LangfuseConnected, got.LangfuseExternal},
"observability": {got.ObservabilityConnected, got.ObservabilityExternal},
} {
if flags != [2]bool{tt.connected, tt.external} {
t.Errorf("%s: connected=%t external=%t, want %t and %t", stack, flags[0], flags[1], tt.connected, tt.external)
}
}
})
}
}
func TestChecker_GatherPentagiInfo_LooksForTheExtractedStackBesideTheEnvFile(t *testing.T) {
tests := []struct {
name string
beside, elsewhere []string // files beside the env file, and in the working directory
want bool
}{
{
"the compose file and both examples beside the env file",
[]string{"docker-compose.yml", "example.custom.provider.yml", "example.ollama.provider.yml"}, nil, true,
},
{"the compose file alone", []string{"docker-compose.yml"}, nil, false},
{"the ollama example missing", []string{"docker-compose.yml", "example.custom.provider.yml"}, nil, false},
{"the custom example missing", []string{"docker-compose.yml", "example.ollama.provider.yml"}, nil, false},
{"the compose file missing", []string{"example.custom.provider.yml", "example.ollama.provider.yml"}, nil, false},
{
"the examples in the working directory only",
[]string{"docker-compose.yml"}, []string{"example.custom.provider.yml", "example.ollama.provider.yml"}, false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
envDir, workDir := t.TempDir(), t.TempDir()
for dir, names := range map[string][]string{envDir: tt.beside, workDir: tt.elsewhere} {
for _, name := range names {
if err := os.WriteFile(filepath.Join(dir, name), []byte("x"), 0o644); err != nil {
t.Fatalf("write %s: %v", name, err)
}
}
}
t.Chdir(workDir)
handler := &defaultCheckHandler{mx: &sync.Mutex{}, appState: &mockState{envPath: filepath.Join(envDir, ".env")}}
got := &CheckResult{}
if err := handler.GatherPentagiInfo(t.Context(), got); err != nil {
t.Fatalf("gather: %v", err)
}
if got.PentagiExtracted != tt.want {
t.Errorf("PentagiExtracted = %t, want %t", got.PentagiExtracted, tt.want)
}
})
}
}
+458
View File
@@ -0,0 +1,458 @@
package checker
import (
"context"
"crypto/sha256"
"encoding/hex"
"io"
"os"
"path/filepath"
"runtime"
"strings"
"pentagi/cmd/installer/cloud"
"pentagi/cmd/installer/wizard/logger"
"github.com/moby/moby/client"
"github.com/vxcontrol/cloud/models"
)
// This file turns a running installation into the component list the update server is
// asked about. The list has to be COMPLETE: the server answers only about what it was
// told, so a component left out comes back as "nothing to report" — which reads exactly
// like "up to date" and is the more dangerous of the two mistakes.
// maxReportedComponents is the server-side ceiling on one request, and it IS the
// contract's constant rather than a number that agrees with it today. A local literal
// can only be wrong in two ways, and both are silent: too high and the service refuses
// the whole request — losing the answer for every component, not just the ones past the
// bound — too low and the tail is trimmed here while the service would have taken it.
//
// The inventory is well under it, but the list grows with every stack, so the limit is
// enforced before sending and what gets dropped is written to the log: a silently
// truncated list would report the remaining components as complete.
const maxReportedComponents = models.MaxReportedComponents
// JaegerPluginDir holds the Jaeger storage plugin, relative to the directory the
// environment file lives in.
//
// Exported because the processor writes into this directory when it downloads a newer
// plugin: the path, the file names and the digests reported for them have to be one
// table, or an update writes a file nothing reads.
const JaegerPluginDir = "observability/jaeger/bin"
// JaegerPluginBinaries maps the architecture a plugin file is built for to its name.
//
// Both files are on disk regardless of the host: the choice happens inside the Jaeger
// container, by the architecture of the Docker VM rather than of this machine. So both are
// reported, as two components.
var JaegerPluginBinaries = map[models.ArchType]string{
models.ArchTypeAMD64: "jaeger-clickhouse-linux-amd64",
models.ArchTypeARM64: "jaeger-clickhouse-linux-arm64",
}
// imageComponent names the container an image component is observed through.
//
// The table is explicit because nothing here can be derived. Four of the sixteen observed
// components run in a container whose name is not the component's: postgres, clickhouse,
// redis and minio all carry the `langfuse-` prefix of the stack that owns them. Guessing
// the container from the component would silently drop those four — a name matching no
// container is indistinguishable from a container that is not deployed — so the mapping
// lives in exactly one place, and TestComponents_ImageComponent_MatchesTheComposeContainersBothWays
// keeps it honest against the compose files.
type imageComponent struct {
Component models.ComponentType
Container string
}
// The four groups below are also the order components are reported in, which is the order
// the ceiling above cuts from: the stacks whose updates matter most come first.
var (
pentagiImageComponents = []imageComponent{
{models.ComponentTypePentagi, PentagiContainerName},
{models.ComponentTypeScraper, ScraperContainerName},
{models.ComponentTypePgvector, PgvectorContainerName},
// Last in its group on purpose: the ceiling cuts from the tail, and an
// exporter is the one component of this stack an installation can live
// without hearing about.
{models.ComponentTypePgexporter, PgexporterContainerName},
}
graphitiImageComponents = []imageComponent{
{models.ComponentTypeGraphiti, GraphitiContainerName},
{models.ComponentTypeNeo4j, Neo4jContainerName},
}
langfuseImageComponents = []imageComponent{
{models.ComponentTypeLangfuseWorker, LangfuseWorkerContainerName},
{models.ComponentTypeLangfuseWeb, LangfuseWebContainerName},
{models.ComponentTypePostgres, LangfusePostgresContainerName},
{models.ComponentTypeClickhouse, LangfuseClickhouseContainerName},
{models.ComponentTypeRedis, LangfuseRedisContainerName},
{models.ComponentTypeMinio, LangfuseMinioContainerName},
}
observabilityImageComponents = []imageComponent{
{models.ComponentTypeGrafana, GrafanaContainerName},
{models.ComponentTypeOtel, OpenTelemetryContainerName},
{models.ComponentTypeVictoriametrics, VictoriaMetricsContainerName},
{models.ComponentTypeLoki, LokiContainerName},
{models.ComponentTypeJaeger, JaegerContainerName},
// clickstore is the ClickHouse server Jaeger stores traces in, and it is a
// different component from `clickhouse`, which is Langfuse's. The two run
// the same image and belong to different stacks.
{models.ComponentTypeClickstore, ClickstoreContainerName},
{models.ComponentTypeCadvisor, CadvisorContainerName},
{models.ComponentTypeNodeExporter, NodeExporterContainerName},
}
)
// stackGate decides how a stack's components are reported.
//
// A stack pointing at an external address has no local images to describe, so its
// components are reported as connected and carry no image data. A stack that is not
// configured at all is not reported: "unused" would spend one of the thirty slots saying
// nothing.
type stackGate struct {
connected bool
external bool
}
func (g stackGate) skip() bool { return !g.connected }
func (g stackGate) isExternal() bool { return g.external }
// gatherComponents builds the component list for an update check.
//
// Anything that cannot be described completely is left out rather than guessed at: a
// component with an unknown architecture, or an image the daemon will not describe, would
// fail the contract's validation and take the whole request down with it — costing the
// answer for every other component too.
// reportedComponents is what one update check says about this machine. Images and
// files are separate all the way through: an image is identified by a registry
// reference and a digest, a file by a version and a hash, and no artefact is both.
type reportedComponents struct {
images []models.ImageComponentInfo
files []models.FileComponentInfo
}
func (r reportedComponents) total() int { return len(r.images) + len(r.files) }
func (h *defaultCheckHandler) gatherComponents(ctx context.Context, c *CheckResult) reportedComponents {
var reported reportedComponents
// The pentagi stack is always reported: it is the product itself, with no external
// alternative to point at.
reported.images = append(reported.images,
h.imageComponents(ctx, pentagiImageComponents, stackGate{connected: true})...)
if worker := h.workerComponent(ctx, c); worker != nil {
reported.images = append(reported.images, *worker)
}
if installer := h.installerComponent(); installer != nil {
reported.files = append(reported.files, *installer)
}
reported.images = append(reported.images, h.imageComponents(ctx, graphitiImageComponents,
stackGate{connected: c.GraphitiConnected, external: c.GraphitiExternal})...)
reported.images = append(reported.images, h.imageComponents(ctx, langfuseImageComponents,
stackGate{connected: c.LangfuseConnected, external: c.LangfuseExternal})...)
observability := stackGate{connected: c.ObservabilityConnected, external: c.ObservabilityExternal}
reported.images = append(reported.images, h.imageComponents(ctx, observabilityImageComponents, observability)...)
reported.files = append(reported.files, h.jaegerPluginComponents(observability)...)
return h.enforceComponentLimit(reported)
}
// enforceComponentLimit trims the report to what the server accepts, naming what it
// dropped.
//
// The limit is on the SUM of both lists — that is how the server counts it, and
// bounding each separately would build a request the server rejects whole.
func (h *defaultCheckHandler) enforceComponentLimit(reported reportedComponents) reportedComponents {
if reported.total() <= maxReportedComponents {
return reported
}
var dropped []string
// Files are trimmed first only if images alone already fill the budget; otherwise
// the tail of the files is what goes, so the images — which are the product — keep
// their slots.
if len(reported.images) > maxReportedComponents {
for _, component := range reported.images[maxReportedComponents:] {
dropped = append(dropped, component.Component.String())
}
for _, component := range reported.files {
dropped = append(dropped, component.Component.String())
}
reported.images = reported.images[:maxReportedComponents]
reported.files = nil
} else {
room := maxReportedComponents - len(reported.images)
for _, component := range reported.files[room:] {
dropped = append(dropped, component.Component.String())
}
reported.files = reported.files[:room]
}
logger.Warnf("update check covers %d of %d components, no answer for: %s",
maxReportedComponents, maxReportedComponents+len(dropped), strings.Join(dropped, ", "))
return reported
}
// imageComponents describes one stack's images.
func (h *defaultCheckHandler) imageComponents(
ctx context.Context, sources []imageComponent, gate stackGate,
) []models.ImageComponentInfo {
if gate.skip() {
return nil
}
components := make([]models.ImageComponentInfo, 0, len(sources))
for _, source := range sources {
if gate.isExternal() {
// An external stack runs somewhere we cannot inspect. There is no reference
// to report and therefore nothing the server can resolve, so the component
// is left out rather than sent as an image without an image.
continue
}
if component := h.describeContainerImage(ctx, source); component != nil {
components = append(components, *component)
}
}
return components
}
// describeContainerImage inspects one container and the image behind it.
//
// The image, not the host, decides os and arch: a container image is linux even on a
// darwin host, and on Apple silicon it may well be an amd64 image running under emulation.
// Taking either from runtime would describe the wrong artefact.
func (h *defaultCheckHandler) describeContainerImage(
ctx context.Context, source imageComponent,
) *models.ImageComponentInfo {
if h.dockerClient == nil {
return nil
}
container, err := h.dockerClient.ContainerInspect(ctx, source.Container, client.ContainerInspectOptions{})
if err != nil {
// No container means the component is not deployed here, which is not worth a
// slot in the request.
return nil
}
status := models.ComponentStatusInstalled
if container.Container.State != nil && container.Container.State.Running {
status = models.ComponentStatusRunning
}
reference := ""
if container.Container.Config != nil {
reference = container.Container.Config.Image
}
image, err := h.dockerClient.ImageInspect(ctx, container.Container.Image)
if err != nil {
logger.Warnf("component %s: image %s cannot be inspected: %v",
source.Component, container.Container.Image, err)
return nil
}
osType := models.OSType(strings.ToLower(image.Os))
archType := models.ArchType(strings.ToLower(image.Architecture))
if osType.Valid() != nil || archType.Valid() != nil {
// A platform the contract has no name for would fail validation and take the
// whole request with it, so this one component is dropped instead.
logger.Warnf("component %s: unsupported image platform %s/%s, not reported",
source.Component, image.Os, image.Architecture)
return nil
}
repository, tag, ok := imageReference(reference)
if !ok {
logger.Warnf("component %s: container image reference %q cannot be parsed, not reported",
source.Component, reference)
return nil
}
component := models.ImageComponentInfo{
Component: source.Component,
Status: status,
OS: osType,
Arch: archType,
Repository: repository,
Tag: tag,
}
if digest := normalizeDigest(image.ID); digest != "" {
component.ImageHash = &digest
}
return &component
}
// imageReference splits a container's image reference into the pair the server
// matches on — repository as compose spells it, with the registry prefix and the
// implicit "library/" removed — and reports whether it can be named at all.
//
// A reference that cannot be named has no channel to resolve, so the component is
// dropped rather than sent incomplete: an update is the newest image UNDER a
// reference, and the contract requires both halves for exactly that reason.
//
// There is no tag default here because parseImageRef already applies the one
// `docker pull` applies, and never returns an empty tag or an empty name for a
// non-empty reference — it falls back to the whole original. So the only
// reference this rejects is the absent one, which is a container whose config
// carries no image at all.
func imageReference(reference string) (repository, tag string, ok bool) {
info := parseImageRef(reference, "")
if info == nil || info.Name == "" {
return "", "", false
}
return info.Name, info.Tag, true
}
// workerComponent describes the pentest worker image.
//
// It has no container and no compose service: the image is pulled into the worker
// environment on demand. What is reported is what is actually there — substituting the
// built-in default would claim an image the machine may not have.
func (h *defaultCheckHandler) workerComponent(ctx context.Context, c *CheckResult) *models.ImageComponentInfo {
if h.workerClient == nil || !c.WorkerImageExists {
return nil
}
configured := getEnvVar(h.appState, "DOCKER_DEFAULT_IMAGE_FOR_PENTEST", DefaultImageForPentest)
info := getImageInfo(ctx, h.workerClient, configured)
if info == nil || info.Name == "" {
return nil
}
component := models.ImageComponentInfo{
Component: models.ComponentTypeWorker,
// No container exists for it, so the image being present is the whole story.
Status: models.ComponentStatusInstalled,
OS: models.OSTypeLinux,
Arch: models.ArchType(runtime.GOARCH),
}
// The image itself is authoritative about its platform when the daemon will describe
// it; the host architecture is only a fallback for a daemon that will not.
if image, err := h.workerClient.ImageInspect(ctx, info.Name+":"+info.Tag); err == nil {
osType := models.OSType(strings.ToLower(image.Os))
archType := models.ArchType(strings.ToLower(image.Architecture))
if osType.Valid() == nil && archType.Valid() == nil {
component.OS, component.Arch = osType, archType
}
if digest := normalizeDigest(image.ID); digest != "" {
component.ImageHash = &digest
}
} else if digest := normalizeDigest(info.Hash); digest != "" {
component.ImageHash = &digest
}
if component.Arch.Valid() != nil {
return nil
}
// getImageInfo answers through parseImageRef, so the tag is already the one
// `docker pull` would apply.
component.Repository = info.Name
component.Tag = info.Tag
return &component
}
// installerComponent describes the running installer binary — the one component that is a
// file on this host rather than an image, and so the only one whose os and arch are the
// host's own.
func (h *defaultCheckHandler) installerComponent() *models.FileComponentInfo {
osType := models.OSType(runtime.GOOS)
archType := models.ArchType(runtime.GOARCH)
if osType.Valid() != nil || archType.Valid() != nil {
logger.Warnf("installer runs on unsupported platform %s/%s, not reported",
runtime.GOOS, runtime.GOARCH)
return nil
}
version := cloud.NormalizeVersion(InstallerVersion)
component := models.FileComponentInfo{
Component: models.ComponentTypeInstaller,
Status: models.ComponentStatusInstalled,
OS: osType,
Arch: archType,
Version: &version,
}
// A hash of ourselves is a nice-to-have: the server identifies installer builds by
// version. Failing to read our own path is no reason to drop the component.
if path, err := os.Executable(); err == nil {
if digest, err := fileDigest(path); err == nil {
component.FileHash = &digest
}
}
return &component
}
// jaegerPluginComponents describes the Jaeger storage plugin, which ships as one file per
// architecture. Both are reported: which one runs is decided inside the Jaeger container.
func (h *defaultCheckHandler) jaegerPluginComponents(gate stackGate) []models.FileComponentInfo {
if gate.skip() || gate.isExternal() || h.appState == nil {
return nil
}
base := filepath.Join(filepath.Dir(h.appState.GetEnvPath()), JaegerPluginDir)
components := make([]models.FileComponentInfo, 0, len(JaegerPluginBinaries))
// Fixed order, so two runs on the same machine produce the same request.
for _, arch := range []models.ArchType{models.ArchTypeAMD64, models.ArchTypeARM64} {
digest, err := fileDigest(filepath.Join(base, JaegerPluginBinaries[arch]))
if err != nil {
continue
}
components = append(components, models.FileComponentInfo{
Component: models.ComponentTypeJaegerClickhouse,
Status: models.ComponentStatusInstalled,
// The plugin runs inside the Jaeger container, so it is a linux binary
// whatever this host is.
OS: models.OSTypeLinux,
Arch: arch,
FileHash: &digest,
})
}
return components
}
// normalizeDigest converts a digest as the Docker daemon reports it into the form the
// contract accepts: bare lowercase hex, no "sha256:" prefix. An unrecognisable value
// becomes empty, so it is omitted rather than sent and rejected.
func normalizeDigest(raw string) string {
digest := strings.ToLower(strings.TrimPrefix(strings.TrimSpace(raw), "sha256:"))
if len(digest) != 64 {
return ""
}
for _, r := range digest {
if (r < '0' || r > '9') && (r < 'a' || r > 'f') {
return ""
}
}
return digest
}
// fileDigest returns the sha256 of a file in the same bare-hex form.
func fileDigest(path string) (string, error) {
file, err := os.Open(path)
if err != nil {
return "", err
}
defer file.Close()
digest := sha256.New()
if _, err := io.Copy(digest, file); err != nil {
return "", err
}
return hex.EncodeToString(digest.Sum(nil)), nil
}
@@ -0,0 +1,353 @@
package checker
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"net/http"
"os"
"path/filepath"
"reflect"
"strings"
"sync"
"testing"
"pentagi/cmd/installer/cloud"
"pentagi/cmd/installer/loader"
"github.com/vxcontrol/cloud/models"
)
// composeContainerNames reads every container_name declared across the compose files.
func composeContainerNames(t *testing.T) map[string]string {
t.Helper()
names := map[string]string{}
for _, path := range composeFiles {
content, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read %s: %v", path, err)
}
for _, line := range strings.Split(string(content), "\n") {
if name, found := strings.CutPrefix(strings.TrimSpace(line), "container_name:"); found {
names[strings.TrimSpace(name)] = filepath.Base(path)
}
}
}
if len(names) == 0 {
t.Fatal("no container names found — the compose files moved or changed shape")
}
return names
}
// inventoryContainers is the component-to-container mapping as the gathering holds it.
func inventoryContainers(t *testing.T) map[models.ComponentType]string {
t.Helper()
got := map[models.ComponentType]string{}
for _, group := range [][]imageComponent{
pentagiImageComponents, graphitiImageComponents,
langfuseImageComponents, observabilityImageComponents,
} {
for _, source := range group {
if previous, seen := got[source.Component]; seen {
t.Errorf("component %s is listed twice (%s and %s)", source.Component, previous, source.Container)
}
got[source.Component] = source.Container
}
}
return got
}
func TestComponents_ImageComponent_MatchesTheComposeContainersBothWays(t *testing.T) {
declared := composeContainerNames(t)
observed := map[string]models.ComponentType{}
for component, container := range inventoryContainers(t) {
observed[container] = component
if _, exists := declared[container]; !exists {
t.Errorf("component %s is observed through container %q, which no compose file declares", component, container)
}
}
for container, file := range declared {
if _, reported := observed[container]; !reported {
t.Errorf("container %q in %s is not reported as a component, so it is never checked for updates", container, file)
}
}
}
func TestComponents_ImageComponent_CoversEveryImageComponentOfADeployedStack(t *testing.T) {
deployed := map[models.ProductStack]bool{
models.ProductStackPentagi: true,
models.ProductStackGraphiti: true,
models.ProductStackLangfuse: true,
models.ProductStackObservability: true,
}
reported := inventoryContainers(t)
for _, component := range models.AllComponentTypes {
if !component.IsImageComponent() || !deployed[component.GetProductStack()] {
continue
}
if _, ok := reported[component]; !ok {
t.Errorf("component %s of the %s stack is an image, but no source names its container",
component, component.GetProductStack())
}
}
}
// Which list an artefact goes in is decided by the builder that constructs it; the contract decides it by kind.
func TestComponents_BuildsEachComponentIntoTheListForItsKind(t *testing.T) {
for component, container := range inventoryContainers(t) {
if !component.IsImageComponent() {
t.Errorf("%s is built as an image component (container %q) but is delivered as a %s",
component, container, component.ArtifactKind())
}
}
if !models.ComponentTypeWorker.IsImageComponent() {
t.Errorf("the worker is built as an image component but is delivered as a %s", models.ComponentTypeWorker.ArtifactKind())
}
for _, component := range []models.ComponentType{models.ComponentTypeInstaller, models.ComponentTypeJaegerClickhouse} {
if !component.IsFileComponent() {
t.Errorf("%s is built as a file component but is delivered as an %s", component, component.ArtifactKind())
}
}
}
func TestComponents_JaegerPluginDir_MatchesWhatTheContainerLoads(t *testing.T) {
content, err := os.ReadFile("../files/fs/docker-compose-observability.yml")
if err != nil {
t.Fatalf("read compose: %v", err)
}
compose := string(content)
if !strings.Contains(compose, "./observability/jaeger:/etc/jaeger") {
t.Fatal("the jaeger service no longer mounts ./observability/jaeger at /etc/jaeger")
}
if !strings.Contains(compose, "/etc/jaeger/bin/jaeger-clickhouse-linux-$$ARCH") {
t.Fatal("the jaeger service no longer loads its plugin from /etc/jaeger/bin")
}
if JaegerPluginDir != "observability/jaeger/bin" {
t.Errorf("plugin directory = %q, want observability/jaeger/bin", JaegerPluginDir)
}
for _, name := range JaegerPluginBinaries {
if _, err := os.Stat(filepath.Join("../files/fs", JaegerPluginDir, name)); err != nil {
t.Errorf("plugin %s is not where the installer ships it: %v", name, err)
}
}
}
func TestComponents_MaxReportedComponents_FitsTheWholeInventory(t *testing.T) {
total := len(pentagiImageComponents) + len(graphitiImageComponents) +
len(langfuseImageComponents) + len(observabilityImageComponents) +
1 + // worker
1 + // installer
len(JaegerPluginBinaries)
if total > maxReportedComponents {
t.Fatalf("the inventory is %d components, above the %d a request carries", total, maxReportedComponents)
}
}
func TestComponents_ImageComponents_DescribesOnlyTheImagesOfALocalStack(t *testing.T) {
hash := strings.Repeat("a", 64)
container := func(running bool, image, reference string) http.HandlerFunc {
return checkerJSON(http.StatusOK, fmt.Sprintf(`{"State":{"Running":%t},"Image":%q,"Config":{"Image":%q}}`,
running, image, reference))
}
docker := checkerFakeDocker(t, map[string]http.HandlerFunc{
"GET /containers/langfuse-worker/json": container(true, "sha256:"+hash, "langfuse/langfuse-worker:3"),
"GET /containers/langfuse-web/json": container(false, "sha256:"+hash, "docker.io/langfuse/langfuse:3"),
"GET /containers/langfuse-postgres/json": container(true, "sha256:gone", "postgres:16"),
"GET /containers/langfuse-clickhouse/json": container(true, "sha256:s390x", "clickhouse/clickhouse-server:24"),
"GET /containers/langfuse-redis/json": container(true, "sha256:"+hash, ""),
"GET /images/sha256:" + hash + "/json": checkerJSON(http.StatusOK, `{"Id":"sha256:`+hash+`","Os":"linux","Architecture":"amd64"}`),
"GET /images/sha256:s390x/json": checkerJSON(http.StatusOK, `{"Id":"sha256:s390x","Os":"linux","Architecture":"s390x"}`),
})
// Minio is not deployed; postgres's image, clickhouse's platform and redis's reference cannot be described.
described := []models.ImageComponentInfo{
{Component: models.ComponentTypeLangfuseWorker, Status: models.ComponentStatusRunning, OS: models.OSTypeLinux,
Arch: models.ArchTypeAMD64, Repository: "langfuse/langfuse-worker", Tag: "3", ImageHash: &hash},
{Component: models.ComponentTypeLangfuseWeb, Status: models.ComponentStatusInstalled, OS: models.OSTypeLinux,
Arch: models.ArchTypeAMD64, Repository: "langfuse/langfuse", Tag: "3", ImageHash: &hash},
}
tests := []struct {
name string
gate stackGate
want []models.ImageComponentInfo
}{
{"a local stack reports every image it can describe", stackGate{connected: true}, described},
{"a stack running elsewhere reports nothing", stackGate{connected: true, external: true}, nil},
{"an unused stack reports nothing", stackGate{}, nil},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
handler := &defaultCheckHandler{mx: &sync.Mutex{}, dockerClient: docker}
got := handler.imageComponents(t.Context(), langfuseImageComponents, tt.gate)
if len(got) != len(tt.want) || (len(got) > 0 && !reflect.DeepEqual(got, tt.want)) {
t.Errorf("got %+v, want %+v", got, tt.want)
}
})
}
}
func TestComponents_ImageReference_NamesEveryReferenceButAnAbsentOne(t *testing.T) {
tests := []struct {
reference, wantRepository, wantTag string
wantOK bool
}{
{"vxcontrol/pentagi", "vxcontrol/pentagi", "latest", true},
{":latest", ":latest", "latest", true},
{"", "", "", false},
}
for _, tt := range tests {
repository, tag, ok := imageReference(tt.reference)
if ok != tt.wantOK || repository != tt.wantRepository || tag != tt.wantTag {
t.Errorf("imageReference(%q) = %q, %q, %t; want %q, %q, %t",
tt.reference, repository, tag, ok, tt.wantRepository, tt.wantTag, tt.wantOK)
continue
}
component := models.ImageComponentInfo{
Component: models.ComponentTypePentagi, Status: models.ComponentStatusRunning,
OS: models.OSTypeLinux, Arch: models.ArchTypeAMD64, Repository: repository, Tag: tag,
}
if err := component.Valid(); ok && err != nil {
t.Errorf("a component built from %q would be rejected: %v", tt.reference, err)
}
}
}
func TestComponents_NormalizeDigest_KeepsOnlyABareLowercaseSHA256(t *testing.T) {
valid := strings.Repeat("ab", 32)
tests := []struct {
name, raw, want string
}{
{"the daemon prefix is stripped", "sha256:" + valid, valid},
{"already bare", valid, valid},
{"uppercase is lowered", strings.ToUpper(valid), valid},
{"surrounding whitespace", " sha256:" + valid + " ", valid},
{"truncated digests are refused", valid[:12], ""},
{"non-hex is refused", strings.Repeat("z", 64), ""},
{"empty", "", ""},
}
for _, tt := range tests {
if got := normalizeDigest(tt.raw); got != tt.want {
t.Errorf("%s: normalizeDigest(%q) = %q, want %q", tt.name, tt.raw, got, tt.want)
}
}
}
func TestComponents_JaegerPluginComponents_ReportsBothArchitecturesOfALocalPlugin(t *testing.T) {
envDir := t.TempDir()
pluginDir := filepath.Join(envDir, "observability", "jaeger", "bin")
if err := os.MkdirAll(pluginDir, 0o755); err != nil {
t.Fatalf("mkdir: %v", err)
}
sums := map[string]string{}
for _, name := range []string{"jaeger-clickhouse-linux-amd64", "jaeger-clickhouse-linux-arm64"} {
content := []byte("plugin " + name)
if err := os.WriteFile(filepath.Join(pluginDir, name), content, 0o644); err != nil {
t.Fatalf("write %s: %v", name, err)
}
sum := sha256.Sum256(content)
sums[name] = hex.EncodeToString(sum[:])
}
handler := &defaultCheckHandler{
mx: &sync.Mutex{},
appState: &mockState{vars: map[string]loader.EnvVar{}, envPath: filepath.Join(envDir, ".env")},
}
type archHash struct {
arch models.ArchType
hash string
}
tests := []struct {
name string
gate stackGate
want []archHash
}{
{"a local observability stack", stackGate{connected: true}, []archHash{
{"amd64", sums["jaeger-clickhouse-linux-amd64"]},
{"arm64", sums["jaeger-clickhouse-linux-arm64"]},
}},
{"an unused observability stack", stackGate{}, nil},
{"observability running elsewhere", stackGate{connected: true, external: true}, nil},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var got []archHash
for _, component := range handler.jaegerPluginComponents(tt.gate) {
if component.Component != models.ComponentTypeJaegerClickhouse || component.OS != models.OSTypeLinux ||
component.FileHash == nil || component.Valid() != nil {
t.Fatalf("%s: %+v is not a linux jaeger plugin the contract accepts", component.Arch, component)
}
got = append(got, archHash{component.Arch, *component.FileHash})
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("plugin components = %v, want %v", got, tt.want)
}
})
}
}
func TestComponents_InstallerComponent_ReportsAContractVersion(t *testing.T) {
handler := &defaultCheckHandler{mx: &sync.Mutex{}}
component := handler.installerComponent()
if component == nil {
t.Skip("this platform has no contract name, which the gathering handles by skipping")
}
if err := component.Valid(); err != nil {
t.Fatalf("the installer component would be rejected: %v", err)
}
if component.Version == nil {
t.Fatal("the installer reports no version")
}
if component.FileHash != nil && len(*component.FileHash) != 64 {
t.Errorf("file hash is %d characters, want 64", len(*component.FileHash))
}
}
func TestComponents_EnforceComponentLimit_KeepsTheImagesAndTrimsTheFiles(t *testing.T) {
handler := &defaultCheckHandler{mx: &sync.Mutex{}}
oversized := reportedComponents{}
for range models.MaxReportedComponents {
oversized.images = append(oversized.images, models.ImageComponentInfo{Component: models.ComponentTypePentagi})
}
for range 3 {
oversized.files = append(oversized.files, models.FileComponentInfo{Component: models.ComponentTypeInstaller})
}
trimmed := handler.enforceComponentLimit(oversized)
if len(trimmed.images) != models.MaxReportedComponents || len(trimmed.files) != 0 {
t.Errorf("kept %d images and %d files, want the contract's %d images and no files",
len(trimmed.images), len(trimmed.files), models.MaxReportedComponents)
}
}
func TestComponents_GatherComponents_BuildsARequestTheContractAccepts(t *testing.T) {
handler := &defaultCheckHandler{
mx: &sync.Mutex{},
appState: &mockState{vars: map[string]loader.EnvVar{}, envPath: t.TempDir() + "/.env"},
}
result := &CheckResult{GraphitiConnected: true, LangfuseConnected: true, ObservabilityConnected: true}
components := handler.gatherComponents(t.Context(), result)
request := models.CheckUpdatesRequest{
InstallerVersion: cloud.NormalizeVersion(InstallerVersion),
InstallerOS: models.OSTypeLinux,
InstallerArch: models.ArchTypeAMD64,
Strategy: models.UpdateStrategyStable,
Images: components.images,
Files: components.files,
}
if err := request.Valid(); err != nil {
t.Fatalf("the gathered request would be rejected: %v", err)
}
}
@@ -0,0 +1,86 @@
package checker
import (
"fmt"
"net/http"
"net/http/httptest"
"regexp"
"testing"
"pentagi/cmd/installer/loader"
"github.com/moby/moby/client"
)
// composeFiles are the deployment descriptors the installer ships and extracts.
var composeFiles = []string{
"../files/fs/docker-compose.yml",
"../files/fs/docker-compose-graphiti.yml",
"../files/fs/docker-compose-langfuse.yml",
"../files/fs/docker-compose-observability.yml",
}
type mockState struct {
vars map[string]loader.EnvVar
envPath string
}
func (m *mockState) GetVar(key string) (loader.EnvVar, bool) {
if val, exists := m.vars[key]; exists {
return val, true
}
return loader.EnvVar{}, false
}
func (m *mockState) GetVars(names []string) (map[string]loader.EnvVar, map[string]bool) {
return m.vars, make(map[string]bool, len(names))
}
func (m *mockState) GetEnvPath() string { return m.envPath }
func (m *mockState) Exists() bool { return true }
func (m *mockState) Reset() error { return nil }
func (m *mockState) Commit() error { return nil }
func (m *mockState) IsDirty() bool { return false }
func (m *mockState) GetEulaConsent() bool { return true }
func (m *mockState) SetEulaConsent() error { return nil }
func (m *mockState) SetStack(stack []string) error { return nil }
func (m *mockState) GetStack() []string { return []string{} }
func (m *mockState) SetVar(name, value string) error { return nil }
func (m *mockState) ResetVar(name string) error { return nil }
func (m *mockState) SetVars(vars map[string]string) error { return nil }
func (m *mockState) ResetVars(names []string) error { return nil }
func (m *mockState) GetAllVars() map[string]loader.EnvVar { return m.vars }
func (m *mockState) WriteVars(vars map[string]string) error { return nil }
var checkerAPIVersion = regexp.MustCompile(`^/v[0-9.]+`)
// checkerFakeDocker is a daemon answering only its "METHOD /path" routes; anything else is a missing object.
func checkerFakeDocker(t *testing.T, routes map[string]http.HandlerFunc) *client.Client {
t.Helper()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if handler, ok := routes[r.Method+" "+checkerAPIVersion.ReplaceAllString(r.URL.Path, "")]; ok {
handler(w, r)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusNotFound)
fmt.Fprintf(w, `{"message":"no such object: %s"}`, r.URL.Path)
}))
t.Cleanup(server.Close)
cli, err := client.New(client.WithHost("tcp://"+server.Listener.Addr().String()), client.WithAPIVersion("1.47"))
if err != nil {
t.Fatalf("docker client: %v", err)
}
t.Cleanup(func() { cli.Close() })
return cli
}
// checkerJSON answers a route with a fixed status and JSON body.
func checkerJSON(status int, body string) http.HandlerFunc {
return func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
w.Write([]byte(body))
}
}
+77 -190
View File
@@ -2,9 +2,7 @@ package checker
import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"io"
"net"
@@ -22,10 +20,7 @@ import (
"pentagi/cmd/installer/state"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/image"
"github.com/docker/docker/api/types/volume"
"github.com/docker/docker/client"
"github.com/moby/moby/client"
)
type DockerVersion struct {
@@ -39,53 +34,6 @@ type ImageInfo struct {
Hash string
}
type CheckUpdatesRequest struct {
InstallerOsType string `json:"installer_os_type"`
InstallerVersion string `json:"installer_version"`
PentagiImageName *string `json:"pentagi_image_name,omitempty"`
PentagiImageTag *string `json:"pentagi_image_tag,omitempty"`
PentagiImageHash *string `json:"pentagi_image_hash,omitempty"`
WorkerImageName *string `json:"worker_image_name,omitempty"`
WorkerImageTag *string `json:"worker_image_tag,omitempty"`
WorkerImageHash *string `json:"worker_image_hash,omitempty"`
GraphitiConnected bool `json:"graphiti_connected"`
GraphitiInstalled bool `json:"graphiti_installed"`
GraphitiExternal bool `json:"graphiti_external"`
GraphitiImageName *string `json:"graphiti_image_name,omitempty"`
GraphitiImageTag *string `json:"graphiti_image_tag,omitempty"`
GraphitiImageHash *string `json:"graphiti_image_hash,omitempty"`
Neo4jImageName *string `json:"neo4j_image_name,omitempty"`
Neo4jImageTag *string `json:"neo4j_image_tag,omitempty"`
Neo4jImageHash *string `json:"neo4j_image_hash,omitempty"`
LangfuseConnected bool `json:"langfuse_connected"`
LangfuseInstalled bool `json:"langfuse_installed"`
LangfuseExternal bool `json:"langfuse_external"`
ObservabilityConnected bool `json:"observability_connected"`
ObservabilityExternal bool `json:"observability_external"`
ObservabilityInstalled bool `json:"observability_installed"`
LangfuseWorkerImageName *string `json:"langfuse_worker_image_name,omitempty"`
LangfuseWorkerImageTag *string `json:"langfuse_worker_image_tag,omitempty"`
LangfuseWorkerImageHash *string `json:"langfuse_worker_image_hash,omitempty"`
LangfuseWebImageName *string `json:"langfuse_web_image_name,omitempty"`
LangfuseWebImageTag *string `json:"langfuse_web_image_tag,omitempty"`
LangfuseWebImageHash *string `json:"langfuse_web_image_hash,omitempty"`
GrafanaImageName *string `json:"grafana_image_name,omitempty"`
GrafanaImageTag *string `json:"grafana_image_tag,omitempty"`
GrafanaImageHash *string `json:"grafana_image_hash,omitempty"`
OpenTelemetryImageName *string `json:"otel_image_name,omitempty"`
OpenTelemetryImageTag *string `json:"otel_image_tag,omitempty"`
OpenTelemetryImageHash *string `json:"otel_image_hash,omitempty"`
}
type CheckUpdatesResponse struct {
InstallerIsUpToDate bool `json:"installer_is_up_to_date"`
PentagiIsUpToDate bool `json:"pentagi_is_up_to_date"`
GraphitiIsUpToDate bool `json:"graphiti_is_up_to_date"`
LangfuseIsUpToDate bool `json:"langfuse_is_up_to_date"`
ObservabilityIsUpToDate bool `json:"observability_is_up_to_date"`
WorkerIsUpToDate bool `json:"worker_is_up_to_date"`
}
func checkFileExists(path string) bool {
_, err := os.Stat(path)
return !os.IsNotExist(err)
@@ -138,9 +86,7 @@ func getProxyURL(appState state.State) string {
}
func createDockerClient(host, certPath string, tlsVerify bool) (*client.Client, error) {
opts := []client.Opt{
client.WithAPIVersionNegotiation(),
}
var opts []client.Opt
if host != "" {
opts = append(opts, client.WithHost(host))
@@ -154,7 +100,7 @@ func createDockerClient(host, certPath string, tlsVerify bool) (*client.Client,
))
}
return client.NewClientWithOpts(opts...)
return client.New(opts...)
}
// createDockerClientFromEnv creates a docker client and returns the error type
@@ -165,13 +111,13 @@ func createDockerClientFromEnv(ctx context.Context) (*client.Client, DockerError
return nil, DockerErrorNotInstalled
}
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
cli, err := client.New(client.FromEnv)
if err != nil {
return nil, DockerErrorAPIError
}
// try to ping the daemon
_, err = cli.Ping(ctx)
_, err = cli.Ping(ctx, client.PingOptions{NegotiateAPIVersion: true})
if err != nil {
cli.Close() // close client on error
// check if it's a connection error (daemon not running)
@@ -206,7 +152,7 @@ const (
)
func checkDockerVersion(ctx context.Context, cli *client.Client) DockerVersion {
version, err := cli.ServerVersion(ctx)
version, err := cli.ServerVersion(ctx, client.ServerVersionOptions{})
if err != nil {
return DockerVersion{Version: "", Valid: false}
}
@@ -236,14 +182,15 @@ func checkDockerCliVersion() DockerVersion {
}
func checkDockerComposeVersion() DockerVersion {
cmd := exec.Command("docker", "compose", "version")
output, err := cmd.Output()
if err != nil {
cmd = exec.Command("docker-compose", "--version")
output, err = cmd.Output()
if err != nil {
return DockerVersion{Version: "", Valid: false}
}
return checkDockerComposeVersionWithRunner(func(name string, args ...string) ([]byte, error) {
return exec.Command(name, args...).Output()
})
}
func checkDockerComposeVersionWithRunner(run func(name string, args ...string) ([]byte, error)) DockerVersion {
output, err := run("docker", "compose", "version")
if err != nil && len(output) == 0 {
return DockerVersion{Version: "", Valid: false}
}
versionStr := extractVersionFromOutput(string(output))
@@ -289,12 +236,12 @@ func checkVersionCompatibility(version, minVersion string) bool {
}
func checkContainerExists(ctx context.Context, cli *client.Client, name string) (exists, running bool) {
containers, err := cli.ContainerList(ctx, container.ListOptions{All: true})
containers, err := cli.ContainerList(ctx, client.ContainerListOptions{All: true})
if err != nil {
return false, false
}
for _, cont := range containers {
for _, cont := range containers.Items {
for _, containerName := range cont.Names {
if strings.TrimPrefix(containerName, "/") == name {
return true, cont.State == "running"
@@ -312,14 +259,14 @@ func checkVolumesExist(ctx context.Context, cli *client.Client, volumeNames []st
return false
}
volumes, err := cli.VolumeList(ctx, volume.ListOptions{})
volumes, err := cli.VolumeList(ctx, client.VolumeListOptions{})
if err != nil {
return false
}
// collect all volume names from Docker
existingVolumes := make([]string, 0, len(volumes.Volumes))
for _, vol := range volumes.Volumes {
existingVolumes := make([]string, 0, len(volumes.Items))
for _, vol := range volumes.Items {
existingVolumes = append(existingVolumes, vol.Name)
}
@@ -429,6 +376,9 @@ func getLinuxAvailableMemoryGB() float64 {
}
}
}
if err := scanner.Err(); err != nil {
return 0.0
}
availableMemGB := float64(memAvailable) / (1024 * 1024 * 1024)
if availableMemGB > 0 {
@@ -519,6 +469,9 @@ func checkLinuxMemory(requiredGB float64) bool {
}
}
}
if err := scanner.Err(); err != nil {
return true // assume OK if can't check
}
availableMemGB := float64(memAvailable) / (1024 * 1024 * 1024)
if availableMemGB > 0 {
@@ -781,23 +734,6 @@ func getNetworkFailures(ctx context.Context, proxyURL string, dockerClient, work
return failures
}
func getContainerImageInfo(ctx context.Context, cli *client.Client, containerName string) *ImageInfo {
containers, err := cli.ContainerList(ctx, container.ListOptions{All: true})
if err != nil {
return nil
}
for _, cont := range containers {
for _, name := range cont.Names {
if strings.TrimPrefix(name, "/") == containerName {
return parseImageRef(cont.Image, cont.ImageID)
}
}
}
return nil
}
func checkImageExists(ctx context.Context, cli *client.Client, imageName string) bool {
imageInfo := getImageInfo(ctx, cli, imageName)
return imageInfo != nil && imageInfo.Hash != ""
@@ -808,7 +744,7 @@ func getImageInfo(ctx context.Context, cli *client.Client, imageName string) *Im
return nil
}
images, err := cli.ImageList(ctx, image.ListOptions{})
images, err := cli.ImageList(ctx, client.ImageListOptions{})
if err != nil {
return nil
}
@@ -819,7 +755,7 @@ func getImageInfo(ctx context.Context, cli *client.Client, imageName string) *Im
}
fullImageName := imageInfo.Name + ":" + imageInfo.Tag
for _, img := range images {
for _, img := range images.Items {
for _, tag := range img.RepoTags {
if tag == imageName || tag == fullImageName {
imageInfo.Hash = img.ID
@@ -831,6 +767,26 @@ func getImageInfo(ctx context.Context, cli *client.Client, imageName string) *Im
return imageInfo
}
// isDockerHubHost reports whether a leading path element is one of the names
// Docker Hub answers to. It is a closed list and not a shape test: "contains a
// dot or a colon" describes every registry there is.
func isDockerHubHost(head string) bool {
switch head {
case "docker.io", "index.docker.io", "registry-1.docker.io", "registry.hub.docker.com":
return true
default:
return false
}
}
// parseImageRef splits a Docker image reference into the repository and tag the update
// server matches on, plus whatever digest the reference or the daemon carried.
//
// The shape is [registry[:port]/]path[:tag][@digest]. The colon of a registry port and the
// colon of a tag are told apart by position, not by content: a tag colon is the last colon
// after the last slash, so a version-numbered tag such as "11.4.0" is not taken for a port.
// A mangled pair fails silently: the update server matches on the repository and tag pair,
// and a pair it does not track is offered nothing, which reads as "nothing to update".
func parseImageRef(imageRef, imageID string) *ImageInfo {
if imageRef == "" {
return nil
@@ -840,67 +796,47 @@ func parseImageRef(imageRef, imageID string) *ImageInfo {
Hash: imageID,
}
// normalize the image reference
originalRef := imageRef
// parse hash if present (image@sha256:...)
if strings.Contains(imageRef, "@") {
parts := strings.SplitN(imageRef, "@", 2)
imageRef = parts[0]
if len(parts) > 1 {
info.Hash = parts[1]
// A digest pins the reference and is not part of the name.
if base, digest, found := strings.Cut(imageRef, "@"); found {
imageRef = base
if digest != "" {
info.Hash = digest
}
}
// handle registry/namespace/repository parsing
var name string
if strings.Contains(imageRef, "/") {
// has registry or namespace
nameParts := strings.Split(imageRef, "/")
if len(nameParts) >= 2 {
// check if first part looks like a registry (contains . or :)
if strings.Contains(nameParts[0], ".") || strings.Contains(nameParts[0], ":") {
// first part is registry, skip it for name extraction
if len(nameParts) > 2 {
name = strings.Join(nameParts[1:], "/")
} else {
name = nameParts[1]
}
} else {
// no registry, combine all parts as name
name = imageRef
}
} else {
name = imageRef
// The registry host is dropped ONLY for Docker Hub, and keeping it everywhere
// else is the whole point.
//
// The service stores a reference the way compose writes it: bare for Docker
// Hub, host and all for anywhere else — `gcr.io/cadvisor/cadvisor`, not
// `cadvisor/cadvisor`. Those two are different images: the second is a Docker
// Hub repository that has nothing to do with cAdvisor. The match is an exact
// string comparison, so a reference of another registry reported without its
// host is answered `repository_not_tracked` and takes its whole stack's
// resolution down to `not_tracked`.
if head, rest, found := strings.Cut(imageRef, "/"); found {
if isDockerHubHost(head) {
imageRef = rest
}
} else {
name = imageRef
}
// parse name and tag
if strings.Contains(name, ":") {
parts := strings.SplitN(name, ":", 2)
info.Name = parts[0]
if len(parts) > 1 && parts[1] != "" {
// validate that it's not a port number (for registry detection edge case)
if !strings.Contains(parts[1], ".") {
info.Tag = parts[1]
} else {
info.Name = name
info.Tag = "latest"
}
}
} else {
info.Name = name
info.Tag = "latest"
// Docker Hub spells an official image "library/nginx" in full; every other place spells
// it "nginx", and that is the form the server is asked about.
imageRef = strings.TrimPrefix(imageRef, "library/")
// The tag is what follows the last colon, and only when that colon comes after the last
// slash — otherwise it belongs to a registry port that was kept as part of the name.
name, tag := imageRef, ""
if colon := strings.LastIndex(imageRef, ":"); colon > strings.LastIndex(imageRef, "/") {
name, tag = imageRef[:colon], imageRef[colon+1:]
}
// if we still don't have a tag, default to latest
info.Name, info.Tag = name, tag
if info.Tag == "" {
info.Tag = "latest"
}
// validate that name is not empty
if info.Name == "" {
info.Name = originalRef
info.Tag = "latest"
@@ -909,55 +845,6 @@ func parseImageRef(imageRef, imageID string) *ImageInfo {
return info
}
func checkUpdatesServer(
ctx context.Context,
serverURL, proxyURL string,
request CheckUpdatesRequest,
) *CheckUpdatesResponse {
jsonData, err := json.Marshal(request)
if err != nil {
return nil
}
client := &http.Client{
Timeout: 30 * time.Second,
}
if proxyURL != "" {
if proxyURLParsed, err := url.Parse(proxyURL); err == nil {
client.Transport = &http.Transport{
Proxy: http.ProxyURL(proxyURLParsed),
}
}
}
fullURL := serverURL + UpdatesCheckEndpoint
req, err := http.NewRequestWithContext(ctx, "POST", fullURL, bytes.NewBuffer(jsonData))
if err != nil {
return nil
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", UserAgent)
resp, err := client.Do(req)
if err != nil {
return nil
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil
}
var response CheckUpdatesResponse
if err := json.NewDecoder(resp.Body).Decode(&response); err != nil {
return nil
}
return &response
}
func checkDNSResolution(hostname string) bool {
_, err := net.LookupHost(hostname)
return err == nil
@@ -1010,7 +897,7 @@ func checkDockerPullConnectivity(ctx context.Context, dockerClient, workerClient
func checkSingleDockerPull(ctx context.Context, cli *client.Client, imageName string) bool {
// try to pull the image
reader, err := cli.ImagePull(ctx, imageName, image.PullOptions{})
reader, err := cli.ImagePull(ctx, imageName, client.ImagePullOptions{})
if err != nil {
return false
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,132 @@
package checker
import (
"bytes"
"context"
"encoding/json"
"io"
"time"
"pentagi/cmd/installer/wizard/logger"
"github.com/moby/moby/api/pkg/stdcopy"
"github.com/moby/moby/client"
"github.com/vxcontrol/cloud/models"
)
// productInfoCommand asks the running product to describe its own state.
const productInfoBinary = "/opt/pentagi/bin/pentagi"
// productInfoTimeout bounds the whole exchange.
//
// This is an optional extra on a gathering the user is waiting for. A product
// that does not answer promptly costs nothing beyond a missing field, and must
// never cost the update check itself.
const productInfoTimeout = 20 * time.Second
// maxProductInfoBytes bounds what is read back.
//
// The contract that carries this field refuses anything larger, so reading more
// would only build a request the service rejects whole — losing the answer for
// every component along with it.
//
// It is the contract's own constant rather than a number that agrees with it
// today. This was written as 64 KiB against a 16 KiB contract: a product whose
// description landed in between passed every check here and cost the installation
// the answer for all of its components, and the local test could not see it
// because it measured against this same constant.
const maxProductInfoBytes = models.MaxProductInfoBytes
// gatherProductInfo asks the running product for its state and returns it exactly
// as it was given.
//
// Nothing here interprets the document. It is read, checked for being JSON at
// all, and carried on; whoever consumes it decides what it means. That is not
// laziness — the installer and the product are released separately, so anything
// the installer understood about the shape would become a second place to update
// whenever the product learns to describe more of itself.
//
// Every failure is silent by design and returns nil: no container, an older build
// without the flag, a product that cannot reach its own database, output that is
// not JSON. The update check proceeds without the field, exactly as it did before
// the field existed.
func (h *defaultCheckHandler) gatherProductInfo(ctx context.Context) json.RawMessage {
if h.dockerClient == nil {
return nil
}
ctx, cancel := context.WithTimeout(ctx, productInfoTimeout)
defer cancel()
container, err := h.dockerClient.ContainerInspect(ctx, PentagiContainerName, client.ContainerInspectOptions{})
if err != nil {
return nil
}
if container.Container.State == nil || !container.Container.State.Running {
// A stopped product cannot describe itself, and the description of a
// stopped product would not be the one anybody wants anyway.
return nil
}
exec, err := h.dockerClient.ExecCreate(ctx, PentagiContainerName, client.ExecCreateOptions{
Cmd: []string{productInfoBinary, "-info"},
AttachStdout: true,
AttachStderr: true,
})
if err != nil {
logger.Debugf("product state: exec create failed: %v", err)
return nil
}
attached, err := h.dockerClient.ExecAttach(ctx, exec.ID, client.ExecAttachOptions{})
if err != nil {
logger.Debugf("product state: exec attach failed: %v", err)
return nil
}
defer attached.Close()
// The stream is MULTIPLEXED. Without a TTY the daemon frames every chunk with
// an eight-byte header saying which stream it came from and how long it is, so
// reading the socket directly yields JSON with binary interleaved through it —
// and the first header lands in front of the opening brace, which makes even a
// perfectly good document unparsable.
var stdout, stderr bytes.Buffer
if _, err := stdcopy.StdCopy(
&stdout,
&stderr,
io.LimitReader(attached.Reader, maxProductInfoBytes+1),
); err != nil {
logger.Debugf("product state: reading the answer failed: %v", err)
return nil
}
// The exit code decides whether the output is an answer or the remains of one.
// A truncated document that happens to parse would be worse than no document.
inspected, err := h.dockerClient.ExecInspect(ctx, exec.ID, client.ExecInspectOptions{})
if err == nil && inspected.ExitCode != 0 {
logger.Debugf("product state: the product exited with %d", inspected.ExitCode)
return nil
}
return productInfoFromOutput(stdout.Bytes())
}
// productInfoFromOutput decides whether what came back is a document.
//
// Separate from the exchange above so that the decision can be exercised without
// a container: everything that makes this fail in practice — an older build
// printing usage, a half-written answer, an answer larger than the contract
// accepts — is a property of the bytes, not of the daemon.
func productInfoFromOutput(output []byte) json.RawMessage {
answer := bytes.TrimSpace(output)
if len(answer) == 0 || len(answer) > maxProductInfoBytes {
return nil
}
if !json.Valid(answer) {
// An older build has no such flag and prints its usage, or nothing at all.
// Either way there is no document here.
return nil
}
return json.RawMessage(answer)
}
@@ -0,0 +1,110 @@
package checker
import (
"bytes"
"encoding/binary"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"strings"
"sync"
"testing"
"github.com/moby/moby/api/pkg/stdcopy"
"github.com/vxcontrol/cloud/models"
)
// frame writes one chunk the way the daemon multiplexes a non-TTY exec: stream, three zero bytes, big-endian length.
func frame(buffer *bytes.Buffer, stream stdcopy.StdType, payload string) {
var header [8]byte
header[0] = byte(stream)
binary.BigEndian.PutUint32(header[4:], uint32(len(payload)))
buffer.Write(header[:])
buffer.WriteString(payload)
}
// productInfoExecStream answers an exec start as the daemon does: upgrade the connection, write the raw stream.
func productInfoExecStream(t *testing.T, stream []byte) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
_, _ = io.Copy(io.Discard, r.Body)
conn, _, err := http.NewResponseController(w).Hijack()
if err != nil {
t.Errorf("hijack: %v", err)
return
}
defer conn.Close()
upgrade := "HTTP/1.1 101 UPGRADED\r\nContent-Type: application/vnd.docker.multiplexed-stream\r\n" +
"Connection: Upgrade\r\nUpgrade: tcp\r\n\r\n"
if _, err := conn.Write(append([]byte(upgrade), stream...)); err != nil {
t.Errorf("write the exec stream: %v", err)
return
}
// A half-close, then waiting for the client to hang up, lets it read to EOF instead of a reset.
if tcp, ok := conn.(*net.TCPConn); ok {
_ = tcp.CloseWrite()
}
_, _ = io.Copy(io.Discard, conn)
}
}
func TestProductInfo_GatherProductInfo_DemultiplexesTheExecStream(t *testing.T) {
const document = `{"schema":1,"version":"0.9.3"}`
var stream bytes.Buffer
frame(&stream, stdcopy.Stderr, "cannot reach the database\n")
frame(&stream, stdcopy.Stdout, document)
if json.Valid(stream.Bytes()) {
t.Fatal("the framed stream parses as JSON, so it cannot tell a demultiplexed read from a raw one")
}
tests := []struct {
name string
running bool
exitCode int
want string
}{
{"a running product's answer arrives without its stderr", true, 0, document},
{"a product that exits with an error gave no answer", true, 1, ""},
{"a stopped product is not asked", false, 0, ""},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
docker := checkerFakeDocker(t, map[string]http.HandlerFunc{
"GET /containers/pentagi/json": checkerJSON(http.StatusOK, fmt.Sprintf(`{"State":{"Running":%t}}`, tt.running)),
"POST /containers/pentagi/exec": checkerJSON(http.StatusCreated, `{"Id":"info"}`),
"POST /exec/info/start": productInfoExecStream(t, stream.Bytes()),
"GET /exec/info/json": checkerJSON(http.StatusOK, fmt.Sprintf(`{"ExitCode":%d}`, tt.exitCode)),
})
handler := &defaultCheckHandler{mx: &sync.Mutex{}, dockerClient: docker}
if got := string(handler.gatherProductInfo(t.Context())); got != tt.want {
t.Errorf("product info = %q, want %q", got, tt.want)
}
})
}
}
func TestProductInfo_ProductInfoFromOutput_CarriesOnlyADocumentTheContractAccepts(t *testing.T) {
future := `{"schema":7,"version":"9.9.9","engine":{"scenarios":12},"unheard_of":[1,2,3]}`
atTheBound := `{"p":"` + strings.Repeat("x", models.MaxProductInfoBytes-8) + `"}`
tests := []struct {
name, output, want string
}{
{"a document from a newer product, byte for byte", " " + future + "\n", future},
{"a document exactly at the contract's bound", atTheBound, atTheBound},
{"an older build printing usage", "Usage of /opt/pentagi/bin/pentagi:\n -info\n", ""},
{"nothing at all", "", ""},
{"whitespace only", " \n\t ", ""},
{"a truncated document", `{"schema":1,"version":`, ""},
{"a log line before the answer", "level=info msg=starting\n" + `{"schema":1}`, ""},
{"one byte over the contract's bound", `{"p":"` + strings.Repeat("x", models.MaxProductInfoBytes-7) + `"}`, ""},
}
for _, tt := range tests {
got := productInfoFromOutput([]byte(tt.output))
if string(got) != tt.want || (got == nil) != (tt.want == "") {
t.Errorf("%s: carried %d bytes, want %d", tt.name, len(got), len(tt.want))
}
}
}
+618
View File
@@ -0,0 +1,618 @@
package checker
import (
"context"
"errors"
"runtime"
"strings"
"time"
"pentagi/cmd/installer/cloud"
"pentagi/cmd/installer/state"
"pentagi/cmd/installer/wizard/logger"
"github.com/vxcontrol/cloud/models"
)
// StackUpdate is what the update server said about one product stack.
//
// HasUpdate is the stack-level verdict and the only thing the menu needs. Everything else
// is for the screen that explains the update before it is applied: which version is
// current, which is offered, and what the release says about the difference.
type StackUpdate struct {
Stack string `json:"stack" yaml:"stack"`
HasUpdate bool `json:"has_update" yaml:"has_update"`
CurrentVersion string `json:"current_version,omitempty" yaml:"current_version,omitempty"`
LatestVersion string `json:"latest_version,omitempty" yaml:"latest_version,omitempty"`
// CurrentVersionMixed says the stack's components came from DIFFERENT releases, so
// CurrentVersion names the oldest of them rather than a version this installation as
// a whole ever was. Legitimate — a component nobody rebuilt stays on its old release
// — but "you are on 2.1.0" and "the oldest thing you have is from 2.1.0" are
// different sentences and the overview must not print the first when it means the
// second.
CurrentVersionMixed bool `json:"current_version_mixed,omitempty" yaml:"current_version_mixed,omitempty"`
// Changelog and ReleaseNotes carry the TARGET release's text only. They are the
// fallback for a server that predates Releases; when Releases is present its last
// entry carries the same text.
Changelog string `json:"changelog,omitempty" yaml:"changelog,omitempty"`
ReleaseNotes string `json:"release_notes,omitempty" yaml:"release_notes,omitempty"`
// Releases is every curated release this update crosses, oldest first, the last one
// being the target. Empty when the server did not send any — either it is older than
// the field, or there is genuinely nothing to cross.
Releases []ReleaseSummary `json:"releases,omitempty" yaml:"releases,omitempty"`
// ReleasesTruncated says older entries were dropped by the server.
ReleasesTruncated bool `json:"releases_truncated,omitempty" yaml:"releases_truncated,omitempty"`
// Resolution says HOW the server arrived at this answer — release, channel,
// ahead_of_release, no_artifact_for_tag, not_tracked. It is DIAGNOSTIC ONLY:
// nothing here may branch on it, and it exists so `has_update: false` can be
// read in a log instead of guessed at.
Resolution string `json:"resolution,omitempty" yaml:"resolution,omitempty"`
Components []ComponentUpdate `json:"components,omitempty" yaml:"components,omitempty"`
}
// ReleaseSummary is one curated release crossed by applying an update.
type ReleaseSummary struct {
Version string `json:"version" yaml:"version"`
IsStable bool `json:"is_stable" yaml:"is_stable"`
ReleasedAt string `json:"released_at,omitempty" yaml:"released_at,omitempty"`
Changelog string `json:"changelog,omitempty" yaml:"changelog,omitempty"`
ReleaseNotes string `json:"release_notes,omitempty" yaml:"release_notes,omitempty"`
}
// ComponentUpdate is one artefact inside a stack, and what would change for it.
//
// Being listed does NOT mean the artefact is outdated. Under the stable strategy the
// answer names every artefact of the release that matches something reported, so the
// installation can be attributed to a version even when nothing needs doing. Outdated is
// the conclusion drawn here by comparing digests.
type ComponentUpdate struct {
Component string `json:"component" yaml:"component"`
OS string `json:"os" yaml:"os"`
Arch string `json:"arch" yaml:"arch"`
Repository string `json:"repository,omitempty" yaml:"repository,omitempty"`
Tag string `json:"tag,omitempty" yaml:"tag,omitempty"`
// Action is what the SERVER says to do — current, install, upgrade,
// downgrade or unknown — and it is the authority. Membership in the answer
// is not: under a curated release every artefact matching a reported
// component is listed, whether or not it differs from what is installed.
//
// Reason explains an `unknown`, and is empty for every other action. It is
// the difference between "nothing to do" and "we publish nothing for what you
// are running", which are opposite situations that used to arrive identically.
Action string `json:"action,omitempty" yaml:"action,omitempty"`
Reason string `json:"reason,omitempty" yaml:"reason,omitempty"`
// PullReference is what to write into the compose variable before pulling,
// ready to use. It is NOT always `repository:tag` — which tag to pull is the
// cloud's decision and varies with the update strategy, so composing one here
// out of the repository and tag fields would override the answer with a guess.
PullReference string `json:"pull_reference,omitempty" yaml:"pull_reference,omitempty"`
// Outdated is true only when the installed artefact is known AND differs from the
// offered one.
Outdated bool `json:"outdated" yaml:"outdated"`
// Verifiable is false when there is nothing on THIS side to compare: nothing is
// installed yet, or the server answered `unknown` and there is no artefact at all. An
// unverifiable component is not a mismatch, and saying so is the difference between
// "this will change" and "we cannot tell".
//
// It says nothing about whether the ANSWER carried a digest we can match — the server
// compared against what we reported and its action is the authority either way.
Verifiable bool `json:"verifiable" yaml:"verifiable"`
CurrentVersion string `json:"current_version,omitempty" yaml:"current_version,omitempty"`
// TargetVersion is the VERSION of the offered artefact, and only that. Files have
// one; images do not (the cloud identifies their builds by digest), so it stays empty
// for them. It is what the self-update download asks for as `?version=`.
TargetVersion string `json:"target_version,omitempty" yaml:"target_version,omitempty"`
// TargetDigest is the sha256 an updated artefact should end up carrying, in the same
// identity the installed side reports: the config digest for an image, the file hash
// for a file.
//
// Separate from TargetVersion because the two are not interchangeable and were once
// the same field. Post-update verification compares this against what is on disk, and
// with a version in it the Jaeger plugin — which has a hash and no version at all —
// reported a mismatch after every successful update: "expected 0.13.0, got a423c6…".
//
// Empty means the cloud did not name a digest, and verification degrades to "nothing
// to compare" rather than inventing a mismatch.
TargetDigest string `json:"target_digest,omitempty" yaml:"target_digest,omitempty"`
}
// InstalledComponent is what the last update check reported about one artefact on this
// machine. It is kept because verifying an update afterwards needs to know what was
// installed, and re-inspecting every container a second time would ask Docker the same
// questions the check already asked.
type InstalledComponent struct {
Component string `json:"component" yaml:"component"`
OS string `json:"os" yaml:"os"`
Arch string `json:"arch" yaml:"arch"`
Status string `json:"status" yaml:"status"`
Repository string `json:"repository,omitempty" yaml:"repository,omitempty"`
Tag string `json:"tag,omitempty" yaml:"tag,omitempty"`
// Digest is the image config digest, or the file digest for components that ship as
// files. Empty when nothing observable was installed.
Digest string `json:"digest,omitempty" yaml:"digest,omitempty"`
Version string `json:"version,omitempty" yaml:"version,omitempty"`
}
// UpdateCheckFailure explains why the update check produced no answer, in terms the
// interface can act on. A bare "server unavailable" tells the user nothing they can do
// about it — a spent daily quota and a broken proxy call for opposite reactions.
type UpdateCheckFailure struct {
Reason string `json:"reason" yaml:"reason"`
Message string `json:"message" yaml:"message"`
// RetryAfter is the server-advertised cooldown; zero when there is none, either
// because the server did not say or because waiting will not help.
RetryAfter time.Duration `json:"retry_after" yaml:"retry_after"`
// Retryable separates "come back later" from "this needs a different license".
Retryable bool `json:"retryable" yaml:"retryable"`
}
// updateStackFlags maps a contract stack onto the per-stack flag the menus already read,
// so the answer changes what those flags say without the screens having to change.
type stackFlag struct {
stack models.ProductStack
set func(c *CheckResult, upToDate bool)
}
var updateStackFlags = []stackFlag{
{models.ProductStackPentagi, func(c *CheckResult, v bool) { c.PentagiIsUpToDate = v }},
{models.ProductStackWorker, func(c *CheckResult, v bool) { c.WorkerIsUpToDate = v }},
{models.ProductStackInstaller, func(c *CheckResult, v bool) { c.InstallerIsUpToDate = v }},
{models.ProductStackGraphiti, func(c *CheckResult, v bool) { c.GraphitiIsUpToDate = v }},
{models.ProductStackLangfuse, func(c *CheckResult, v bool) { c.LangfuseIsUpToDate = v }},
{models.ProductStackObservability, func(c *CheckResult, v bool) { c.ObservabilityIsUpToDate = v }},
}
// GatherUpdatesInfo asks the update server what is available for this installation.
//
// It never fails the surrounding gather: an update check that cannot be made is a fact
// about the installation, recorded in the result, not a reason to abandon everything else
// the checker learned.
func (h *defaultCheckHandler) GatherUpdatesInfo(ctx context.Context, c *CheckResult) error {
h.mx.Lock()
defer h.mx.Unlock()
client, err := h.updateClient()
if err != nil {
c.recordUpdateFailure(err)
return nil
}
if warning := client.LicenseWarning(); warning != nil {
// The check still runs, just without the license — say so, because otherwise the
// only symptom is a tier the user did not expect.
logger.Warnf("update check: %v", warning)
}
components := h.gatherComponents(ctx, c)
// Recorded before the call: what is installed is a local fact, true whether or not the
// server answers, and the verification after an update needs it either way.
c.recordInstalledComponents(components)
request := models.CheckUpdatesRequest{
// The installer is a binary for THIS machine, so its platform is the host's.
// Every other component describes an image and carries its own.
InstallerVersion: cloud.NormalizeVersion(InstallerVersion),
InstallerOS: models.OSType(runtime.GOOS),
InstallerArch: models.ArchType(runtime.GOARCH),
Strategy: updateStrategy(h.appState),
Images: components.images,
Files: components.files,
// Reported for its own sake: nothing in the answer depends on it. A stack
// deployed elsewhere contributes no components at all — there is no
// reference to resolve — so without this the service cannot tell "runs
// Langfuse on their own cluster" from "does not use Langfuse".
Stacks: stackStatuses(c),
// What the product says about itself, carried through untouched. Absent
// whenever the product is not running or cannot be asked, which is why it
// is gathered last and why nothing below depends on it.
Info: h.gatherProductInfo(ctx),
}
response, err := client.CheckUpdates(ctx, request)
if err != nil {
c.recordUpdateFailure(err)
return nil
}
c.applyUpdateAnswer(response, components)
return nil
}
// updateClient builds the client for this installation's configuration.
func (h *defaultCheckHandler) updateClient() (*cloud.Client, error) {
defaultUpdateServerHost := strings.TrimPrefix(strings.TrimSuffix(DefaultUpdateServerEndpoint, "/"), "https://")
return cloud.New(cloud.Config{
Host: getEnvVar(h.appState, "UPDATE_SERVER_HOST", defaultUpdateServerHost),
ProxyURL: getProxyURL(h.appState),
LicenseKey: getEnvVar(h.appState, "LICENSE_KEY", ""),
InstallerVersion: InstallerVersion,
})
}
// DefaultUpdateStrategy is the channel an installation follows when it has not
// been told otherwise.
//
// `preview` rather than `stable`, and the difference is not caution versus
// eagerness. Under `stable` the answer is measured against curated releases, and
// an installation whose stack has no published release is offered nothing at all
// — which reads to the user as "no updates exist" rather than "we are not
// publishing releases for this yet". `preview` follows the channels the client is
// already on, which is what an installation actually wants until releases are a
// thing it can rely on.
const DefaultUpdateStrategy = models.UpdateStrategyPreview
// updateStrategy reads which release channel to follow. An unrecognised value falls back
// to the default rather than failing the check, and says so: a typo should not leave an
// installation unable to learn about security updates.
func updateStrategy(appState state.State) models.UpdateStrategy {
configured := strings.ToLower(strings.TrimSpace(getEnvVar(appState, "UPDATE_STRATEGY", "")))
if configured == "" {
return DefaultUpdateStrategy
}
strategy := models.UpdateStrategy(configured)
if err := strategy.Valid(); err != nil {
logger.Warnf("unknown UPDATE_STRATEGY %q, falling back to %s", configured, DefaultUpdateStrategy)
return DefaultUpdateStrategy
}
return strategy
}
// recordInstalledComponents stores what the gathering observed on this machine.
func (c *CheckResult) recordInstalledComponents(components reportedComponents) {
c.InstalledComponents = make([]InstalledComponent, 0, components.total())
for _, component := range components.images {
c.InstalledComponents = append(c.InstalledComponents, InstalledComponent{
Component: component.Component.String(),
OS: component.OS.String(),
Arch: component.Arch.String(),
Status: component.Status.String(),
Repository: component.Repository,
Tag: component.Tag,
Digest: derefString(component.ImageHash),
})
}
for _, component := range components.files {
c.InstalledComponents = append(c.InstalledComponents, InstalledComponent{
Component: component.Component.String(),
OS: component.OS.String(),
Arch: component.Arch.String(),
Status: component.Status.String(),
Digest: derefString(component.FileHash),
Version: derefString(component.Version),
})
}
}
// recordUpdateFailure stores why the check produced nothing and resets every per-stack
// flag.
//
// Resetting ALL of them matters: leaving one behind means a stack keeps whatever verdict
// an earlier, successful check left in it, and the interface presents a stale answer as a
// current one. The worker flag used to be the one left behind.
func (c *CheckResult) recordUpdateFailure(err error) {
c.UpdateServerAccessible = false
c.StackUpdates = nil
for _, flag := range updateStackFlags {
flag.set(c, false)
}
failure := &UpdateCheckFailure{
Reason: string(cloud.FailureUnreachable),
Message: err.Error(),
}
var classified *cloud.Failure
if errors.As(err, &classified) {
failure.Reason = string(classified.Reason)
failure.RetryAfter = classified.RetryAfter
failure.Retryable = classified.Reason.Retryable()
}
c.UpdateFailure = failure
logger.Warnf("update check failed (%s): %v", failure.Reason, err)
}
// applyUpdateAnswer turns the server's answer into the per-stack verdicts the menus read
// and the detail the update screen shows.
//
// A stack missing from the answer stays "up to date": the server reports on what it was
// asked about, and no news is not the same as bad news. Offering an update nobody has
// evidence for is the worse failure.
func (c *CheckResult) applyUpdateAnswer(response *models.CheckUpdatesResponse, reported reportedComponents) {
c.UpdateServerAccessible = true
c.UpdateFailure = nil
for _, flag := range updateStackFlags {
flag.set(c, true)
}
installed := make(map[string]installedArtefact, reported.total())
for _, component := range reported.images {
installed[componentKey(component.Component, component.OS, component.Arch)] = installedArtefact{
digest: component.ImageHash,
}
}
for _, component := range reported.files {
installed[componentKey(component.Component, component.OS, component.Arch)] = installedArtefact{
digest: component.FileHash,
version: component.Version,
}
}
c.StackUpdates = make([]StackUpdate, 0, len(response.Updates))
for _, update := range response.Updates {
for _, flag := range updateStackFlags {
if flag.stack == update.Stack {
flag.set(c, !update.HasUpdate)
}
}
c.StackUpdates = append(c.StackUpdates, buildStackUpdate(update, installed))
}
}
// installedArtefact is what is known about an artefact on this machine, in the one shape
// both kinds share: something to compare an offer against.
type installedArtefact struct {
digest *string
version *string
}
func buildStackUpdate(update models.UpdateInfo, installed map[string]installedArtefact) StackUpdate {
stack := StackUpdate{
Stack: update.Stack.String(),
HasUpdate: update.HasUpdate,
CurrentVersion: derefString(update.CurrentVersion),
CurrentVersionMixed: update.CurrentVersionMixed,
LatestVersion: derefString(update.LatestVersion),
Changelog: derefString(update.Changelog), //nolint:staticcheck
ReleaseNotes: derefString(update.ReleaseNotes),
ReleasesTruncated: update.ReleasesTruncated,
Resolution: string(update.Resolution),
}
// Copied rather than referenced: CheckResult is serialised to the state file, and a
// time.Time there would round-trip through a format nothing else in this struct uses.
// The overview only ever prints the date.
for _, release := range update.Releases {
summary := ReleaseSummary{
Version: release.Version,
IsStable: release.IsStable,
Changelog: release.Changelog,
ReleaseNotes: release.ReleaseNotes,
}
if release.ReleasedAt != nil {
summary.ReleasedAt = release.ReleasedAt.UTC().Format(time.RFC3339)
}
stack.Releases = append(stack.Releases, summary)
}
stack.Components = make([]ComponentUpdate, 0, len(update.Images)+len(update.Files))
for _, offered := range update.Images {
current := installed[componentKey(offered.Component, offered.OS, offered.Arch)]
stack.Components = append(stack.Components, buildImageComponentUpdate(offered, current))
}
for _, offered := range update.Files {
current := installed[componentKey(offered.Component, offered.OS, offered.Arch)]
stack.Components = append(stack.Components, buildFileComponentUpdate(offered, current))
}
// Logged and nothing more. `resolution` explains an answer — "you are ahead
// of the curated set", "we track nothing under that reference" — and the one
// thing it must never do is drive a decision here: it is diagnostic by
// contract, and a client branching on it would couple itself to wording the
// server is free to extend.
if stack.Resolution != "" {
logger.Debugf("update check: stack %s resolved as %s (has_update=%t)",
stack.Stack, stack.Resolution, stack.HasUpdate)
}
for _, component := range stack.Components {
if component.Reason != "" {
logger.Debugf("update check: %s is %s — %s",
component.Component, component.Action, component.Reason)
}
}
return stack
}
// buildComponentUpdate decides whether one artefact would actually change.
//
// Images are compared by digest, not by tag: a moving tag such as "latest" points at a
// different image over time, so the tag alone says nothing. Binaries are compared by
// version, which is how the server identifies their builds.
//
// A comparison that cannot be made is reported as unverifiable rather than as a
// difference. The server omits a digest it does not know, and treating an absent value as
// a mismatch would offer an update on no evidence at all.
func buildImageComponentUpdate(offered models.ImageUpdate, current installedArtefact) ComponentUpdate {
component := ComponentUpdate{
Component: offered.Component.String(),
OS: offered.OS.String(),
Arch: offered.Arch.String(),
Repository: offered.Repository,
Tag: offered.Tag,
Action: string(offered.Action),
PullReference: offered.PullReference,
}
if offered.Reason != nil {
component.Reason = string(*offered.Reason)
}
// The target an updated image should end up carrying is the offered CONFIG
// digest: the installed side of every comparison is normalizeDigest(image.ID),
// which is `docker inspect` → Id, and ConfigHash is the same identity as the
// server resolved it (cloud/models: "this is the value to verify a pulled
// image against"). Without this the post-update verification had a target of
// "" for every image, routed each one to "not verifiable", and then printed
// the pass line for an update that may not have taken.
//
// When the server does not know the config digest the target stays empty and
// verification degrades honestly to "cannot verify" — never to a mismatch.
//
// TargetVersion is deliberately left empty here: an image has no version of its
// own in the answer, and the field means a version everywhere else.
if offered.ConfigHash != nil {
component.TargetDigest = *offered.ConfigHash
}
// Nothing installed means nothing to compare, which is not a mismatch: it is the
// state of a component that has never been pulled, and the answer names what to pull
// rather than a difference to reconcile.
if current.digest != nil {
component.CurrentVersion = *current.digest
component.Verifiable = true
component.Outdated = !offered.CarriesDigest(*current.digest)
}
// The server's own verdict wins where it is more informed than a digest
// comparison can be, and it always is: it compared against the digest THIS
// client reported, knowing every identity the artefact has.
//
// `install` is the case that matters most: nothing is pulled, so there is no
// digest to compare and the loop above leaves `Outdated` false — which reads
// as "nothing to do" for the one component that most needs doing. `unknown`
// is the mirror image: there is no artefact at all, so whatever a comparison
// produced means nothing.
//
// `current` is here because the comparison above can disagree with it and be
// wrong. Docker exposes three sha256 identities per image and this client
// reports the config digest; an answer that names only the manifest digest
// therefore matches nothing locally, and `CarriesDigest` returns false for an
// installation that is exactly up to date. Without this branch the overview
// tells the user a component will be updated while the server has just said
// it will not.
switch offered.Action {
case models.ComponentActionInstall, models.ComponentActionUpgrade, models.ComponentActionDowngrade:
component.Outdated = true
case models.ComponentActionCurrent:
component.Outdated = false
case models.ComponentActionUnknown:
component.Outdated = false
component.Verifiable = false
}
return component
}
// buildFileComponentUpdate is the file half. Files are compared by version, which is how
// the server identifies their builds, and by hash when no version was reported — which is
// the Jaeger plugin's case, since it ships without one.
func buildFileComponentUpdate(offered models.FileUpdate, current installedArtefact) ComponentUpdate {
component := ComponentUpdate{
Component: offered.Component.String(),
OS: offered.OS.String(),
Arch: offered.Arch.String(),
Action: string(offered.Action),
// A file carries both, and they describe different sides. The version is the
// OFFERED build's, and it is always present — a published binary cannot exist
// without one — and it is what the download asks for, since the package request
// requires a version and has no field for a hash. The hash is what the result is
// verified against, and it is the only identity the INSTALLED side has for a
// plugin: a file on disk carries no version metadata. Conflating the two is what
// made a correctly updated plugin report "expected 0.13.0, got a423c6…".
TargetVersion: offered.Version,
TargetDigest: offered.FileHash,
}
if offered.Reason != nil {
component.Reason = string(*offered.Reason)
}
switch {
case current.version != nil:
component.CurrentVersion = *current.version
component.Verifiable = true
component.Outdated = offered.Version != *current.version
case current.digest != nil:
component.CurrentVersion = *current.digest
component.Verifiable = true
component.Outdated = offered.FileHash != *current.digest
}
// Same rule as the image half, for the same reason: the server's action is the
// authority, because it compared against what this client reported. A file that
// was never installed reports neither a version nor a digest, so both branches
// above are skipped; and a `current` verdict has to survive a version string
// that merely spells the same build differently.
switch offered.Action {
case models.ComponentActionInstall, models.ComponentActionUpgrade, models.ComponentActionDowngrade:
component.Outdated = true
case models.ComponentActionCurrent:
component.Outdated = false
case models.ComponentActionUnknown:
component.Outdated = false
component.Verifiable = false
}
return component
}
// componentKey identifies an artefact across the request and the answer. The platform is
// part of it: the Jaeger plugin is reported twice, once per architecture, and matching on
// the component name alone would collapse the two.
func componentKey(component models.ComponentType, os models.OSType, arch models.ArchType) string {
return component.String() + "/" + os.String() + "/" + arch.String()
}
func derefString(value *string) string {
if value == nil {
return ""
}
return *value
}
// stackStatuses says how each product stack is deployed on this machine.
//
// Every stack is reported, including the unused ones: silence about a stack is
// indistinguishable from an installer too old to speak about stacks at all, and
// the difference matters to whoever reads the numbers.
//
// The precedence between installed and external is deliberate. `external` is the
// more specific statement — it says who OPERATES the stack — and an installation
// pointing at somebody else's Langfuse may well also have the compose file on
// disk.
func stackStatuses(c *CheckResult) []models.StackInfo {
state := func(connected, installed, external bool) models.StackStatus {
switch {
case !connected:
return models.StackStatusUnused
case external:
return models.StackStatusExternal
case installed:
return models.StackStatusInstalled
default:
return models.StackStatusConnected
}
}
worker := models.StackStatusUnused
if c.WorkerImageExists {
worker = models.StackStatusInstalled
}
return []models.StackInfo{
// The product itself and the installer asking the question: both present
// by definition, or this check would not be running.
{Stack: models.ProductStackPentagi, Status: models.StackStatusInstalled},
{Stack: models.ProductStackInstaller, Status: models.StackStatusInstalled},
{Stack: models.ProductStackWorker, Status: worker},
{Stack: models.ProductStackGraphiti, Status: state(
c.GraphitiConnected, c.GraphitiInstalled, c.GraphitiExternal)},
{Stack: models.ProductStackLangfuse, Status: state(
c.LangfuseConnected, c.LangfuseInstalled, c.LangfuseExternal)},
{Stack: models.ProductStackObservability, Status: state(
c.ObservabilityConnected, c.ObservabilityInstalled, c.ObservabilityExternal)},
// Not deployed by compose, so the installer has nothing to observe about
// them — and `undefined` is the value that says exactly that.
//
// They used to be reported as `unused`, on the reasoning that saying
// something beats saying nothing. That reasoning held only while silence
// and `unused` were recorded identically: it made a placeholder for "we
// cannot tell" indistinguishable from a measured negative, and every count
// of engine adoption was reading a hardcoded constant.
{Stack: models.ProductStackEngine, Status: models.StackStatusUndefined},
{Stack: models.ProductStackBrowser, Status: models.StackStatusUndefined},
}
}
@@ -0,0 +1,293 @@
package checker
import (
"errors"
"reflect"
"strings"
"testing"
"time"
"pentagi/cmd/installer/cloud"
"pentagi/cmd/installer/loader"
"github.com/vxcontrol/cloud/models"
"github.com/vxcontrol/cloud/sdk"
)
func ptr[T any](v T) *T { return &v }
func digest(fill string) string {
return strings.Repeat(fill, 64/len(fill))
}
func TestUpdates_RecordUpdateFailure_ResetsEveryVerdictAndSaysWhy(t *testing.T) {
tests := []struct {
name string
err error
wantReason cloud.FailureReason
wantRetry time.Duration
wantRetryable bool
}{
{"a daily quota says when it resets", cloud.Classify(&sdk.QuotaError{
Err: sdk.ErrQuotaExceededDaily, Scope: sdk.QuotaScopeDaily, RetryAfter: 2 * time.Hour,
}), cloud.FailureQuotaExceeded, 2 * time.Hour, true},
{"a tier without access is not a wait", cloud.Classify(sdk.ErrForbidden), cloud.FailureForbidden, 0, false},
{"an unclassified error is still a failure", errors.New("dial tcp: no route to host"), cloud.FailureUnreachable, 0, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := &CheckResult{
UpdateServerAccessible: true,
PentagiIsUpToDate: true, GraphitiIsUpToDate: true, LangfuseIsUpToDate: true,
ObservabilityIsUpToDate: true, InstallerIsUpToDate: true, WorkerIsUpToDate: true,
StackUpdates: []StackUpdate{{Stack: "pentagi"}},
}
result.recordUpdateFailure(tt.err)
for stack, upToDate := range map[string]bool{
"pentagi": result.PentagiIsUpToDate, "graphiti": result.GraphitiIsUpToDate,
"langfuse": result.LangfuseIsUpToDate, "observability": result.ObservabilityIsUpToDate,
"installer": result.InstallerIsUpToDate, "worker": result.WorkerIsUpToDate,
} {
if upToDate {
t.Errorf("stack %s kept its verdict from an earlier check after the check failed", stack)
}
}
if result.UpdateServerAccessible || result.StackUpdates != nil {
t.Errorf("reachable = %t, answer = %v after a failed check", result.UpdateServerAccessible, result.StackUpdates)
}
want := UpdateCheckFailure{
Reason: string(tt.wantReason), Message: tt.err.Error(), RetryAfter: tt.wantRetry, Retryable: tt.wantRetryable,
}
if result.UpdateFailure == nil || *result.UpdateFailure != want {
t.Errorf("failure = %+v, want %+v", result.UpdateFailure, want)
}
})
}
}
func TestUpdates_ApplyUpdateAnswer_KeepsAStackTheAnswerOmitsUpToDate(t *testing.T) {
result := &CheckResult{UpdateFailure: &UpdateCheckFailure{Reason: "stale"}}
answer := &models.CheckUpdatesResponse{Updates: []models.UpdateInfo{
{Stack: models.ProductStackPentagi, HasUpdate: true},
}}
result.applyUpdateAnswer(answer, reportedComponents{})
if result.PentagiIsUpToDate {
t.Error("pentagi has an update but is reported as up to date")
}
for stack, upToDate := range map[string]bool{
"graphiti": result.GraphitiIsUpToDate, "langfuse": result.LangfuseIsUpToDate,
"observability": result.ObservabilityIsUpToDate, "installer": result.InstallerIsUpToDate,
"worker": result.WorkerIsUpToDate,
} {
if !upToDate {
t.Errorf("stack %s is offered an update the server never mentioned", stack)
}
}
if !result.UpdateServerAccessible || result.UpdateFailure != nil {
t.Error("a successful check is recorded as a failure")
}
}
// The Jaeger plugin is reported once per architecture, so the answer must be matched on the platform too.
func TestUpdates_ApplyUpdateAnswer_MatchesEachComponentOnItsPlatform(t *testing.T) {
amd64Digest, arm64Digest := digest("a"), digest("b")
reported := reportedComponents{files: []models.FileComponentInfo{
{Component: models.ComponentTypeJaegerClickhouse, OS: models.OSTypeLinux, Arch: models.ArchTypeAMD64, FileHash: ptr(amd64Digest)},
{Component: models.ComponentTypeJaegerClickhouse, OS: models.OSTypeLinux, Arch: models.ArchTypeARM64, FileHash: ptr(arm64Digest)},
}}
answer := &models.CheckUpdatesResponse{Updates: []models.UpdateInfo{{
Stack: models.ProductStackObservability,
Files: []models.FileUpdate{
{Component: models.ComponentTypeJaegerClickhouse, OS: models.OSTypeLinux, Arch: models.ArchTypeAMD64,
PackageName: "jaeger-clickhouse", Version: "0.13.0", FileHash: amd64Digest},
{Component: models.ComponentTypeJaegerClickhouse, OS: models.OSTypeLinux, Arch: models.ArchTypeARM64,
PackageName: "jaeger-clickhouse", Version: "0.13.0", FileHash: arm64Digest},
},
}}}
result := &CheckResult{}
result.applyUpdateAnswer(answer, reported)
if len(result.StackUpdates) != 1 || len(result.StackUpdates[0].Components) != 2 {
t.Fatalf("got %+v, want one stack with two components", result.StackUpdates)
}
for _, component := range result.StackUpdates[0].Components {
if component.Outdated || !component.Verifiable {
t.Errorf("%s/%s matches what is installed: outdated=%t verifiable=%t",
component.Component, component.Arch, component.Outdated, component.Verifiable)
}
}
}
func TestUpdates_ApplyUpdateAnswer_CarriesTheReleaseTextsToTheUpdateScreen(t *testing.T) {
releasedAt := time.Date(2025, 7, 1, 12, 0, 0, 0, time.FixedZone("CEST", 2*60*60))
answer := &models.CheckUpdatesResponse{Updates: []models.UpdateInfo{{
Stack: models.ProductStackPentagi,
HasUpdate: true,
CurrentVersion: ptr("2.0.0"),
LatestVersion: ptr("2.1.0"),
Changelog: ptr("## Changed\n- everything"),
ReleaseNotes: ptr("## Notes\n- read this"),
Releases: []models.ReleaseNote{{
Version: "2.1.0", IsStable: true, ReleasedAt: &releasedAt, Changelog: "- changed", ReleaseNotes: "- noted",
}},
}}}
result := &CheckResult{}
result.applyUpdateAnswer(answer, reportedComponents{})
if len(result.StackUpdates) != 1 {
t.Fatalf("got %d stacks, want 1", len(result.StackUpdates))
}
got := result.StackUpdates[0]
want := StackUpdate{
Stack: "pentagi", HasUpdate: true, CurrentVersion: "2.0.0", LatestVersion: "2.1.0",
Changelog: "## Changed\n- everything", ReleaseNotes: "## Notes\n- read this",
Releases: []ReleaseSummary{{
Version: "2.1.0", IsStable: true, ReleasedAt: "2025-07-01T10:00:00Z", Changelog: "- changed", ReleaseNotes: "- noted",
}},
Components: []ComponentUpdate{},
}
if !reflect.DeepEqual(got, want) {
t.Errorf("stack = %+v\nwant %+v", got, want)
}
}
func TestUpdates_BuildImageComponentUpdate_TrustsTheServerActionOverADigestComparison(t *testing.T) {
installed := digest("a")
offer := func(edit func(*models.ImageUpdate)) models.ImageUpdate {
update := models.ImageUpdate{
Component: models.ComponentTypePentagi, OS: models.OSTypeLinux, Arch: models.ArchTypeAMD64,
Repository: "vxcontrol/pentagi", Tag: "latest",
}
edit(&update)
return update
}
reason := models.ReasonTagNotPublished
tests := []struct {
name string
offered models.ImageUpdate
installed *string
outdated, verifiable bool
targetDigest, reason string
}{
{"the config digest matches what is installed", offer(func(u *models.ImageUpdate) {
u.ImageHash, u.ConfigHash = digest("z"), ptr(installed)
}), ptr(installed), false, true, installed, ""},
{"the index digest matches though the config digest does not", offer(func(u *models.ImageUpdate) {
u.ImageHash, u.ConfigHash, u.IndexHash = digest("z"), ptr(digest("b")), ptr(installed)
}), ptr(installed), false, true, digest("b"), ""},
{"a genuinely different image targets the offered config digest", offer(func(u *models.ImageUpdate) {
u.ImageHash, u.ConfigHash = digest("z"), ptr(digest("c"))
}), ptr(installed), true, true, digest("c"), ""},
{"nothing installed to compare against", offer(func(u *models.ImageUpdate) {
u.ImageHash, u.ConfigHash = digest("z"), ptr(digest("c"))
}), nil, false, false, digest("c"), ""},
{"no config digest known leaves the target empty", offer(func(u *models.ImageUpdate) {
u.ImageHash = digest("m")
}), ptr(installed), true, true, "", ""},
{"current survives a digest the client never reports", offer(func(u *models.ImageUpdate) {
u.ImageHash, u.Action = digest("m"), models.ComponentActionCurrent
}), ptr(installed), false, true, "", ""},
{"upgrade survives matching digests", offer(func(u *models.ImageUpdate) {
u.ImageHash, u.ConfigHash, u.Action = digest("m"), ptr(installed), models.ComponentActionUpgrade
}), ptr(installed), true, true, installed, ""},
{"an image never pulled is an update", offer(func(u *models.ImageUpdate) {
u.ImageHash, u.Action, u.PullReference = digest("b"), models.ComponentActionInstall, "vxcontrol/pentagi:latest"
}), nil, true, false, "", ""},
{"unknown carries a reason and nothing to act on", offer(func(u *models.ImageUpdate) {
u.Action, u.Reason = models.ComponentActionUnknown, &reason
}), ptr(installed), false, false, "", "tag_not_published"},
{"current with the installed digest stays current", offer(func(u *models.ImageUpdate) {
u.ImageHash, u.Action, u.PullReference = installed, models.ComponentActionCurrent, "vxcontrol/pentagi:latest"
}), ptr(installed), false, true, "", ""},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := buildImageComponentUpdate(tt.offered, installedArtefact{digest: tt.installed})
if got.Outdated != tt.outdated || got.Verifiable != tt.verifiable {
t.Errorf("outdated=%t verifiable=%t, want %t and %t", got.Outdated, got.Verifiable, tt.outdated, tt.verifiable)
}
if got.TargetDigest != tt.targetDigest || got.TargetVersion != "" {
t.Errorf("target digest %q version %q, want digest %q and no version", got.TargetDigest, got.TargetVersion, tt.targetDigest)
}
if got.Action != string(tt.offered.Action) || got.PullReference != tt.offered.PullReference || got.Reason != tt.reason {
t.Errorf("action %q pull %q reason %q, want %q, %q, %q", got.Action, got.PullReference, got.Reason,
tt.offered.Action, tt.offered.PullReference, tt.reason)
}
})
}
}
func TestUpdates_BuildFileComponentUpdate_ComparesTheVersionThenTheHash(t *testing.T) {
tests := []struct {
name string
offered models.FileUpdate
installed installedArtefact
outdated, verifiable bool
}{
{"a newer installer build", models.FileUpdate{Component: models.ComponentTypeInstaller, OS: models.OSTypeDarwin,
Arch: models.ArchTypeARM64, PackageName: "installer", Version: "2.1.0", FileHash: digest("z")},
installedArtefact{version: ptr("2.0.0")}, true, true},
{"the same installer build", models.FileUpdate{Component: models.ComponentTypeInstaller, OS: models.OSTypeDarwin,
Arch: models.ArchTypeARM64, PackageName: "installer", Version: "2.0.0", FileHash: digest("z")},
installedArtefact{version: ptr("2.0.0")}, false, true},
{"no version reported falls back to the hash", models.FileUpdate{Component: models.ComponentTypeJaegerClickhouse,
OS: models.OSTypeLinux, Arch: models.ArchTypeAMD64, PackageName: "jaeger-clickhouse", Version: "0.13.0", FileHash: digest("a")},
installedArtefact{digest: ptr(digest("a"))}, false, true},
{"nothing installed to compare against", models.FileUpdate{Component: models.ComponentTypeInstaller, OS: models.OSTypeDarwin,
Arch: models.ArchTypeARM64, PackageName: "installer", Version: "2.1.0", FileHash: digest("z")},
installedArtefact{}, false, false},
{"an upgrade names the version to download and the hash to verify", models.FileUpdate{
Component: models.ComponentTypeJaegerClickhouse, OS: models.OSTypeLinux, Arch: models.ArchTypeAMD64,
Version: "0.13.0", FileHash: digest("plugin-0-13-0"), Action: models.ComponentActionUpgrade},
installedArtefact{digest: ptr(digest("plugin-0-12-0"))}, true, true},
{"current survives a version spelled differently", models.FileUpdate{Component: models.ComponentTypeJaegerClickhouse,
OS: models.OSTypeLinux, Arch: models.ArchTypeAMD64, Version: "v0.13.0", Action: models.ComponentActionCurrent},
installedArtefact{version: ptr("0.13.0")}, false, true},
{"a file never installed is an update", models.FileUpdate{Component: models.ComponentTypeInstaller, OS: models.OSTypeLinux,
Arch: models.ArchTypeAMD64, Action: models.ComponentActionInstall, PackageName: "installer", Version: "2.1.0",
FileHash: digest("b")}, installedArtefact{}, true, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := buildFileComponentUpdate(tt.offered, tt.installed)
if got.Outdated != tt.outdated || got.Verifiable != tt.verifiable {
t.Errorf("outdated=%t verifiable=%t, want %t and %t", got.Outdated, got.Verifiable, tt.outdated, tt.verifiable)
}
if got.TargetVersion != tt.offered.Version || got.TargetDigest != tt.offered.FileHash || got.Action != string(tt.offered.Action) {
t.Errorf("target version %q digest %q action %q, want the offered %q, %q, %q", got.TargetVersion, got.TargetDigest,
got.Action, tt.offered.Version, tt.offered.FileHash, tt.offered.Action)
}
})
}
}
func TestUpdates_UpdateStrategy_FallsBackToPreviewForAnythingUnknown(t *testing.T) {
tests := []struct {
name, configured string
want models.UpdateStrategy
}{
{"unset follows the channels already in use", "", models.UpdateStrategyPreview},
{"explicit stable", "stable", models.UpdateStrategyStable},
{"case is normalised", "NIGHTLY", models.UpdateStrategyNightly},
{"surrounding whitespace", " preview ", models.UpdateStrategyPreview},
{"a typo falls back rather than failing", "bleeding-edge", models.UpdateStrategyPreview},
}
for _, tt := range tests {
appState := &mockState{vars: map[string]loader.EnvVar{"UPDATE_STRATEGY": {Value: tt.configured}}}
if got := updateStrategy(appState); got != tt.want {
t.Errorf("%s: updateStrategy(%q) = %q, want %q", tt.name, tt.configured, got, tt.want)
}
}
}
+239
View File
@@ -0,0 +1,239 @@
// Package cloud is the installer's client for the PentAGI Cloud API: update checks and
// package downloads.
//
// It is a thin layer over the published SDK. Wire types come from the SDK's models package
// rather than being redeclared here, so a contract change is a compile error instead of a
// silent mismatch, and the whole package is free of installer state — it takes a Config,
// returns answers, and knows nothing about the wizard, the checker or the processor. Tests
// substitute the call functions directly; nothing here needs a server to exercise.
package cloud
import (
"fmt"
"net/http"
"net/url"
"strings"
"time"
"github.com/vxcontrol/cloud/sdk"
"github.com/vxcontrol/cloud/system"
)
// DefaultHost is the update server used when none is configured.
const DefaultHost = "update.pentagi.com"
// Route names and paths are part of the API contract: the server dispatches on the name,
// and a name it does not know is refused outright rather than reported as a missing page.
const (
routeUpdatesCheck = "updates_check"
routePackagesInfo = "packages_info"
routePackagesDownload = "packages_download"
pathUpdatesCheck = "/api/v1/proxy/updates/check"
pathPackagesInfo = "/api/v1/proxy/packages/info"
pathPackagesDownload = "/api/v1/proxy/packages/download"
)
const (
// clientName identifies the installer in the User-Agent, alongside its build version.
clientName = "PentAGI-Installer"
// powTimeout is the budget for the proof-of-work challenge each call has to solve.
// It is raised well above the SDK default because the SDK does not retry a timed-out
// challenge, and a laptop or a throttled VM can genuinely need the extra seconds.
powTimeout = 60 * time.Second
maxRetries = 3
)
// Config describes how to reach the update server. Every field is optional; the zero
// Config talks to DefaultHost anonymously, with no proxy.
type Config struct {
// Host is the update server, with or without a scheme (UPDATE_SERVER_HOST).
Host string
// ProxyURL is the installer's own proxy (PROXY_URL), used for every call. It takes
// precedence over the environment, which is what the user configured it for.
ProxyURL string
// LicenseKey is the PentAGI license key (LICENSE_KEY). An unusable key is dropped
// rather than sent, and reported through LicenseWarning.
LicenseKey string
// InstallerVersion is this build's version, as displayed. It is normalised for the
// request and sent verbatim in the User-Agent.
InstallerVersion string
// Logger receives the SDK's own diagnostics. Nil keeps them silent.
Logger sdk.Logger
}
// Client talks to the update server. Build one with New.
type Client struct {
checkUpdates sdk.CallReqBytesRespBytes
packageInfo sdk.CallReqQueryRespBytes
downloadPackage sdk.CallReqQueryRespWriter
host string
version string
licenseWarning error
}
// New builds a client for cfg.
//
// It fails only on configuration that cannot produce working calls — an unusable host or
// proxy. A license key that does not hold up is deliberately not fatal: the update check is
// the one thing that still works without a license, and refusing to run would leave the
// user with no way to learn that their key is the problem. The key is dropped and the
// reason is available from LicenseWarning.
func New(cfg Config) (*Client, error) {
host, err := NormalizeHost(cfg.Host)
if err != nil {
return nil, err
}
transport, err := newTransport(cfg.ProxyURL)
if err != nil {
return nil, err
}
client := &Client{
host: host,
version: NormalizeVersion(cfg.InstallerVersion),
}
userAgentVersion := strings.TrimSpace(cfg.InstallerVersion)
if userAgentVersion == "" {
userAgentVersion = UnknownVersion
}
options := []sdk.Option{
sdk.WithTransport(transport),
// The installation ID identifies this machine to the server across calls, and the
// contract requires it on every one of them.
sdk.WithInstallationID(system.GetInstallationID()),
sdk.WithClient(clientName, userAgentVersion),
sdk.WithPowTimeout(powTimeout),
sdk.WithMaxRetries(maxRetries),
}
if cfg.Logger != nil {
options = append(options, sdk.WithLogger(cfg.Logger))
}
// Validate before handing the key over: the SDK drops a key it cannot decode without
// saying so, and the call then runs anonymously — which looks, from the outside, like
// the license simply not being honoured.
if key := strings.TrimSpace(cfg.LicenseKey); key != "" {
if _, err := sdk.IntrospectLicenseKey(key); err != nil {
client.licenseWarning = fmt.Errorf("license key is not usable, continuing without it: %w", err)
} else {
options = append(options, sdk.WithLicenseKey(key))
}
}
configs := []sdk.CallConfig{
{
Calls: []any{&client.checkUpdates},
Host: host,
Name: routeUpdatesCheck,
Path: pathUpdatesCheck,
Method: sdk.CallMethodPOST,
},
{
Calls: []any{&client.packageInfo},
Host: host,
Name: routePackagesInfo,
Path: pathPackagesInfo,
Method: sdk.CallMethodGET,
},
{
Calls: []any{&client.downloadPackage},
Host: host,
Name: routePackagesDownload,
Path: pathPackagesDownload,
Method: sdk.CallMethodGET,
},
}
if err := sdk.Build(configs, options...); err != nil {
return nil, fmt.Errorf("failed to build update client: %w", err)
}
return client, nil
}
// Host reports the normalised update server this client talks to.
func (c *Client) Host() string { return c.host }
// InstallerVersion reports the version this client sends, after normalisation. It differs
// from the displayed build version whenever that one cannot be expressed as a version
// number.
func (c *Client) InstallerVersion() string { return c.version }
// LicenseWarning reports why the configured license key was not used, or nil when it was
// used or none was configured. Calls still work — anonymously.
func (c *Client) LicenseWarning() error { return c.licenseWarning }
// NormalizeHost reduces a configured update server address to the host[:port] form the
// client needs.
//
// The setting has historically held a full URL, so a scheme and a trailing path are
// tolerated and stripped. The transport is always TLS, so an explicit "http://" is an
// error rather than something to silently upgrade — a user who wrote it meant it, and
// quietly doing the opposite would hide a misconfiguration.
func NormalizeHost(raw string) (string, error) {
value := strings.TrimSpace(raw)
if value == "" {
return DefaultHost, nil
}
if scheme, rest, found := strings.Cut(value, "://"); found {
switch strings.ToLower(scheme) {
case "https":
value = rest
case "http":
return "", fmt.Errorf("update server %q uses http, but the connection is always encrypted: use https", raw)
default:
return "", fmt.Errorf("update server %q uses unsupported scheme %q", raw, scheme)
}
}
// Drop anything after the authority: a path, a query, a fragment.
value, _, _ = strings.Cut(value, "/")
value, _, _ = strings.Cut(value, "?")
value, _, _ = strings.Cut(value, "#")
value = strings.ToLower(strings.TrimSpace(value))
switch {
case value == "":
return "", fmt.Errorf("update server %q has no host", raw)
case strings.Contains(value, "@"):
return "", fmt.Errorf("update server %q carries credentials, which are not supported", raw)
case strings.ContainsAny(value, " \t"):
return "", fmt.Errorf("update server %q contains whitespace", raw)
}
return value, nil
}
// newTransport builds the transport every call uses.
//
// The SDK's default reads the proxy from the environment. The installer keeps its own
// proxy setting — often with credentials the environment does not carry — and that setting
// has to win. With none configured the environment behaviour is left as it is.
func newTransport(proxyURL string) (*http.Transport, error) {
transport := sdk.DefaultTransport()
value := strings.TrimSpace(proxyURL)
if value == "" {
return transport, nil
}
parsed, err := url.Parse(value)
if err != nil {
return nil, fmt.Errorf("proxy %q is not a valid URL: %w", proxyURL, err)
}
if parsed.Host == "" {
return nil, fmt.Errorf("proxy %q has no host", proxyURL)
}
transport.Proxy = http.ProxyURL(parsed)
return transport, nil
}
+172
View File
@@ -0,0 +1,172 @@
package cloud
import (
"context"
"io"
"net/http"
"strings"
"testing"
"github.com/vxcontrol/cloud/models"
)
// TestClient_UninitializedCallsFailCleanly: a failed New leaves a nil client; subtests are keyed by call.
func TestClient_UninitializedCallsFailCleanly(t *testing.T) {
var client *Client
ctx := context.Background()
calls := []struct {
name string
call func() error
}{
{"check updates reports it", func() error {
_, err := client.CheckUpdates(ctx, models.CheckUpdatesRequest{})
return err
}},
{"package info reports it", func() error {
_, err := client.PackageInfo(ctx, models.PackageInfoRequest{})
return err
}},
{"download package reports it", func() error {
return client.DownloadPackage(ctx, models.DownloadPackageRequest{}, models.PackageInfoResponse{}, io.Discard)
}},
}
for _, tt := range calls {
t.Run(tt.name, func(t *testing.T) {
if err := tt.call(); err == nil || !strings.Contains(err.Error(), "update client is not initialized") {
t.Errorf("error = %v, want the client reported uninitialized", err)
}
})
}
}
func TestClient_NormalizeHost_ReducesAnAddressToHostAndPort(t *testing.T) {
tests := []struct {
name string
raw string
want string
wantErr string
}{
{name: "empty falls back to the default server", raw: "", want: "update.pentagi.com"},
{name: "whitespace only falls back too", raw: " ", want: "update.pentagi.com"},
{name: "bare host passes through", raw: "update.pentagi.com", want: "update.pentagi.com"},
{name: "port is kept", raw: "update.pentagi.com:8443", want: "update.pentagi.com:8443"},
// The setting has always held a full URL, so this is what most installations carry.
{name: "https scheme is stripped", raw: "https://update.pentagi.com", want: "update.pentagi.com"},
{name: "trailing slash is stripped", raw: "https://update.pentagi.com/", want: "update.pentagi.com"},
{name: "path is stripped", raw: "https://update.pentagi.com/api/v1", want: "update.pentagi.com"},
{name: "query is stripped", raw: "https://update.pentagi.com?x=1", want: "update.pentagi.com"},
{name: "case is normalised", raw: "HTTPS://Update.PentAGI.com", want: "update.pentagi.com"},
{name: "http is refused rather than upgraded", raw: "http://update.pentagi.com", wantErr: "always encrypted"},
{name: "other schemes are refused", raw: "ftp://update.pentagi.com", wantErr: "unsupported scheme"},
{name: "credentials are refused", raw: "https://user:pass@update.pentagi.com", wantErr: "credentials"},
{name: "scheme with no host is refused", raw: "https:///api", wantErr: "no host"},
{name: "whitespace inside is refused", raw: "update pentagi.com", wantErr: "whitespace"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := NormalizeHost(tt.raw)
if tt.wantErr != "" {
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
t.Fatalf("NormalizeHost(%q) = %q, %v; want an error mentioning %q", tt.raw, got, err, tt.wantErr)
}
return
}
if err != nil || got != tt.want {
t.Errorf("NormalizeHost(%q) = %q, %v; want %q", tt.raw, got, err, tt.want)
}
})
}
}
// The installer's proxy often carries credentials the environment does not, so it has to win.
func TestClient_NewTransport_PrefersTheConfiguredProxyOverTheEnvironment(t *testing.T) {
tests := []struct {
name string
proxy string
wantHost string
wantUser string
wantErr string
}{
{name: "a configured proxy wins and keeps its credentials", proxy: "http://user:secret@proxy.internal:3128", wantHost: "proxy.internal:3128", wantUser: "user"},
{name: "without one the environment proxy is honoured", proxy: "", wantHost: "env-proxy.internal:8080"},
{name: "an unparsable proxy is refused", proxy: "://nope", wantErr: "not a valid URL"},
{name: "a proxy without a host is refused", proxy: "not a url at all", wantErr: "has no host"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Setenv("HTTPS_PROXY", "http://env-proxy.internal:8080")
transport, err := newTransport(tt.proxy)
if tt.wantErr != "" {
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
t.Fatalf("newTransport(%q) error = %v, want it to mention %q", tt.proxy, err, tt.wantErr)
}
return
}
if err != nil || transport.Proxy == nil {
t.Fatalf("newTransport(%q) = %v, %v; want a proxy resolver", tt.proxy, transport, err)
}
request, err := http.NewRequest(http.MethodGet, "https://update.pentagi.com/", nil)
if err != nil {
t.Fatalf("NewRequest: %v", err)
}
proxy, err := transport.Proxy(request)
if err != nil || proxy == nil || proxy.Host != tt.wantHost {
t.Fatalf("proxy = %v, %v; want host %q", proxy, err, tt.wantHost)
}
if tt.wantUser != "" && (proxy.User == nil || proxy.User.Username() != tt.wantUser) {
t.Errorf("proxy credentials were dropped: %v", proxy.User)
}
})
}
}
// An unusable license key is not fatal: the update check still works anonymously and says why.
func TestClient_New_BuildsAClientOrRefusesItsConfiguration(t *testing.T) {
tests := []struct {
name string
cfg Config
wantErr string
wantWarning string
wantVersion string
}{
{name: "a zero config talks to the default server anonymously", cfg: Config{}, wantVersion: "0.0.0"},
{name: "a development build is sent as the unknown version", cfg: Config{InstallerVersion: "develop-87ac00f"}, wantVersion: "0.0.0"},
{name: "an unusable license key is reported, not fatal", cfg: Config{LicenseKey: "NOT-A-REAL-LICENSE"}, wantWarning: "license key is not usable", wantVersion: "0.0.0"},
{name: "a plaintext update server is refused", cfg: Config{Host: "http://update.pentagi.com"}, wantErr: "always encrypted"},
{name: "an unusable proxy is refused", cfg: Config{ProxyURL: "://nope"}, wantErr: "not a valid URL"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
client, err := New(tt.cfg)
if tt.wantErr != "" {
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
t.Fatalf("New() error = %v, want it to mention %q", err, tt.wantErr)
}
return
}
if err != nil {
t.Fatalf("New() error = %v", err)
}
warning := client.LicenseWarning()
if (warning == nil) != (tt.wantWarning == "") || (warning != nil && !strings.Contains(warning.Error(), tt.wantWarning)) {
t.Errorf("LicenseWarning() = %v, want %q", warning, tt.wantWarning)
}
if client.checkUpdates == nil || client.packageInfo == nil || client.downloadPackage == nil {
t.Error("New() left a call unbuilt")
}
if client.Host() != "update.pentagi.com" || client.InstallerVersion() != tt.wantVersion {
t.Errorf("Host(), InstallerVersion() = %q, %q; want update.pentagi.com, %q", client.Host(), client.InstallerVersion(), tt.wantVersion)
}
})
}
}
+127
View File
@@ -0,0 +1,127 @@
package cloud
import (
"context"
"errors"
"time"
"github.com/vxcontrol/cloud/sdk"
)
// FailureReason classifies why a call to the update server did not produce an answer.
//
// The distinction matters to the user, not just to the log: "the server is unreachable"
// invites checking the network, "the daily quota is spent" invites coming back tomorrow,
// and "this request was refused" means retrying will never help. Collapsing all of them
// into one "update server unavailable" flag — as the installer used to — tells the user
// nothing they can act on.
type FailureReason string
const (
// FailureNone is the zero value: no failure.
FailureNone FailureReason = ""
// FailureUnreachable covers everything that never reached a verdict: no network, no
// DNS, a proxy that refused, a connection that died mid-flight.
FailureUnreachable FailureReason = "unreachable"
// FailureTimeout is a deadline: either the caller's, or the proof-of-work challenge
// taking longer than the budget on slow hardware.
FailureTimeout FailureReason = "timeout"
// FailureRateLimited means too many requests in a rolling window. RetryAfter says when
// the window reopens.
FailureRateLimited FailureReason = "rate_limited"
// FailureQuotaExceeded means the allowance for the period is spent. RetryAfter says
// when it resets.
FailureQuotaExceeded FailureReason = "quota_exceeded"
// FailureForbidden means this client is not allowed to make this call at all — a
// license tier without the endpoint, or a temporarily blocked client. Retrying does
// not help; the license does.
FailureForbidden FailureReason = "forbidden"
// FailureNotFound means the server has no such package or version. It is an answer,
// not an outage.
FailureNotFound FailureReason = "not_found"
// FailureRejected means the server refused the request as malformed. That is our bug,
// not the user's, and retrying an identical request cannot succeed.
FailureRejected FailureReason = "rejected"
// FailureServerError means the server failed on its side. Worth retrying later.
FailureServerError FailureReason = "server_error"
)
// Retryable reports whether waiting and trying again could plausibly succeed.
func (r FailureReason) Retryable() bool {
switch r {
case FailureUnreachable, FailureTimeout, FailureRateLimited,
FailureQuotaExceeded, FailureServerError:
return true
default:
return false
}
}
// Failure is a classified call error. It wraps the original, so errors.Is and errors.As
// against the SDK sentinels keep working on it.
type Failure struct {
Reason FailureReason
// RetryAfter is the server-advertised cooldown, zero when the server did not say.
RetryAfter time.Duration
Err error
}
func (f *Failure) Error() string { return f.Err.Error() }
func (f *Failure) Unwrap() error { return f.Err }
// Classify maps an SDK error onto a reason the interface can act on. It returns nil for a
// nil error, so it can wrap a call result directly.
//
// Ordering matters here: the typed errors are checked before the sentinels they wrap,
// because that is where the Retry-After cooldown lives.
func Classify(err error) *Failure {
if err == nil {
return nil
}
var quotaErr *sdk.QuotaError
if errors.As(err, &quotaErr) {
// A blocked scope is not an exhausted allowance — the tier never had access, so
// there is nothing to wait for.
if quotaErr.Scope == sdk.QuotaScopeBlocked {
return &Failure{Reason: FailureForbidden, Err: err}
}
return &Failure{Reason: FailureQuotaExceeded, RetryAfter: sdk.RetryAfterOf(err), Err: err}
}
var rateLimitErr *sdk.RateLimitError
if errors.As(err, &rateLimitErr) {
return &Failure{Reason: FailureRateLimited, RetryAfter: sdk.RetryAfterOf(err), Err: err}
}
switch {
case errors.Is(err, sdk.ErrForbidden), errors.Is(err, sdk.ErrBlocked):
return &Failure{Reason: FailureForbidden, Err: err}
case errors.Is(err, sdk.ErrNotFound):
return &Failure{Reason: FailureNotFound, Err: err}
// A rejected request means we built it wrong. The replay and signature errors land
// here too: both mean the server refused what we sent, and resending it is futile.
case errors.Is(err, sdk.ErrBadRequest),
errors.Is(err, sdk.ErrInvalidRequest),
errors.Is(err, sdk.ErrInvalidConfiguration),
errors.Is(err, sdk.ErrInvalidSignature),
errors.Is(err, sdk.ErrReplayAttack):
return &Failure{Reason: FailureRejected, Err: err}
case errors.Is(err, sdk.ErrServerInternal), errors.Is(err, sdk.ErrBadGateway):
return &Failure{Reason: FailureServerError, Err: err}
// The proof-of-work budget is not retried by the SDK, so a client on slow hardware
// has to be told what happened rather than shown a generic network error.
case errors.Is(err, context.DeadlineExceeded),
errors.Is(err, sdk.ErrExperimentTimeout),
errors.Is(err, sdk.ErrPoWFailed):
return &Failure{Reason: FailureTimeout, Err: err}
default:
return &Failure{Reason: FailureUnreachable, Err: err}
}
}
+102
View File
@@ -0,0 +1,102 @@
package cloud
import (
"context"
"errors"
"fmt"
"testing"
"time"
"github.com/vxcontrol/cloud/sdk"
)
func TestErrors_Classify_MapsSDKErrorsToActionableReasons(t *testing.T) {
tests := []struct {
name string
err error
wantReason FailureReason
wantRetryAfter time.Duration
}{
{name: "no error", err: nil},
{name: "forbidden", err: sdk.ErrForbidden, wantReason: FailureForbidden},
{name: "blocked client", err: sdk.ErrBlocked, wantReason: FailureForbidden},
{
// A tier without access has no reset to wait for, so it must not read as "try again later".
name: "quota blocked is a permission problem, not a wait",
err: &sdk.QuotaError{Err: sdk.ErrQuotaBlocked, Scope: sdk.QuotaScopeBlocked},
wantReason: FailureForbidden,
},
{
name: "daily quota carries its reset",
err: &sdk.QuotaError{
Err: sdk.ErrQuotaExceededDaily, Scope: sdk.QuotaScopeDaily, RetryAfter: 3 * time.Hour,
},
wantReason: FailureQuotaExceeded,
wantRetryAfter: 3 * time.Hour,
},
{
name: "rate limit carries its window",
err: &sdk.RateLimitError{
Err: sdk.ErrTooManyRequestsRPH, Scope: sdk.RateLimitScopeRPH, RetryAfter: 42 * time.Second,
},
wantReason: FailureRateLimited,
wantRetryAfter: 42 * time.Second,
},
{name: "not found is an answer", err: sdk.ErrNotFound, wantReason: FailureNotFound},
{name: "malformed request is ours to fix", err: sdk.ErrBadRequest, wantReason: FailureRejected},
{name: "server side failure", err: sdk.ErrServerInternal, wantReason: FailureServerError},
{name: "bad gateway", err: sdk.ErrBadGateway, wantReason: FailureServerError},
// The SDK does not retry a timed-out challenge, so this is a budget, not a broken network.
{name: "proof of work budget", err: sdk.ErrExperimentTimeout, wantReason: FailureTimeout},
{name: "caller deadline", err: context.DeadlineExceeded, wantReason: FailureTimeout},
{name: "anything else is a reachability problem", err: errors.New("dial tcp: no route to host"), wantReason: FailureUnreachable},
{name: "wrapped errors are still classified", err: fmt.Errorf("update check failed: %w", sdk.ErrForbidden), wantReason: FailureForbidden},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
failure := Classify(tt.err)
if tt.err == nil {
if failure != nil {
t.Fatalf("Classify(nil) = %v, want nil", failure)
}
return
}
if failure == nil {
t.Fatalf("Classify(%v) = nil, want reason %q", tt.err, tt.wantReason)
}
if failure.Reason != tt.wantReason {
t.Errorf("reason = %q, want %q", failure.Reason, tt.wantReason)
}
if failure.RetryAfter != tt.wantRetryAfter {
t.Errorf("retry after = %v, want %v", failure.RetryAfter, tt.wantRetryAfter)
}
if !errors.Is(failure, tt.err) {
t.Errorf("the original error is no longer reachable through the classification")
}
})
}
}
// Waiting out a forbidden endpoint wastes the user's time; hiding a quota reset wastes the license.
func TestErrors_Retryable_MatchesWhatWaitingCanFix(t *testing.T) {
retryable := map[FailureReason]bool{
FailureUnreachable: true,
FailureTimeout: true,
FailureRateLimited: true,
FailureQuotaExceeded: true,
FailureServerError: true,
FailureForbidden: false,
FailureNotFound: false,
FailureRejected: false,
FailureNone: false,
}
for reason, want := range retryable {
if got := reason.Retryable(); got != want {
t.Errorf("%q.Retryable() = %t, want %t", reason, got, want)
}
}
}
+114
View File
@@ -0,0 +1,114 @@
package cloud
import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"strings"
"github.com/vxcontrol/cloud/models"
)
// PackageInfo asks the update server about one downloadable package: its size, its
// sha256 and the signature over it.
//
// The answer is validated before it is returned, because everything DownloadPackage checks
// is taken from it — an unverified description of a file is not a basis for trusting the
// file.
func (c *Client) PackageInfo(
ctx context.Context,
req models.PackageInfoRequest,
) (*models.PackageInfoResponse, error) {
if c == nil || c.packageInfo == nil {
return nil, fmt.Errorf("update client is not initialized")
}
if err := req.Valid(); err != nil {
return nil, fmt.Errorf("package info request is malformed: %w", err)
}
answer, err := c.packageInfo(ctx, req.Query())
if err != nil {
return nil, Classify(err)
}
response, err := models.ParseEnvelope[models.PackageInfoResponse](answer)
if err != nil {
return nil, fmt.Errorf("failed to read package info answer: %w", err)
}
if err := response.Valid(); err != nil {
return nil, fmt.Errorf("package info answer is malformed: %w", err)
}
return &response, nil
}
// DownloadPackage streams a package into dst, verifying it against info as the bytes
// arrive.
//
// Three things are checked, and all three describe the file itself: the transport
// encryption is transparent and changes none of them. The length must match info.Size —
// the encrypted response carries no Content-Length, so this is the only length the caller
// ever learns. The sha256 must match info.Hash. The Ed25519 signature must verify against
// the file's SHA-512 digest, which is what makes the package ours rather than merely
// intact.
//
// Verification can only complete once the last byte has been written, so on any error dst
// holds a partial or unverified file. It is the caller's job to discard it — write to a
// file that is only put in place after this returns nil.
func (c *Client) DownloadPackage(
ctx context.Context,
req models.DownloadPackageRequest,
info models.PackageInfoResponse,
dst io.Writer,
) error {
if c == nil || c.downloadPackage == nil {
return fmt.Errorf("update client is not initialized")
}
if err := req.Valid(); err != nil {
return fmt.Errorf("package download request is malformed: %w", err)
}
if err := info.Valid(); err != nil {
return fmt.Errorf("package description is malformed: %w", err)
}
digest := sha256.New()
counter := &countingWriter{}
// The signature wrapper hashes with SHA-512 on the way through; the tee adds the
// sha256 and the byte count, so a single pass over the stream feeds all three checks.
signed := info.Signature.ValidateWrapWriter(io.MultiWriter(dst, digest, counter))
if err := c.downloadPackage(ctx, req.Query(), signed); err != nil {
return Classify(err)
}
if counter.written != info.Size {
return fmt.Errorf("package is %d bytes, expected %d", counter.written, info.Size)
}
actual := hex.EncodeToString(digest.Sum(nil))
if !strings.EqualFold(actual, info.Hash) {
return fmt.Errorf("package sha256 is %s, expected %s", actual, info.Hash)
}
if err := signed.Valid(); err != nil {
return fmt.Errorf("package signature does not verify: %w", err)
}
return nil
}
// countingWriter counts the bytes passing through it and discards them; the real
// destination sits alongside it in the MultiWriter.
type countingWriter struct {
written int64
}
func (w *countingWriter) Write(p []byte) (int, error) {
w.written += int64(len(p))
return len(p), nil
}
@@ -0,0 +1,168 @@
package cloud
import (
"bytes"
"context"
"crypto/ed25519"
"crypto/sha256"
"crypto/sha512"
"encoding/hex"
"encoding/json"
"io"
"strings"
"testing"
"github.com/vxcontrol/cloud/models"
)
// packagesValidInfo is a well-formed package description, so a refusal is not caused by it.
func packagesValidInfo() models.PackageInfoResponse {
return models.PackageInfoResponse{
Size: 1024,
Hash: strings.Repeat("a", 64),
Version: "2.0.0",
OS: models.OSTypeLinux,
Arch: models.ArchTypeAMD64,
Signature: models.SignatureValue(strings.Repeat("Q", 86)),
}
}
// packagesSigned describes payload with a real sha256 and an Ed25519 signature over its SHA-512 digest.
func packagesSigned(t *testing.T, payload []byte) (models.PackageInfoResponse, models.DownloadPackageRequest) {
t.Helper()
_, private, err := ed25519.GenerateKey(nil)
if err != nil {
t.Fatalf("generate key: %v", err)
}
sha512Digest := sha512.Sum512(payload)
sha256Digest := sha256.Sum256(payload)
var signature models.SignatureValue
if _, err := signature.FromBytes(ed25519.Sign(private, sha512Digest[:])); err != nil {
t.Fatalf("encode signature: %v", err)
}
info := packagesValidInfo()
info.Size = int64(len(payload))
info.Hash = hex.EncodeToString(sha256Digest[:])
info.Signature = signature
request := models.DownloadPackageRequest{
Component: models.ComponentTypeInstaller,
Version: "2.0.0",
OS: models.OSTypeLinux,
Arch: models.ArchTypeAMD64,
}
return info, request
}
func TestPackages_PackageInfo_UnwrapsTheEnvelopeAndValidates(t *testing.T) {
malformed := packagesValidInfo()
malformed.Hash = "not-a-sha256"
tests := []struct {
name string
answer models.PackageInfoResponse
wantErr string
}{
{name: "a valid answer is unwrapped", answer: packagesValidInfo()},
{name: "an answer that fails validation is refused", answer: malformed, wantErr: "package info answer is malformed"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
enveloped, err := json.Marshal(map[string]any{"status": "success", "data": tt.answer})
if err != nil {
t.Fatalf("marshal: %v", err)
}
client := &Client{packageInfo: func(ctx context.Context, query map[string]string) ([]byte, error) {
if query["component"] != "installer" || query["version"] != "2.0.0" {
t.Errorf("query = %v, want component installer and version 2.0.0", query)
}
return enveloped, nil
}}
info, err := client.PackageInfo(context.Background(), models.PackageInfoRequest{
Component: models.ComponentTypeInstaller,
Version: "2.0.0",
OS: models.OSTypeLinux,
Arch: models.ArchTypeAMD64,
})
if tt.wantErr != "" {
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
t.Fatalf("PackageInfo() = %+v, %v; want an error mentioning %q", info, err, tt.wantErr)
}
return
}
if err != nil {
t.Fatalf("PackageInfo: %v", err)
}
if info.Size != 1024 {
t.Errorf("size = %d, want 1024 - the envelope was not unwrapped", info.Size)
}
})
}
}
func TestPackages_DownloadPackage_VerifiesWhatItStreams(t *testing.T) {
payload := []byte(strings.Repeat("installer bytes ", 512))
info, request := packagesSigned(t, payload)
tests := []struct {
name string
served []byte
wantHint string
}{
{name: "a truncated package fails the size check", served: payload[:len(payload)-16], wantHint: "bytes, expected"},
{name: "a padded package fails the size check", served: append(append([]byte{}, payload...), 'x'), wantHint: "bytes, expected"},
{name: "same length with other content fails the sha256 check", served: append(append([]byte{}, payload[:len(payload)-1]...), 'X'), wantHint: "sha256"},
// The throwaway key is not the release key, so an intact package gets as far as the signature.
{name: "an intact package reaches the signature check", served: payload, wantHint: "signature"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
client := &Client{downloadPackage: func(ctx context.Context, query map[string]string, w io.Writer) error {
if query["component"] != "installer" {
t.Errorf("component = %q, want installer", query["component"])
}
_, err := w.Write(tt.served)
return err
}}
var sink bytes.Buffer
err := client.DownloadPackage(context.Background(), request, info, &sink)
if err == nil || !strings.Contains(err.Error(), tt.wantHint) {
t.Fatalf("DownloadPackage() error = %v, want it to mention %q", err, tt.wantHint)
}
// Whatever the verdict the destination has the bytes, which is why it stays unverified until nil.
if !bytes.Equal(sink.Bytes(), tt.served) {
t.Errorf("the destination received %d bytes, want %d", sink.Len(), len(tt.served))
}
})
}
}
func TestPackages_DownloadPackage_RefusesAMalformedRequestBeforeSending(t *testing.T) {
called := false
client := &Client{downloadPackage: func(ctx context.Context, query map[string]string, w io.Writer) error {
called = true
return nil
}}
// neo4j has no package under any circumstances; pentagi would be valid, it ships an executable.
request := models.DownloadPackageRequest{
Component: models.ComponentTypeNeo4j,
Version: "2.0.0",
OS: models.OSTypeLinux,
Arch: models.ArchTypeAMD64,
}
err := client.DownloadPackage(context.Background(), request, packagesValidInfo(), io.Discard)
if err == nil || !strings.Contains(err.Error(), "package download request is malformed") {
t.Fatalf("DownloadPackage() error = %v, want the request refused as malformed", err)
}
if called {
t.Error("the malformed request was sent anyway")
}
}
+52
View File
@@ -0,0 +1,52 @@
package cloud
import (
"context"
"encoding/json"
"fmt"
"github.com/vxcontrol/cloud/models"
)
// CheckUpdates asks the update server what is available for the components described in
// req, and returns the answer per product stack.
//
// The request is validated before it leaves: a malformed one is refused by the server as an
// internal error, which is indistinguishable from an outage and equally pointless to retry.
// Catching it here names the offending field instead.
//
// The component list must describe the whole installation, not just the parts that look
// suspicious: the server answers only about what it was told, so anything left out comes
// back as "nothing to report" rather than "not asked".
func (c *Client) CheckUpdates(
ctx context.Context,
req models.CheckUpdatesRequest,
) (*models.CheckUpdatesResponse, error) {
if c == nil || c.checkUpdates == nil {
return nil, fmt.Errorf("update client is not initialized")
}
if err := req.Valid(); err != nil {
return nil, fmt.Errorf("update check request is malformed: %w", err)
}
body, err := json.Marshal(req)
if err != nil {
return nil, fmt.Errorf("failed to encode update check request: %w", err)
}
answer, err := c.checkUpdates(ctx, body)
if err != nil {
return nil, Classify(err)
}
// Answers are wrapped in a status envelope. Decoding straight into the response type
// succeeds against the wrapper too — every field simply stays at its zero value — so
// the unwrapping is not optional: skipping it reports "no updates" for every answer.
response, err := models.ParseEnvelope[models.CheckUpdatesResponse](answer)
if err != nil {
return nil, fmt.Errorf("failed to read update check answer: %w", err)
}
return &response, nil
}
+102
View File
@@ -0,0 +1,102 @@
package cloud
import (
"context"
"encoding/json"
"errors"
"fmt"
"reflect"
"strings"
"testing"
"github.com/vxcontrol/cloud/models"
"github.com/vxcontrol/cloud/sdk"
)
// updatesValidRequest is the smallest request the contract accepts, so a rejection is for the reason under test.
func updatesValidRequest() models.CheckUpdatesRequest {
return models.CheckUpdatesRequest{
InstallerVersion: "2.0.0",
InstallerOS: models.OSTypeLinux,
InstallerArch: models.ArchTypeAMD64,
Strategy: models.UpdateStrategyStable,
Images: []models.ImageComponentInfo{{
Component: models.ComponentTypePentagi,
Status: models.ComponentStatusRunning,
OS: models.OSTypeLinux,
Arch: models.ArchTypeAMD64,
Repository: "vxcontrol/pentagi",
Tag: "latest",
}},
}
}
// Decoding the envelope straight into the response type succeeds with every field zero: "no updates", silently.
func TestUpdates_CheckUpdates_SendsTheRequestAndUnwrapsTheAnswer(t *testing.T) {
latest := "2.1.0"
enveloped, err := json.Marshal(map[string]any{"status": "success", "data": models.CheckUpdatesResponse{
Updates: []models.UpdateInfo{{Stack: models.ProductStackPentagi, HasUpdate: true, LatestVersion: &latest}},
}})
if err != nil {
t.Fatalf("marshal: %v", err)
}
var sent models.CheckUpdatesRequest
client := &Client{checkUpdates: func(ctx context.Context, body []byte) ([]byte, error) {
if err := json.Unmarshal(body, &sent); err != nil {
return nil, err
}
return enveloped, nil
}}
request := updatesValidRequest()
response, err := client.CheckUpdates(context.Background(), request)
if err != nil {
t.Fatalf("CheckUpdates: %v", err)
}
if !reflect.DeepEqual(sent, request) {
t.Errorf("sent %+v, want the caller's request unaltered %+v", sent, request)
}
if len(response.Updates) != 1 || !response.Updates[0].HasUpdate || *response.Updates[0].LatestVersion != "2.1.0" {
t.Errorf("updates = %+v, want the one enveloped stack with 2.1.0 available", response.Updates)
}
}
func TestUpdates_CheckUpdates_RefusesAMalformedRequestBeforeSending(t *testing.T) {
called := false
client := &Client{checkUpdates: func(ctx context.Context, body []byte) ([]byte, error) {
called = true
return nil, nil
}}
request := updatesValidRequest()
request.Strategy = models.UpdateStrategy("bleeding-edge")
_, err := client.CheckUpdates(context.Background(), request)
if err == nil || !strings.Contains(err.Error(), "update check request is malformed") {
t.Fatalf("CheckUpdates() error = %v, want the request refused as malformed", err)
}
if called {
t.Error("the malformed request was sent anyway")
}
}
func TestUpdates_CheckUpdates_ClassifiesCallFailures(t *testing.T) {
client := &Client{checkUpdates: func(ctx context.Context, body []byte) ([]byte, error) {
return nil, fmt.Errorf("call refused: %w", sdk.ErrForbidden)
}}
_, err := client.CheckUpdates(context.Background(), updatesValidRequest())
var failure *Failure
if !errors.As(err, &failure) {
t.Fatalf("error is not classified: %v", err)
}
if failure.Reason != FailureForbidden {
t.Errorf("reason = %q, want %q", failure.Reason, FailureForbidden)
}
if err.Error() != "call refused: forbidden" {
t.Errorf("message = %q, want the call's own %q", err.Error(), "call refused: forbidden")
}
}
+48
View File
@@ -0,0 +1,48 @@
package cloud
import (
"strings"
"github.com/vxcontrol/cloud/models"
)
// UnknownVersion is what a build reports when its own version cannot be expressed as a
// version number — the conventional stand-in for "some build, older than anything we
// publish". Development builds are named after their branch, not a release, so this is the
// normal case outside CI.
const UnknownVersion = "0.0.0"
// latestVersion is accepted by the update server as "the newest published version" when
// asking about a package. It is meaningless as a description of the installer you are
// running, so it is never sent as one.
const latestVersion = "latest"
// NormalizeVersion converts a build version into one the update server accepts.
//
// A leading "v" is dropped, since it is a display convention rather than part of the
// number. Anything that still does not parse as a version — a branch name such as
// "develop", a bare commit hash, an empty string — becomes UnknownVersion. The original
// value is not lost: it travels in the User-Agent, where it identifies the exact build
// without having to satisfy the version grammar.
//
// The check is delegated to the shared validator rather than re-implemented here, so the
// client and the server can never disagree about what a valid version looks like.
func NormalizeVersion(raw string) string {
value := strings.TrimSpace(raw)
value = strings.TrimPrefix(value, "v")
if value == "" || value == latestVersion {
return UnknownVersion
}
if err := validateSemver(value); err != nil {
return UnknownVersion
}
return value
}
// validateSemver reports whether the update server would accept value as a version.
func validateSemver(value string) error {
return models.GetValidator().Var(value, "semver")
}
@@ -0,0 +1,54 @@
package cloud
import (
"testing"
"github.com/vxcontrol/cloud/models"
)
func TestVersion_NormalizeVersion_SendsOnlyWhatTheContractAccepts(t *testing.T) {
tests := []struct {
name string
raw string
want string
}{
// A revision suffix identifies a branch build; dropping it would pass it off as the release.
{name: "release version", raw: "2.0.0", want: "2.0.0"},
{name: "branch build with revision", raw: "2.0.0-87ac00f", want: "2.0.0-87ac00f"},
{name: "leading v is a display convention", raw: "v2.0.0", want: "2.0.0"},
{name: "surrounding whitespace", raw: " 2.0.0 ", want: "2.0.0"},
{name: "two-part version", raw: "2.0", want: "2.0"},
{name: "build metadata", raw: "2.0.0+build.5", want: "2.0.0+build.5"},
// Everything a build with no release behind it can be named; sending any of
// them gets the request refused.
{name: "edition build naming its base version", raw: "2.0.0-ce.h87ac00f", want: "2.0.0-ce.h87ac00f"},
{name: "enterprise edition build", raw: "2.0.0-ee.h87ac00f", want: "2.0.0-ee.h87ac00f"},
{name: "edition release", raw: "2.0.0-ce", want: "2.0.0-ce"},
{name: "edition alone is not a version", raw: "ce", want: "0.0.0"},
{name: "edition and revision without a release", raw: "ce.h87ac00f", want: "0.0.0"},
{name: "empty", raw: "", want: "0.0.0"},
{name: "whitespace only", raw: " ", want: "0.0.0"},
{name: "bare commit hash", raw: "87ac00f", want: "0.0.0"},
{name: "branch path", raw: "feature/some-branch", want: "0.0.0"},
{name: "four-part version", raw: "2.0.0.1", want: "0.0.0"},
{name: "five-part version", raw: "1.2.3.4.5", want: "0.0.0"},
{name: "word with an underscore", raw: "release_candidate", want: "0.0.0"},
{name: "bare v", raw: "v", want: "0.0.0"},
{name: "dots only", raw: "..", want: "0.0.0"},
// "latest" is valid to ask a package endpoint for, and meaningless as the running installer.
{name: "latest is never an installer version", raw: "latest", want: "0.0.0"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := NormalizeVersion(tt.raw)
if got != tt.want {
t.Errorf("NormalizeVersion(%q) = %q, want %q", tt.raw, got, tt.want)
}
if err := models.GetValidator().Var(got, "semver"); err != nil {
t.Errorf("NormalizeVersion(%q) = %q, which the contract rejects: %v", tt.raw, got, err)
}
})
}
}
+203 -546
View File
@@ -1,6 +1,7 @@
package files
import (
"errors"
"os"
"path/filepath"
"runtime"
@@ -8,602 +9,258 @@ import (
"testing"
)
// newTestFiles creates a Files instance for testing with a custom links directory
func newTestFiles(linksDir string) Files {
return &files{
linksDir: linksDir,
// filesLinksFixture returns a Files reading from a fresh links directory that holds
// test.txt, an executable run.sh and testdir/nested.txt.
func filesLinksFixture(t *testing.T) Files {
t.Helper()
links := filepath.Join(t.TempDir(), "links")
filesWrite(t, filepath.Join(links, "test.txt"), "test content", 0o644)
filesWrite(t, filepath.Join(links, "run.sh"), "#!/bin/sh\necho hi\n", 0o755)
filesWrite(t, filepath.Join(links, "testdir", "nested.txt"), "nested content", 0o644)
return &files{linksDir: links}
}
// filesWrite creates path with an exact mode: WriteFile alone is subject to the umask.
func filesWrite(t *testing.T, path, content string, mode os.FileMode) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatalf("MkdirAll: %v", err)
}
if err := os.WriteFile(path, []byte(content), mode); err != nil {
t.Fatalf("WriteFile: %v", err)
}
if err := os.Chmod(path, mode); err != nil {
t.Fatalf("Chmod: %v", err)
}
}
func TestNewFiles(t *testing.T) {
f := NewFiles()
if f == nil {
t.Fatal("NewFiles() returned nil")
}
}
func TestGetContent_FromFS(t *testing.T) {
// Create temporary test directory structure
tmpDir := t.TempDir()
defer os.RemoveAll(tmpDir)
testLinksDir := filepath.Join(tmpDir, "links")
setupTestLinksInDir(t, testLinksDir)
f := newTestFiles(testLinksDir)
content, err := f.GetContent("test.txt")
// filesEmbedded reads the generated source of an embedded file, independently of the provider.
func filesEmbedded(t *testing.T, name string) []byte {
t.Helper()
content, err := os.ReadFile(filepath.Join("fs", name))
if err != nil {
t.Fatalf("GetContent() error = %v", err)
t.Fatalf("read generated fs/%s: %v", name, err)
}
return content
}
expected := "test content"
if string(content) != expected {
t.Errorf("GetContent() = %q, want %q", string(content), expected)
func filesRequireEmbedded(t *testing.T) {
t.Helper()
if embeddedProvider == nil {
t.Skip("embedded provider not generated: run go generate ./cmd/installer/files/")
}
}
func TestExistsInFS(t *testing.T) {
tmpDir := t.TempDir()
defer os.RemoveAll(tmpDir)
// filesWithoutEmbeddedProvider makes the rest of the test run as a build without go generate.
func filesWithoutEmbeddedProvider(t *testing.T) {
saved := embeddedProvider
embeddedProvider = nil
t.Cleanup(func() { embeddedProvider = saved })
}
testLinksDir := filepath.Join(tmpDir, "links")
setupTestLinksInDir(t, testLinksDir)
f := newTestFiles(testLinksDir)
func TestFiles_GetContent_ReadsTheEmbeddedFileThenTheLinksDirectory(t *testing.T) {
t.Run("an embedded file comes from the provider", func(t *testing.T) {
filesRequireEmbedded(t)
content, err := NewFiles().GetContent("docker-compose.yml")
if err != nil || string(content) != string(filesEmbedded(t, "docker-compose.yml")) {
t.Errorf("GetContent(docker-compose.yml) = %d bytes, %v; want the generated file", len(content), err)
}
})
t.Run("a file only in the links directory falls back to it", func(t *testing.T) {
content, err := filesLinksFixture(t).GetContent("test.txt")
if err != nil || string(content) != "test content" {
t.Errorf("GetContent(test.txt) = %q, %v; want %q", content, err, "test content")
}
})
}
func TestFiles_ExistsInFS_ReportsWhatTheLinksDirectoryHolds(t *testing.T) {
f := filesLinksFixture(t)
if !f.ExistsInFS("test.txt") {
t.Error("ExistsInFS() = false, want true for existing file")
t.Error("ExistsInFS(test.txt) = false, want true")
}
if f.ExistsInFS("nonexistent.txt") {
t.Error("ExistsInFS() = true, want false for non-existent file")
t.Error("ExistsInFS(nonexistent.txt) = true, want false")
}
}
func TestStat_FromFS(t *testing.T) {
tmpDir := t.TempDir()
defer os.RemoveAll(tmpDir)
testLinksDir := filepath.Join(tmpDir, "links")
setupTestLinksInDir(t, testLinksDir)
f := newTestFiles(testLinksDir)
info, err := f.Stat("test.txt")
func TestFiles_Stat_FallsBackToTheLinksDirectory(t *testing.T) {
info, err := filesLinksFixture(t).Stat("test.txt")
if err != nil {
t.Fatalf("Stat() error = %v", err)
}
if info.IsDir() {
t.Error("Stat() IsDir() = true, want false for file")
}
if info.Size() == 0 {
t.Error("Stat() Size() = 0, want > 0")
if info.IsDir() || info.Size() != 12 {
t.Errorf("Stat() = dir %v, size %d; want a file of 12 bytes", info.IsDir(), info.Size())
}
}
func TestCopy_File(t *testing.T) {
tmpDir := t.TempDir()
defer os.RemoveAll(tmpDir)
testLinksDir := filepath.Join(tmpDir, "links")
setupTestLinksInDir(t, testLinksDir)
copyDstDir := t.TempDir()
defer os.RemoveAll(copyDstDir)
f := newTestFiles(testLinksDir)
err := f.Copy("test.txt", copyDstDir, false)
if err != nil {
t.Fatalf("Copy() error = %v", err)
func TestFiles_Copy_WritesTheSourceUnderTheDestination(t *testing.T) {
tests := []struct {
name string
embedded bool
src string
existing string // content already at the destination
rewrite bool
path string // file checked under the destination
content string
mode os.FileMode
wantErr error
}{
{name: "a linked file keeps its content and mode", src: "run.sh", path: "run.sh", content: "#!/bin/sh\necho hi\n", mode: 0o755},
{name: "a linked directory is copied recursively", src: "testdir", path: "testdir/nested.txt", content: "nested content"},
{name: "an existing file is kept without rewrite", src: "test.txt", existing: "existing", path: "test.txt", content: "existing", wantErr: os.ErrExist},
{name: "an existing file is replaced with rewrite", src: "test.txt", existing: "existing", rewrite: true, path: "test.txt", content: "test content"},
{name: "an embedded file is copied byte for byte", embedded: true, src: "docker-compose.yml", path: "docker-compose.yml"},
}
// Verify file was copied
copiedPath := filepath.Join(copyDstDir, "test.txt")
content, err := os.ReadFile(copiedPath)
if err != nil {
t.Fatalf("Failed to read copied file: %v", err)
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
f, want := filesLinksFixture(t), tt.content
if tt.embedded {
filesRequireEmbedded(t)
f, want = NewFiles(), string(filesEmbedded(t, tt.src))
}
dst := t.TempDir()
if tt.existing != "" {
filesWrite(t, filepath.Join(dst, tt.src), tt.existing, 0o644)
}
expected := "test content"
if string(content) != expected {
t.Errorf("Copied file content = %q, want %q", string(content), expected)
if err := f.Copy(tt.src, dst, tt.rewrite); !errors.Is(err, tt.wantErr) {
t.Fatalf("Copy() error = %v, want %v", err, tt.wantErr)
}
target := filepath.Join(dst, filepath.FromSlash(tt.path))
got, err := os.ReadFile(target)
if err != nil {
t.Fatalf("read copied file: %v", err)
}
if string(got) != want {
t.Errorf("copied content = %q, want %q", got, want)
}
if tt.mode != 0 && runtime.GOOS != "windows" {
info, err := os.Stat(target)
if err != nil {
t.Fatalf("stat copied file: %v", err)
}
if info.Mode().Perm() != tt.mode {
t.Errorf("copied mode = %v, want %v", info.Mode().Perm(), tt.mode)
}
}
})
}
}
func TestCopy_PreservesExecutable_FromFS(t *testing.T) {
tmpDir := t.TempDir()
defer os.RemoveAll(tmpDir)
testLinksDir := filepath.Join(tmpDir, "links")
if err := os.MkdirAll(testLinksDir, 0755); err != nil {
t.Fatalf("failed to create links dir: %v", err)
}
// create source file with specific permissions
src := filepath.Join(testLinksDir, "run.sh")
if err := os.WriteFile(src, []byte("#!/bin/sh\necho hi\n"), 0755); err != nil {
t.Fatalf("failed to create exec file: %v", err)
}
// get actual source mode (may differ on Windows)
srcInfo, err := os.Stat(src)
if err != nil {
t.Fatalf("failed to stat source: %v", err)
}
expectedMode := srcInfo.Mode().Perm()
copyDstDir := t.TempDir()
defer os.RemoveAll(copyDstDir)
f := newTestFiles(testLinksDir)
if err := f.Copy("run.sh", copyDstDir, false); err != nil {
t.Fatalf("Copy() error = %v", err)
}
// verify permissions preserved (whatever they actually are on this OS)
copied := filepath.Join(copyDstDir, "run.sh")
info, err := os.Stat(copied)
if err != nil {
t.Fatalf("failed to stat copied: %v", err)
}
if info.Mode().Perm() != expectedMode {
t.Errorf("copied mode = %o, want %o (source permissions not preserved)", info.Mode().Perm(), expectedMode)
}
}
func TestCheck_DetectsPermissionMismatch_FromFS(t *testing.T) {
tmpDir := t.TempDir()
defer os.RemoveAll(tmpDir)
testLinksDir := filepath.Join(tmpDir, "links")
if err := os.MkdirAll(testLinksDir, 0755); err != nil {
t.Fatalf("failed to create links dir: %v", err)
}
// create source file
src := filepath.Join(testLinksDir, "tool.sh")
if err := os.WriteFile(src, []byte("#!/bin/sh\necho tool\n"), 0755); err != nil {
t.Fatalf("failed to create exec file: %v", err)
}
// get actual source mode
srcInfo, err := os.Stat(src)
if err != nil {
t.Fatalf("failed to stat source: %v", err)
}
f := newTestFiles(testLinksDir)
workingDir := t.TempDir()
defer os.RemoveAll(workingDir)
if err := f.Copy("tool.sh", workingDir, false); err != nil {
t.Fatalf("Copy() error = %v", err)
}
target := filepath.Join(workingDir, "tool.sh")
// try to change permissions
newMode := os.FileMode(0644)
func TestFiles_Check_ComparesTheWorkingCopyWithTheSource(t *testing.T) {
permMismatch := FileStatusModified
if runtime.GOOS == "windows" {
// on Windows, we can only toggle read-only bit
newMode = 0444 // read-only
permMismatch = FileStatusOK // Windows has no permission bits to compare
}
if err := os.Chmod(target, newMode); err != nil {
t.Fatalf("failed to chmod: %v", err)
}
// verify permissions actually changed
targetInfo, err := os.Stat(target)
if err != nil {
t.Fatalf("failed to stat target: %v", err)
}
if targetInfo.Mode().Perm() == srcInfo.Mode().Perm() {
// permissions didn't change on this OS, skip the rest
t.Skipf("cannot change file permissions on this OS (from %o to %o, got %o)",
srcInfo.Mode().Perm(), newMode, targetInfo.Mode().Perm())
}
status := f.Check("tool.sh", workingDir)
// on Windows, Check() doesn't compare permissions (by design)
// so even if permissions changed, status will be OK
if runtime.GOOS == "windows" {
if status != FileStatusOK {
t.Errorf("Check() on Windows = %v, want %v (permissions not checked on Windows)", status, FileStatusOK)
}
} else {
// on Unix, permissions should be checked
if status != FileStatusModified {
t.Errorf("Check() perms mismatch = %v, want %v", status, FileStatusModified)
copyOf := func(name string) func(*testing.T, Files, string) {
return func(t *testing.T, f Files, work string) {
if err := f.Copy(name, work, false); err != nil {
t.Fatalf("Copy(%q) error = %v", name, err)
}
}
}
}
func TestCopy_Directory(t *testing.T) {
tmpDir := t.TempDir()
defer os.RemoveAll(tmpDir)
testLinksDir := filepath.Join(tmpDir, "links")
setupTestLinksWithDirInDir(t, testLinksDir)
copyDstDir := t.TempDir()
defer os.RemoveAll(copyDstDir)
f := newTestFiles(testLinksDir)
err := f.Copy("testdir", copyDstDir, false)
if err != nil {
t.Fatalf("Copy() error = %v", err)
write := func(name, content string) func(*testing.T, Files, string) {
return func(t *testing.T, _ Files, work string) {
filesWrite(t, filepath.Join(work, name), content, 0o644)
}
}
// Verify directory structure was copied
copiedFile := filepath.Join(copyDstDir, "testdir", "nested.txt")
content, err := os.ReadFile(copiedFile)
if err != nil {
t.Fatalf("Failed to read copied nested file: %v", err)
}
expected := "nested content"
if string(content) != expected {
t.Errorf("Copied nested file content = %q, want %q", string(content), expected)
}
}
func TestCopy_WithoutRewrite(t *testing.T) {
tmpDir := t.TempDir()
defer os.RemoveAll(tmpDir)
testLinksDir := filepath.Join(tmpDir, "links")
setupTestLinksInDir(t, testLinksDir)
copyDstDir := t.TempDir()
defer os.RemoveAll(copyDstDir)
f := newTestFiles(testLinksDir)
// Create existing file
existingPath := filepath.Join(copyDstDir, "test.txt")
err := os.WriteFile(existingPath, []byte("existing"), 0644)
if err != nil {
t.Fatalf("Failed to create existing file: %v", err)
}
// Try to copy without rewrite
err = f.Copy("test.txt", copyDstDir, false)
if err == nil {
t.Error("Copy() without rewrite should fail for existing file")
}
}
func TestCopy_WithRewrite(t *testing.T) {
tmpDir := t.TempDir()
defer os.RemoveAll(tmpDir)
testLinksDir := filepath.Join(tmpDir, "links")
setupTestLinksInDir(t, testLinksDir)
copyDstDir := t.TempDir()
defer os.RemoveAll(copyDstDir)
f := newTestFiles(testLinksDir)
// Create existing file
existingPath := filepath.Join(copyDstDir, "test.txt")
err := os.WriteFile(existingPath, []byte("existing"), 0644)
if err != nil {
t.Fatalf("Failed to create existing file: %v", err)
}
// Copy with rewrite
err = f.Copy("test.txt", copyDstDir, true)
if err != nil {
t.Fatalf("Copy() with rewrite error = %v", err)
}
// Verify file was overwritten
content, err := os.ReadFile(existingPath)
if err != nil {
t.Fatalf("Failed to read overwritten file: %v", err)
}
expected := "test content"
if string(content) != expected {
t.Errorf("Overwritten file content = %q, want %q", string(content), expected)
}
}
func TestExists_WithoutEmbedded(t *testing.T) {
f := NewFiles()
// Without embedded provider, Exists should return false
if f.Exists("any.txt") {
t.Error("Exists() = true, want false when no embedded provider")
}
}
func TestCopy_FromEmbedded(t *testing.T) {
f := NewFiles()
// This test only runs if embedded provider is available
if !f.Exists("docker-compose.yml") {
t.Skip("Skipping embedded test - no embedded provider")
}
tmpDir := t.TempDir()
defer os.RemoveAll(tmpDir)
err := f.Copy("docker-compose.yml", tmpDir, false)
if err != nil {
t.Fatalf("Copy() from embedded error = %v", err)
}
// Verify file was copied from embedded FS
copiedPath := filepath.Join(tmpDir, "docker-compose.yml")
content, err := os.ReadFile(copiedPath)
if err != nil {
t.Fatalf("Failed to read copied file: %v", err)
}
if len(content) == 0 {
t.Error("Copied file is empty")
}
// Verify content matches what we get from embedded FS
embeddedContent, err := f.GetContent("docker-compose.yml")
if err != nil {
t.Fatalf("Failed to get embedded content: %v", err)
}
if string(content) != string(embeddedContent) {
t.Error("Copied file content doesn't match embedded content")
}
}
func TestCheck_Missing(t *testing.T) {
tmpDir := t.TempDir()
defer os.RemoveAll(tmpDir)
testLinksDir := filepath.Join(tmpDir, "links")
setupTestLinksInDir(t, testLinksDir)
f := newTestFiles(testLinksDir)
workingDir := t.TempDir()
defer os.RemoveAll(workingDir)
status := f.Check("test.txt", workingDir)
if status != FileStatusMissing {
t.Errorf("Check() = %v, want %v for missing file", status, FileStatusMissing)
}
}
func TestCheck_OK(t *testing.T) {
tmpDir := t.TempDir()
defer os.RemoveAll(tmpDir)
testLinksDir := filepath.Join(tmpDir, "links")
setupTestLinksInDir(t, testLinksDir)
f := newTestFiles(testLinksDir)
workingDir := t.TempDir()
defer os.RemoveAll(workingDir)
// copy file to working directory
err := f.Copy("test.txt", workingDir, false)
if err != nil {
t.Fatalf("Copy() error = %v", err)
}
status := f.Check("test.txt", workingDir)
if status != FileStatusOK {
t.Errorf("Check() = %v, want %v for matching file", status, FileStatusOK)
}
}
func TestCheck_Modified(t *testing.T) {
tmpDir := t.TempDir()
defer os.RemoveAll(tmpDir)
testLinksDir := filepath.Join(tmpDir, "links")
setupTestLinksInDir(t, testLinksDir)
f := newTestFiles(testLinksDir)
workingDir := t.TempDir()
defer os.RemoveAll(workingDir)
// create modified file in working directory
modifiedPath := filepath.Join(workingDir, "test.txt")
err := os.WriteFile(modifiedPath, []byte("modified content"), 0644)
if err != nil {
t.Fatalf("Failed to create modified file: %v", err)
}
status := f.Check("test.txt", workingDir)
if status != FileStatusModified {
t.Errorf("Check() = %v, want %v for modified file", status, FileStatusModified)
}
}
func TestList(t *testing.T) {
// test with real embedded provider (if available)
f := NewFiles()
// test listing with observability prefix (should exist in embedded)
files, err := f.List("observability")
if err != nil {
t.Fatalf("List() error = %v", err)
}
// we should have at least some observability files
if len(files) == 0 {
t.Error("List() with 'observability' prefix returned no files from embedded")
}
// verify we get some expected files
foundObservabilityFile := false
for _, file := range files {
if strings.HasPrefix(file, "observability/") {
foundObservabilityFile = true
break
copyWithMode := func(name string, mode os.FileMode) func(*testing.T, Files, string) {
return func(t *testing.T, f Files, work string) {
copyOf(name)(t, f, work)
if err := os.Chmod(filepath.Join(work, name), mode); err != nil {
t.Fatalf("Chmod: %v", err)
}
}
}
if !foundObservabilityFile {
t.Error("List() with 'observability' prefix did not include any observability files")
tests := []struct {
name string
embedded bool
file string
setup func(t *testing.T, f Files, work string)
want FileStatus
}{
{name: "a file absent from the working directory is missing", file: "test.txt", want: FileStatusMissing},
{name: "an exact copy of a linked file is ok", file: "test.txt", setup: copyOf("test.txt"), want: FileStatusOK},
{name: "a linked file with other content is modified", file: "test.txt", setup: write("test.txt", "modified content"), want: FileStatusModified},
{name: "a linked file with other permissions is modified", file: "run.sh", setup: copyWithMode("run.sh", 0o644), want: permMismatch},
{name: "an exact copy of an embedded file is ok", embedded: true, file: "docker-compose.yml", setup: copyOf("docker-compose.yml"), want: FileStatusOK},
{name: "an embedded file with other permissions is modified", embedded: true, file: "docker-compose.yml", setup: copyWithMode("docker-compose.yml", 0o755), want: permMismatch},
{
name: "an embedded file with other bytes of the same size is modified",
embedded: true,
file: "docker-compose.yml",
setup: func(t *testing.T, f Files, work string) {
write("docker-compose.yml", strings.Repeat("X", len(filesEmbedded(t, "docker-compose.yml"))))(t, f, work)
},
want: FileStatusModified,
},
{name: "an embedded file of another size is modified", embedded: true, file: "docker-compose.yml", setup: write("docker-compose.yml", "different size content"), want: FileStatusModified},
}
// test listing with non-existent prefix
emptyFiles, err := f.List("nonexistent-prefix")
if err != nil {
t.Fatalf("List() with non-existent prefix error = %v", err)
}
if len(emptyFiles) != 0 {
t.Errorf("List() with non-existent prefix returned %d files, want 0", len(emptyFiles))
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
f := filesLinksFixture(t)
if tt.embedded {
filesRequireEmbedded(t)
// As a released installer runs: no links directory to take an expected mode from.
f = &files{linksDir: filepath.Join(t.TempDir(), "links")}
}
work := t.TempDir()
if tt.setup != nil {
tt.setup(t, f, work)
}
if got := f.Check(tt.file, work); got != tt.want {
t.Errorf("Check(%q) = %v, want %v", tt.file, got, tt.want)
}
})
}
}
func TestList_NonExistentPrefix(t *testing.T) {
tmpDir := t.TempDir()
defer os.RemoveAll(tmpDir)
testLinksDir := filepath.Join(tmpDir, "links")
setupTestLinksInDir(t, testLinksDir)
f := newTestFiles(testLinksDir)
files, err := f.List("nonexistent")
if err != nil {
t.Fatalf("List() error = %v", err)
func TestFiles_Exists_AnswersFromTheEmbeddedProviderOnly(t *testing.T) {
tests := []struct {
name string
file string
noProvider bool
want bool
}{
{name: "an embedded file exists", file: "docker-compose.yml", want: true},
{name: "an unknown name does not", file: "any.txt", want: false},
{name: "nothing exists without an embedded provider", file: "docker-compose.yml", noProvider: true, want: false},
}
if len(files) != 0 {
t.Errorf("List() for nonexistent prefix = %v, want empty slice", files)
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.noProvider {
filesWithoutEmbeddedProvider(t)
} else {
filesRequireEmbedded(t)
}
if got := NewFiles().Exists(tt.file); got != tt.want {
t.Errorf("Exists(%q) = %v, want %v", tt.file, got, tt.want)
}
})
}
}
func TestCheck_HashComparison_Embedded(t *testing.T) {
// test with real embedded files that have metadata
func TestFiles_List_FiltersEmbeddedFilesByPrefix(t *testing.T) {
filesRequireEmbedded(t)
f := NewFiles()
workingDir := t.TempDir()
defer os.RemoveAll(workingDir)
// copy embedded file to working directory
embeddedFile := "docker-compose.yml"
err := f.Copy(embeddedFile, workingDir, false)
if err != nil {
t.Fatalf("Copy() error = %v", err)
listed, err := f.List("observability")
if err != nil || len(listed) == 0 {
t.Fatalf("List(observability) = %v, %v; want files", listed, err)
}
for _, name := range listed {
if !strings.HasPrefix(name, "observability/") {
t.Errorf("List(observability) returned %q", name)
}
}
// check should return OK (hash matches)
status := f.Check(embeddedFile, workingDir)
if status != FileStatusOK {
t.Errorf("Check() hash comparison = %v, want %v for embedded file", status, FileStatusOK)
}
}
func TestCheck_HashComparison_SameSize_DifferentContent(t *testing.T) {
// test case where file has same size but different content (different hash)
f := NewFiles()
workingDir := t.TempDir()
defer os.RemoveAll(workingDir)
// get metadata for docker-compose.yml to know its size
embeddedContent, err := f.GetContent("docker-compose.yml")
if err != nil {
t.Skip("Skipping test - docker-compose.yml not available")
}
originalSize := len(embeddedContent)
// create file with same size but different content
modifiedContent := make([]byte, originalSize)
for i := range modifiedContent {
modifiedContent[i] = 'X' // fill with different content
}
modifiedPath := filepath.Join(workingDir, "docker-compose.yml")
err = os.WriteFile(modifiedPath, modifiedContent, 0644)
if err != nil {
t.Fatalf("Failed to create modified file: %v", err)
}
// check should return Modified (same size, different hash)
status := f.Check("docker-compose.yml", workingDir)
if status != FileStatusModified {
t.Errorf("Check() same size different hash = %v, want %v", status, FileStatusModified)
}
}
func TestCheck_HashComparison_DifferentSize(t *testing.T) {
// test case where file has different size (quick size check should catch this)
f := NewFiles()
workingDir := t.TempDir()
defer os.RemoveAll(workingDir)
// create file with different size
modifiedContent := []byte("different size content")
modifiedPath := filepath.Join(workingDir, "docker-compose.yml")
err := os.WriteFile(modifiedPath, modifiedContent, 0644)
if err != nil {
t.Fatalf("Failed to create modified file: %v", err)
}
// check should return Modified (different size detected quickly)
status := f.Check("docker-compose.yml", workingDir)
if status != FileStatusModified {
t.Errorf("Check() different size = %v, want %v", status, FileStatusModified)
}
}
// Helper functions
// setupTestLinksInDir creates test files structure in specified directory
func setupTestLinksInDir(t *testing.T, linksDir string) {
err := os.MkdirAll(linksDir, 0755)
if err != nil {
t.Fatalf("Failed to create test links directory: %v", err)
}
testFile := filepath.Join(linksDir, "test.txt")
err = os.WriteFile(testFile, []byte("test content"), 0644)
if err != nil {
t.Fatalf("Failed to create test file: %v", err)
}
}
// setupTestLinksWithDirInDir creates test files and directories structure in specified directory
func setupTestLinksWithDirInDir(t *testing.T, linksDir string) {
setupTestLinksInDir(t, linksDir)
testDir := filepath.Join(linksDir, "testdir")
err := os.MkdirAll(testDir, 0755)
if err != nil {
t.Fatalf("Failed to create test directory: %v", err)
}
nestedFile := filepath.Join(testDir, "nested.txt")
err = os.WriteFile(nestedFile, []byte("nested content"), 0644)
if err != nil {
t.Fatalf("Failed to create nested test file: %v", err)
if unknown, err := f.List("nonexistent-prefix"); err != nil || len(unknown) != 0 {
t.Errorf("List(nonexistent-prefix) = %v, %v; want no files", unknown, err)
}
}
+1 -1
View File
@@ -142,7 +142,7 @@ import (
"strings"
)
//go:embed fs/*
//go:embed all:fs
var embeddedFS embed.FS
// FileMetadata represents metadata for embedded files
@@ -0,0 +1 @@
../../../../../examples/configs/bedrock.provider.yml
+1
View File
@@ -0,0 +1 @@
../../../../../examples/graphiti
+1
View File
@@ -0,0 +1 @@
../../../../../examples/neo4j
@@ -0,0 +1,86 @@
package hardening
import (
"errors"
"os"
"path/filepath"
"testing"
"pentagi/cmd/installer/loader"
)
var errMocked = errors.New("mocked error")
// hardeningHostPaths returns a directory and a regular file that exist on the host.
func hardeningHostPaths(t *testing.T) (dir, file string) {
t.Helper()
dir = t.TempDir()
file = filepath.Join(t.TempDir(), "custom.provider.yml")
if err := os.WriteFile(file, nil, 0o600); err != nil {
t.Fatalf("write %s: %v", file, err)
}
return dir, file
}
// mockState stages writes into vars the way state.State does, and counts commits.
type mockState struct {
vars map[string]loader.EnvVar
setVarError map[string]error
setVarsError error
commits int
}
func (m *mockState) GetVar(key string) (loader.EnvVar, bool) {
if val, exists := m.vars[key]; exists {
return val, true
}
return loader.EnvVar{Name: key, Line: -1}, false
}
func (m *mockState) GetVars(names []string) (map[string]loader.EnvVar, map[string]bool) {
vars := make(map[string]loader.EnvVar, len(names))
present := make(map[string]bool, len(names))
for _, name := range names {
vars[name], present[name] = m.GetVar(name)
}
return vars, present
}
func (m *mockState) SetVar(name, value string) error {
if err := m.setVarError[name]; err != nil {
return err
}
if m.vars == nil {
m.vars = make(map[string]loader.EnvVar)
}
envVar := m.vars[name]
envVar.Name, envVar.Value, envVar.IsChanged = name, value, true
m.vars[name] = envVar
return nil
}
func (m *mockState) SetVars(vars map[string]string) error {
if m.setVarsError != nil {
return m.setVarsError
}
for name, value := range vars {
if err := m.SetVar(name, value); err != nil {
return err
}
}
return nil
}
func (m *mockState) Commit() error { m.commits++; return nil }
func (m *mockState) WriteVars(vars map[string]string) error { return m.SetVars(vars) }
func (m *mockState) GetAllVars() map[string]loader.EnvVar { return m.vars }
func (m *mockState) GetEnvPath() string { return "" }
func (m *mockState) Exists() bool { return true }
func (m *mockState) Reset() error { return nil }
func (m *mockState) IsDirty() bool { return false }
func (m *mockState) GetEulaConsent() bool { return true }
func (m *mockState) SetEulaConsent() error { return nil }
func (m *mockState) SetStack(stack []string) error { return nil }
func (m *mockState) GetStack() []string { return []string{} }
func (m *mockState) ResetVar(name string) error { return nil }
func (m *mockState) ResetVars(names []string) error { return nil }
File diff suppressed because it is too large. Load diff
+15 -28
View File
@@ -34,36 +34,23 @@ func DoMigrateSettings(s state.State) error {
configsPath := controller.GetEmbeddedLLMConfigsPath(files.NewFiles())
// migration from LLM_SERVER_CONFIG_PATH to PENTAGI_LLM_SERVER_CONFIG_PATH
llmServerConfigPathVar, exists := s.GetVar("LLM_SERVER_CONFIG_PATH")
llmServerConfigPath := llmServerConfigPathVar.Value
isEmbeddedCustomConfig := slices.Contains(configsPath, llmServerConfigPath) ||
llmServerConfigPath == controller.DefaultCustomConfigsPath
if exists && !isEmbeddedCustomConfig && llmServerConfigPath != "" {
exists = checkPathInHostFS(llmServerConfigPath, file)
}
if exists && !isEmbeddedCustomConfig && llmServerConfigPath != "" {
if err := s.SetVar("PENTAGI_LLM_SERVER_CONFIG_PATH", llmServerConfigPath); err != nil {
// A provider config variable that names a file on the host becomes the mount source,
// and the variable itself the path that file is mounted at in the container.
for _, config := range []struct{ variable, mountedPath string }{
{"LLM_SERVER_CONFIG_PATH", controller.DefaultCustomConfigsPath},
{"OLLAMA_SERVER_CONFIG_PATH", controller.DefaultOllamaConfigsPath},
{"BEDROCK_CONFIG_PATH", controller.DefaultBedrockConfigsPath},
} {
configPathVar, exists := s.GetVar(config.variable)
configPath := configPathVar.Value
isInContainer := slices.Contains(configsPath, configPath) || configPath == config.mountedPath
if !exists || isInContainer || configPath == "" || !checkPathInHostFS(configPath, file) {
continue
}
if err := s.SetVar("PENTAGI_"+config.variable, configPath); err != nil {
return err
}
if err := s.SetVar("LLM_SERVER_CONFIG_PATH", controller.DefaultCustomConfigsPath); err != nil {
return err
}
}
// migration from OLLAMA_SERVER_CONFIG_PATH to PENTAGI_OLLAMA_SERVER_CONFIG_PATH
ollamaServerConfigPathVar, exists := s.GetVar("OLLAMA_SERVER_CONFIG_PATH")
ollamaServerConfigPath := ollamaServerConfigPathVar.Value
isEmbeddedOllamaConfig := slices.Contains(configsPath, ollamaServerConfigPath) ||
ollamaServerConfigPath == controller.DefaultOllamaConfigsPath
if exists && !isEmbeddedOllamaConfig && ollamaServerConfigPath != "" {
exists = checkPathInHostFS(ollamaServerConfigPath, file)
}
if exists && !isEmbeddedOllamaConfig && ollamaServerConfigPath != "" {
if err := s.SetVar("PENTAGI_OLLAMA_SERVER_CONFIG_PATH", ollamaServerConfigPath); err != nil {
return err
}
if err := s.SetVar("OLLAMA_SERVER_CONFIG_PATH", controller.DefaultOllamaConfigsPath); err != nil {
if err := s.SetVar(config.variable, config.mountedPath); err != nil {
return err
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -19,7 +19,7 @@ DEBUG=false
# API Settings
API_KEY=old_key`
os.WriteFile(envPath, []byte(initialContent), 0644)
_ = os.WriteFile(envPath, []byte(initialContent), 0644)
// Step 1: Load existing .env file
envFile, err := LoadEnvFile(envPath)
+258
View File
@@ -0,0 +1,258 @@
package loader
import (
"os"
"path/filepath"
"reflect"
"runtime"
"strings"
"sync"
"testing"
)
func TestFile_EnvVar_ReportsDefaultAndPresence(t *testing.T) {
tests := []struct {
name string
envVar EnvVar
wantDefault bool
wantPresent bool
}{
{name: "a file value other than the default", envVar: EnvVar{Value: "test_value", Default: "default_value", Line: 5}, wantPresent: true},
{name: "a file value equal to the default", envVar: EnvVar{Value: "default_value", Default: "default_value", Line: 5}, wantDefault: true, wantPresent: true},
{name: "an empty value not in the file falls back to the default", envVar: EnvVar{Default: "default_value", Line: -1}, wantDefault: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tt.envVar.IsDefault(); got != tt.wantDefault {
t.Errorf("IsDefault() = %v, want %v", got, tt.wantDefault)
}
if got := tt.envVar.IsPresent(); got != tt.wantPresent {
t.Errorf("IsPresent() = %v, want %v", got, tt.wantPresent)
}
})
}
}
// TestFile_EnvFile_KeepsVariablesInMemory: subtests run in order over one file and are keyed by method.
func TestFile_EnvFile_KeepsVariablesInMemory(t *testing.T) {
envFile := &envFile{vars: make(map[string]*EnvVar), mx: &sync.Mutex{}}
t.Run("set adds a new variable as changed and absent from the file", func(t *testing.T) {
envFile.Set("NEW_VAR", "new_value")
envVar, exists := envFile.Get("NEW_VAR")
if !exists || envVar.Name != "NEW_VAR" || envVar.Value != "new_value" || !envVar.IsChanged || envVar.Line != -1 {
t.Errorf("Get(NEW_VAR) = %+v, %v; want a changed new_value on line -1", envVar, exists)
}
})
t.Run("set updates an existing variable", func(t *testing.T) {
envFile.Set("NEW_VAR", "updated_value")
if envVar, exists := envFile.Get("NEW_VAR"); !exists || envVar.Value != "updated_value" || !envVar.IsChanged {
t.Errorf("Get(NEW_VAR) = %+v, %v; want a changed updated_value", envVar, exists)
}
})
t.Run("set with the same value does not mark it changed", func(t *testing.T) {
envFile.vars["NEW_VAR"].IsChanged = false
envFile.Set("NEW_VAR", "updated_value")
if envVar, exists := envFile.Get("NEW_VAR"); !exists || envVar.IsChanged {
t.Errorf("Get(NEW_VAR) = %+v, %v; want it unchanged", envVar, exists)
}
})
t.Run("get reports an unknown variable as absent", func(t *testing.T) {
if envVar, exists := envFile.Get("NON_EXISTENT"); exists || envVar.Name != "NON_EXISTENT" || envVar.Line != -1 {
t.Errorf("Get(NON_EXISTENT) = %+v, %v; want an absent variable on line -1", envVar, exists)
}
})
t.Run("set trims names and values", func(t *testing.T) {
envFile.Set(" TRIM_VAR ", " trim_value ")
if envVar, exists := envFile.Get("TRIM_VAR"); !exists || envVar.Name != "TRIM_VAR" || envVar.Value != "trim_value" {
t.Errorf("Get(TRIM_VAR) = %+v, %v; want TRIM_VAR=trim_value", envVar, exists)
}
})
t.Run("del removes a variable", func(t *testing.T) {
envFile.Set("DELETE_VAR", "delete_value")
if envVar, exists := envFile.Get("DELETE_VAR"); !exists || envVar.Value != "delete_value" {
t.Fatalf("Get(DELETE_VAR) before Del = %+v, %v", envVar, exists)
}
envFile.Del("DELETE_VAR")
if _, exists := envFile.Get("DELETE_VAR"); exists {
t.Error("DELETE_VAR still exists after Del")
}
})
t.Run("del of an unknown variable changes nothing", func(t *testing.T) {
envFile.Del("NON_EXISTENT_VAR")
if got := len(envFile.GetAll()); got != 2 {
t.Errorf("GetAll() holds %d variables after Del of an unknown one, want 2", got)
}
})
t.Run("get all returns every variable", func(t *testing.T) {
allVars := envFile.GetAll()
if len(allVars) != 2 || allVars["NEW_VAR"].Value != "updated_value" || allVars["TRIM_VAR"].Value != "trim_value" {
t.Errorf("GetAll() = %+v, want NEW_VAR=updated_value and TRIM_VAR=trim_value", allVars)
}
})
t.Run("set all adds and overwrites variables as given", func(t *testing.T) {
newVars := map[string]EnvVar{
"BATCH_VAR1": {Name: "BATCH_VAR1", Value: "batch_value1", IsChanged: true, Line: -1},
"BATCH_VAR2": {Name: "BATCH_VAR2", Value: "batch_value2", IsChanged: false, Line: 5},
"NEW_VAR": {Name: "NEW_VAR", Value: "overwritten", IsChanged: true, Line: 10},
}
envFile.SetAll(newVars)
for name, expected := range newVars {
if actual, exists := envFile.Get(name); !exists || actual != expected {
t.Errorf("Get(%s) = %+v, %v; want %+v", name, actual, exists, expected)
}
}
if _, exists := envFile.Get("TRIM_VAR"); !exists {
t.Error("SetAll dropped TRIM_VAR, which it was not given")
}
})
t.Run("set all with an empty map changes nothing", func(t *testing.T) {
envFile.SetAll(map[string]EnvVar{})
if got := len(envFile.GetAll()); got != 4 {
t.Errorf("GetAll() holds %d variables after an empty SetAll, want 4", got)
}
})
}
func TestFile_Save_RewritesChangedLinesAndKeepsABackup(t *testing.T) {
const original = "# Comment line\nVAR1=value1\nVAR2=value2\nVAR3=value3\n"
path := loaderEnvFile(t, original)
envFile, err := LoadEnvFile(path)
if err != nil {
t.Fatalf("LoadEnvFile: %v", err)
}
envFile.Set("VAR1", "new_value1")
envFile.Set("NEW_VAR", "new_value")
envFile.Del("VAR2")
if err := envFile.Save(path); err != nil {
t.Fatalf("Save: %v", err)
}
saved, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read saved file: %v", err)
}
if want := "# Comment line\nVAR1=new_value1\nVAR3=value3\nNEW_VAR=new_value\n"; string(saved) != want {
t.Errorf("saved file = %q, want %q", saved, want)
}
backupDir := filepath.Join(filepath.Dir(path), ".bak")
backups, err := os.ReadDir(backupDir)
if err != nil || len(backups) != 1 || !strings.HasPrefix(backups[0].Name(), ".env.") {
t.Fatalf("backups = %v, %v; want one .env.<timestamp>", backups, err)
}
if backup, err := os.ReadFile(filepath.Join(backupDir, backups[0].Name())); err != nil || string(backup) != original {
t.Errorf("backup = %q, %v; want the original file", backup, err)
}
if info, err := os.Stat(path); err != nil {
t.Errorf("stat saved file: %v", err)
} else if runtime.GOOS != "windows" && info.Mode().Perm() != 0o600 {
t.Errorf("saved file mode = %v, want the original -rw-------", info.Mode().Perm())
}
for _, envVar := range envFile.GetAll() {
if envVar.IsChanged {
t.Errorf("%s is still marked changed after Save", envVar.Name)
}
}
}
func TestFile_Save_WritesOnlyPendingChangesToAFile(t *testing.T) {
tests := []struct {
name string
vars map[string]*EnvVar
target func(t *testing.T) string
wantErr string
want string
}{
{
name: "a missing file is created",
vars: map[string]*EnvVar{"VAR1": {Name: "VAR1", Value: "value1", IsChanged: true, Line: -1}},
target: func(t *testing.T) string { return filepath.Join(t.TempDir(), "new.env") },
want: "VAR1=value1\n",
},
{
name: "a directory is refused",
vars: map[string]*EnvVar{"VAR1": {Name: "VAR1", Value: "value1", IsChanged: true, Line: 0}},
target: func(t *testing.T) string { return t.TempDir() },
wantErr: "is a directory",
},
{
name: "nothing changed leaves the file untouched",
vars: map[string]*EnvVar{"VAR1": {Name: "VAR1", Value: "value1", IsChanged: false, Line: 0}},
target: func(t *testing.T) string { return loaderEnvFile(t, "# Empty file\n") },
want: "# Empty file\n",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
envFile := &envFile{vars: tt.vars, perm: 0o644, mx: &sync.Mutex{}}
path := tt.target(t)
err := envFile.Save(path)
if tt.wantErr != "" {
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
t.Fatalf("Save() error = %v, want it to mention %q", err, tt.wantErr)
}
return
}
if err != nil {
t.Fatalf("Save() error = %v", err)
}
if content, err := os.ReadFile(path); err != nil || string(content) != tt.want {
t.Errorf("file = %q, %v; want %q", content, err, tt.want)
}
})
}
}
func TestFile_Clone_IsIndependentOfTheOriginal(t *testing.T) {
original := &envFile{
vars: map[string]*EnvVar{
"VAR1": {Name: "VAR1", Value: "value1", IsChanged: true, Line: 0},
"VAR2": {Name: "VAR2", Value: "value2", IsChanged: false, Line: 1},
},
perm: 0o644,
raw: "VAR1=value1\nVAR2=value2",
mx: &sync.Mutex{},
}
clone := original.Clone()
if !reflect.DeepEqual(clone.GetAll(), original.GetAll()) {
t.Errorf("clone variables = %+v, want %+v", clone.GetAll(), original.GetAll())
}
if c := clone.(*envFile); c.raw != original.raw || c.perm != original.perm {
t.Errorf("clone raw, perm = %q, %v; want the original's, or its Save loses the file", c.raw, c.perm)
}
clone.Set("VAR1", "modified")
if original.vars["VAR1"].Value != "value1" {
t.Error("modifying the clone changed the original")
}
}
@@ -0,0 +1,17 @@
package loader
import (
"os"
"path/filepath"
"testing"
)
// loaderEnvFile writes content to .env in a fresh directory, where Save also puts its .bak.
func loaderEnvFile(t *testing.T, content string) string {
t.Helper()
path := filepath.Join(t.TempDir(), ".env")
if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
t.Fatalf("write env file: %v", err)
}
return path
}
+20 -2
View File
@@ -5,6 +5,7 @@ import (
"net/url"
"os"
"reflect"
"regexp"
"strconv"
"strings"
"sync"
@@ -14,6 +15,12 @@ import (
"github.com/caarlos0/env/v10"
)
// envVarNameRe matches valid environment variable identifiers (e.g. OPEN_AI_KEY).
// Used to distinguish a real commented-out assignment (e.g. "#SOME_VAR=value")
// from a plain human-readable comment that merely contains a stray '=' character
// (e.g. "<=" comparisons or "empty = disabled" phrasing in descriptive text).
var envVarNameRe = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`)
func LoadEnvFile(path string) (EnvFile, error) {
info, err := os.Stat(path)
if err != nil {
@@ -51,8 +58,9 @@ func loadVars(raw string) map[string]*EnvVar {
if line == "" {
continue
}
isComment := false
if strings.HasPrefix(line, "#") {
envVar.IsComment = true
isComment = true
line = trim(strings.TrimPrefix(line, "#"))
}
@@ -60,7 +68,17 @@ func loadVars(raw string) map[string]*EnvVar {
if len(parts) != 2 {
continue
}
envVar.Name = trim(parts[0])
name := trim(parts[0])
// a commented line only represents a disabled variable assignment
// (e.g. "#SOME_VAR=value") if what precedes '=' is a valid identifier;
// otherwise it's just descriptive text that happens to contain '='
// (e.g. "<=" comparisons or "empty = disabled" phrasing) and must not
// be treated as a pseudo-variable that never resolves as "unchanged"
if isComment && !envVarNameRe.MatchString(name) {
continue
}
envVar.IsComment = isComment
envVar.Name = name
envVar.Value = trim(stripComments(parts[1]))
envVar.IsChanged = envVar.Value != parts[1] || envVar.Name != parts[0]
if envVar.Name != "" {
+92 -641
View File
@@ -3,696 +3,147 @@ package loader
import (
"os"
"path/filepath"
"reflect"
"strings"
"sync"
"testing"
)
func containsLine(content, line string) bool {
lines := strings.Split(content, "\n")
for _, l := range lines {
if strings.TrimSpace(l) == line {
return true
}
func TestLoader_LoadEnvFile_ParsesAssignmentsAndCommentedOutVariables(t *testing.T) {
type parsed struct {
value string
comment bool
changed bool // the line is not in canonical NAME=value form, so Save rewrites it
}
return false
}
func TestLoadEnvFile(t *testing.T) {
tests := []struct {
name string
content string
wantErr bool
want map[string]parsed // every variable the file itself defines
}{
{name: "empty file", content: "", want: map[string]parsed{}},
{name: "comment only", content: "# Just a comment", want: map[string]parsed{}},
{
name: "valid file",
content: `# Comment
VAR1=value1
VAR2=value2
# Another comment
VAR3=value3`,
wantErr: false,
name: "assignments between comments",
content: "# Comment\nVAR1=value1\nVAR2=value2\n# Another comment\nVAR3=value3",
want: map[string]parsed{"VAR1": {value: "value1"}, "VAR2": {value: "value2"}, "VAR3": {value: "value3"}},
},
{name: "empty lines", content: "\n\n\nVAR1=value1\n\n", want: map[string]parsed{"VAR1": {value: "value1"}}},
{
name: "commented-out variable",
content: "#VAR1=commented\nVAR2=active",
want: map[string]parsed{"VAR1": {value: "commented", comment: true}, "VAR2": {value: "active"}},
},
{
name: "empty file",
content: "",
wantErr: false,
name: "inline comment is stripped",
content: "VAR1=value1 # comment\nVAR2=value2 # comment",
want: map[string]parsed{"VAR1": {value: "value1", changed: true}, "VAR2": {value: "value2", changed: true}},
},
{
name: "comment only",
content: "# Just a comment",
wantErr: false,
name: "spaces around names and values",
content: "VAR1 = value1\n VAR2=value2 ",
want: map[string]parsed{"VAR1": {value: "value1", changed: true}, "VAR2": {value: "value2"}},
},
{
name: "malformed lines",
content: `VAR1=value1
invalid line
VAR2=value2`,
wantErr: false,
name: "equals signs inside values",
content: "VAR1=value=with=equals\nVAR2=url=https://example.com",
want: map[string]parsed{"VAR1": {value: "value=with=equals"}, "VAR2": {value: "url=https://example.com"}},
},
{
name: "comments in value",
content: `VAR1=value1 # comment
VAR2=value2 # comment`,
wantErr: false,
name: "lines without an assignment are ignored",
content: "invalid line\nVAR1=value1\nanother invalid",
want: map[string]parsed{"VAR1": {value: "value1"}},
},
{
name: "comment prose containing an equals sign is not a variable",
content: strings.Join([]string{
"## Default: 1200 (20 minutes). Range: 1-10800 (up to 3 hours). Values <= 0 or above 10800 are clamped to 10800.",
"TERMINAL_TOOL_TIMEOUT=1200",
"",
"## Go pprof HTTP listener (empty = disabled). Use host:port, e.g. :7777.",
"PPROF_ADDR=",
"",
"## one worker node, one Neo4j/Graphiti, one Langfuse (empty = standalone instance).",
"TENANT_ID=",
"",
"#REAL_COMMENTED_VAR=commented_value",
}, "\n"),
want: map[string]parsed{
"TERMINAL_TOOL_TIMEOUT": {value: "1200"},
"PPROF_ADDR": {},
"TENANT_ID": {},
"REAL_COMMENTED_VAR": {value: "commented_value", comment: true},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tmpFile := createTempFile(t, tt.content)
defer os.Remove(tmpFile)
envFile, err := LoadEnvFile(tmpFile)
if (err != nil) != tt.wantErr {
t.Errorf("LoadEnvFile() error = %v, wantErr %v", err, tt.wantErr)
return
envFile, err := LoadEnvFile(loaderEnvFile(t, tt.content))
if err != nil {
t.Fatalf("LoadEnvFile() error = %v", err)
}
if !tt.wantErr && envFile == nil {
t.Error("Expected envFile to be non-nil")
got := map[string]parsed{}
for name, envVar := range envFile.GetAll() {
if envVar.IsPresent() {
got[name] = parsed{value: envVar.Value, comment: envVar.IsComment, changed: envVar.IsChanged}
}
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("variables from the file = %+v, want %+v", got, tt.want)
}
})
}
}
func TestLoadEnvFileErrors(t *testing.T) {
t.Run("non-existent file", func(t *testing.T) {
_, err := LoadEnvFile("/non/existent/file")
if err == nil {
t.Error("Expected error for non-existent file")
}
})
t.Run("directory instead of file", func(t *testing.T) {
tmpDir := t.TempDir()
defer os.RemoveAll(tmpDir)
_, err := LoadEnvFile(tmpDir)
if err == nil {
t.Error("Expected error when path is directory")
}
})
}
func TestEnvVarMethods(t *testing.T) {
envVar := &EnvVar{
Name: "TEST_VAR",
Value: "test_value",
Default: "default_value",
Line: 5,
}
if envVar.IsDefault() {
t.Error("Expected IsDefault() to be false")
}
if !envVar.IsPresent() {
t.Error("Expected IsPresent() to be true")
}
envVar.Value = "default_value"
if !envVar.IsDefault() {
t.Error("Expected IsDefault() to be true")
}
envVar.Line = -1
if envVar.IsPresent() {
t.Error("Expected IsPresent() to be false")
}
}
func TestEnvFileSetGet(t *testing.T) {
envFile := &envFile{
vars: make(map[string]*EnvVar),
mx: &sync.Mutex{},
}
t.Run("set new variable", func(t *testing.T) {
envFile.Set("NEW_VAR", "new_value")
envVar, exists := envFile.Get("NEW_VAR")
if !exists {
t.Error("Expected NEW_VAR to exist")
}
if envVar.Name != "NEW_VAR" || envVar.Value != "new_value" {
t.Errorf("Expected NEW_VAR=new_value, got %s=%s", envVar.Name, envVar.Value)
}
if !envVar.IsChanged {
t.Error("Expected IsChanged to be true for new variable")
}
if envVar.Line != -1 {
t.Error("Expected Line to be -1 for new variable")
}
})
t.Run("update existing variable", func(t *testing.T) {
envFile.Set("NEW_VAR", "updated_value")
envVar, exists := envFile.Get("NEW_VAR")
if !exists {
t.Error("Expected NEW_VAR to exist")
}
if envVar.Value != "updated_value" {
t.Errorf("Expected updated_value, got %s", envVar.Value)
}
if !envVar.IsChanged {
t.Error("Expected IsChanged to remain true")
}
})
t.Run("set same value should not mark as changed", func(t *testing.T) {
// Reset IsChanged flag first
envFile.vars["NEW_VAR"].IsChanged = false
envFile.Set("NEW_VAR", "updated_value") // same value
envVar, exists := envFile.Get("NEW_VAR")
if !exists {
t.Error("Expected NEW_VAR to exist")
}
if envVar.IsChanged {
t.Error("Expected IsChanged to remain false when setting same value")
}
})
t.Run("get non-existent variable", func(t *testing.T) {
envVar, exists := envFile.Get("NON_EXISTENT")
if exists {
t.Error("Expected NON_EXISTENT to not exist")
}
if envVar.Name != "NON_EXISTENT" || envVar.Line != -1 {
t.Error("Expected empty EnvVar with Line=-1 for non-existent variable")
}
})
t.Run("trim whitespace", func(t *testing.T) {
envFile.Set(" TRIM_VAR ", " trim_value ")
envVar, exists := envFile.Get("TRIM_VAR")
if !exists {
t.Error("Expected TRIM_VAR to exist")
}
if envVar.Name != "TRIM_VAR" || envVar.Value != "trim_value" {
t.Errorf("Expected TRIM_VAR=trim_value, got %s=%s", envVar.Name, envVar.Value)
}
})
t.Run("delete variable", func(t *testing.T) {
envFile.Set("DELETE_VAR", "delete_value")
envVar, exists := envFile.Get("DELETE_VAR")
if !exists {
t.Error("Expected DELETE_VAR to exist before deletion")
}
if envVar.Value != "delete_value" {
t.Errorf("Expected DELETE_VAR value 'delete_value', got '%s'", envVar.Value)
}
envFile.Del("DELETE_VAR")
_, exists = envFile.Get("DELETE_VAR")
if exists {
t.Error("Expected DELETE_VAR to not exist after deletion")
}
})
t.Run("delete non-existent variable", func(t *testing.T) {
originalCount := len(envFile.GetAll())
envFile.Del("NON_EXISTENT_VAR")
if len(envFile.GetAll()) != originalCount {
t.Error("Deleting non-existent variable should not change variable count")
}
})
t.Run("get all variables", func(t *testing.T) {
allVars := envFile.GetAll()
if len(allVars) < 2 { // should have at least NEW_VAR and TRIM_VAR
t.Errorf("Expected at least 2 variables, got %d", len(allVars))
}
if newVar, exists := allVars["NEW_VAR"]; !exists {
t.Error("Expected NEW_VAR in GetAll result")
} else if newVar.Value != "updated_value" {
t.Errorf("Expected NEW_VAR value 'updated_value', got '%s'", newVar.Value)
}
})
t.Run("set all variables", func(t *testing.T) {
newVars := map[string]EnvVar{
"BATCH_VAR1": {Name: "BATCH_VAR1", Value: "batch_value1", IsChanged: true, Line: -1},
"BATCH_VAR2": {Name: "BATCH_VAR2", Value: "batch_value2", IsChanged: false, Line: 5},
"EXISTING_VAR": {Name: "EXISTING_VAR", Value: "overwritten", IsChanged: true, Line: 10},
}
envFile.SetAll(newVars)
// Check that all new variables were set
for name, expected := range newVars {
actual, exists := envFile.Get(name)
if !exists {
t.Errorf("Expected variable %s to exist after SetAll", name)
continue
}
if actual.Value != expected.Value {
t.Errorf("Variable %s: expected value %s, got %s", name, expected.Value, actual.Value)
}
if actual.IsChanged != expected.IsChanged {
t.Errorf("Variable %s: expected IsChanged %v, got %v", name, expected.IsChanged, actual.IsChanged)
}
if actual.Line != expected.Line {
t.Errorf("Variable %s: expected Line %d, got %d", name, expected.Line, actual.Line)
}
}
// Check that previous variables still exist
if _, exists := envFile.Get("NEW_VAR"); !exists {
t.Error("Expected NEW_VAR to still exist after SetAll")
}
})
t.Run("set all empty map", func(t *testing.T) {
originalCount := len(envFile.GetAll())
envFile.SetAll(map[string]EnvVar{})
if len(envFile.GetAll()) != originalCount {
t.Error("SetAll with empty map should not change existing variables")
}
})
}
func TestEnvFileSave(t *testing.T) {
content := `VAR1=value1
VAR2=value2`
tmpFile := createTempFile(t, content)
defer os.Remove(tmpFile)
envFile, err := LoadEnvFile(tmpFile)
if err != nil {
t.Fatalf("Failed to load env file: %v", err)
}
envFile.Set("VAR1", "new_value1")
envFile.Set("NEW_VAR", "new_value")
err = envFile.Save(tmpFile)
if err != nil {
t.Fatalf("Failed to save env file: %v", err)
}
// Check backup was created
backupDir := filepath.Join(filepath.Dir(tmpFile), ".bak")
entries, err := os.ReadDir(backupDir)
if err != nil {
t.Fatalf("Failed to read backup directory: %v", err)
}
if len(entries) == 0 {
t.Error("Expected backup file to be created")
}
// Check file content
savedContent, err := os.ReadFile(tmpFile)
if err != nil {
t.Fatalf("Failed to read saved file: %v", err)
}
expectedLines := []string{"VAR1=new_value1", "VAR2=value2", "NEW_VAR=new_value"}
savedLines := strings.Split(strings.TrimSpace(string(savedContent)), "\n")
for _, expected := range expectedLines {
found := false
for _, line := range savedLines {
if strings.TrimSpace(line) == expected {
found = true
break
}
}
if !found {
t.Errorf("Expected line '%s' not found in saved file", expected)
}
}
// Check IsChanged flags reset
for _, envVar := range envFile.GetAll() {
if envVar.IsChanged {
t.Errorf("Expected IsChanged to be false after save for %s", envVar.Name)
}
}
// Cleanup backup
os.RemoveAll(backupDir)
}
func TestEnvFileSaveNewFile(t *testing.T) {
envFile := &envFile{
vars: map[string]*EnvVar{
"VAR1": {Name: "VAR1", Value: "value1", IsChanged: true, Line: -1},
},
perm: 0644,
raw: "",
mx: &sync.Mutex{},
}
tmpDir := t.TempDir()
defer os.RemoveAll(tmpDir)
newFile := filepath.Join(tmpDir, "new.env")
err := envFile.Save(newFile)
if err != nil {
t.Fatalf("Failed to save new file: %v", err)
}
content, err := os.ReadFile(newFile)
if err != nil {
t.Fatalf("Failed to read new file: %v", err)
}
if !strings.Contains(string(content), "VAR1=value1") {
t.Error("Expected VAR1=value1 in new file")
}
}
func TestEnvFileSaveErrors(t *testing.T) {
const defaultEmptyContent = "# Empty file\n"
t.Run("save to directory", func(t *testing.T) {
envFile := &envFile{
vars: map[string]*EnvVar{
"VAR1": {Name: "VAR1", Value: "value1", IsChanged: true, Line: 0},
},
mx: &sync.Mutex{},
}
tmpDir := t.TempDir()
defer os.RemoveAll(tmpDir)
err := envFile.Save(tmpDir)
if err == nil {
t.Error("Expected error when saving to directory")
}
})
t.Run("save empty file", func(t *testing.T) {
envFile := &envFile{
vars: make(map[string]*EnvVar),
mx: &sync.Mutex{},
}
tmpFile := createTempFile(t, defaultEmptyContent)
defer os.Remove(tmpFile)
err := envFile.Save(tmpFile)
if err != nil {
t.Fatalf("Failed to save empty env file: %v", err)
}
content, err := os.ReadFile(tmpFile)
if err != nil {
t.Fatalf("Failed to read empty env file: %v", err)
}
if string(content) != defaultEmptyContent {
t.Errorf("Expected default empty content, got '%s'", string(content))
}
})
t.Run("save without changes", func(t *testing.T) {
envFile := &envFile{
vars: map[string]*EnvVar{
"VAR1": {Name: "VAR1", Value: "value1", IsChanged: false, Line: 0},
},
mx: &sync.Mutex{},
}
tmpFile := createTempFile(t, defaultEmptyContent)
defer os.Remove(tmpFile)
err := envFile.Save(tmpFile)
if err != nil {
t.Fatalf("Failed to save non changed env file: %v", err)
}
content, err := os.ReadFile(tmpFile)
if err != nil {
t.Fatalf("Failed to read empty env file: %v", err)
}
if string(content) != defaultEmptyContent {
t.Errorf("Expected default empty content, got '%s'", string(content))
}
})
}
func TestEnvFileClone(t *testing.T) {
original := &envFile{
vars: map[string]*EnvVar{
"VAR1": {Name: "VAR1", Value: "value1", IsChanged: true, Line: 0},
"VAR2": {Name: "VAR2", Value: "value2", IsChanged: false, Line: 1},
},
perm: 0644,
raw: "VAR1=value1\nVAR2=value2",
mx: &sync.Mutex{},
}
clone := original.Clone()
// Check independence
if clone == original {
t.Error("Clone should return different instance")
}
// Check content equality
if len(clone.GetAll()) != len(original.GetAll()) {
t.Error("Clone should have same number of variables")
}
for name, origVar := range original.GetAll() {
cloneVar, exists := clone.Get(name)
if !exists {
t.Errorf("Variable %s missing in clone", name)
continue
}
if cloneVar.Name != origVar.Name || cloneVar.Value != origVar.Value {
t.Errorf("Variable %s content mismatch in clone", name)
}
}
// Test modification independence
clone.Set("VAR1", "modified")
if original.vars["VAR1"].Value == "modified" {
t.Error("Modifying clone should not affect original")
}
}
func TestLoadVarsEdgeCases(t *testing.T) {
func TestLoader_LoadEnvFile_RefusesAMissingFileOrADirectory(t *testing.T) {
dir := t.TempDir()
tests := []struct {
name string
content string
expected map[string]string
name string
path string
wantErr string
}{
{
name: "empty lines",
content: "\n\n\nVAR1=value1\n\n",
expected: map[string]string{"VAR1": "value1"},
},
{
name: "commented variables",
content: "#VAR1=commented\nVAR2=active",
expected: map[string]string{"VAR1": "commented", "VAR2": "active"},
},
{
name: "comments in value",
content: "VAR1=value1 # comment\nVAR2=value2 # comment",
expected: map[string]string{"VAR1": "value1", "VAR2": "value2"},
},
{
name: "variables with spaces",
content: "VAR1 = value1\n VAR2=value2 ",
expected: map[string]string{"VAR1": "value1", "VAR2": "value2"},
},
{
name: "variables with equals in value",
content: "VAR1=value=with=equals\nVAR2=url=https://example.com",
expected: map[string]string{"VAR1": "value=with=equals", "VAR2": "url=https://example.com"},
},
{
name: "invalid lines ignored",
content: "invalid line\nVAR1=value1\nanother invalid",
expected: map[string]string{"VAR1": "value1"},
},
{name: "a missing file", path: filepath.Join(dir, "absent.env"), wantErr: "failed to stat"},
{name: "a directory", path: dir, wantErr: "is a directory"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
vars := loadVars(tt.content)
for expectedName, expectedValue := range tt.expected {
envVar, exists := vars[expectedName]
if !exists {
t.Errorf("Expected variable %s not found", expectedName)
continue
}
if envVar.Value != expectedValue {
t.Errorf("Variable %s: expected value %s, got %s", expectedName, expectedValue, envVar.Value)
}
if _, err := LoadEnvFile(tt.path); err == nil || !strings.Contains(err.Error(), tt.wantErr) {
t.Errorf("LoadEnvFile() error = %v, want it to mention %q", err, tt.wantErr)
}
})
}
}
func TestPatchRaw(t *testing.T) {
envFile := &envFile{
vars: map[string]*EnvVar{
"EXISTING": {Name: "EXISTING", Value: "updated", IsChanged: true, Line: 1},
"NEW_VAR": {Name: "NEW_VAR", Value: "new_value", IsChanged: true, Line: -1},
},
raw: "# Comment line\nEXISTING=old_value\nUNCHANGED=unchanged\n",
mx: &sync.Mutex{},
func TestLoader_LoadEnvFile_FillsInConfigDefaults(t *testing.T) {
// Defaults are read through the process environment, so a developer's shell must not answer instead.
for _, name := range []string{"SERVER_PORT", "DEBUG", "DATABASE_URL", "STATIC_URL"} {
t.Setenv(name, "")
os.Unsetenv(name)
}
envFile.patchRaw()
lines := strings.Split(envFile.raw, "\n")
// Check existing variable updated
if lines[1] != "EXISTING=updated" {
t.Errorf("Expected line 1 to be 'EXISTING=updated', got '%s'", lines[1])
}
// Check new variable added
found := false
for _, line := range lines {
if line == "NEW_VAR=new_value" {
found = true
break
}
}
if !found {
t.Error("Expected NEW_VAR=new_value to be added to file")
}
// Check comment not modified
if lines[0] != "# Comment line" {
t.Errorf("Expected comment line unchanged, got '%s'", lines[0])
}
// Check last line is empty
if lines[len(lines)-1] != "" {
t.Errorf("Expected last line to be empty, got '%s'", lines[len(lines)-1])
}
}
func TestEnvFileDelInSave(t *testing.T) {
content := `VAR1=value1
VAR2=value2
VAR3=value3`
tmpFile := createTempFile(t, content)
defer os.Remove(tmpFile)
envFile, err := LoadEnvFile(tmpFile)
envFile, err := LoadEnvFile(loaderEnvFile(t, "SERVER_PORT=9090\n"))
if err != nil {
t.Fatalf("Failed to load env file: %v", err)
t.Fatalf("LoadEnvFile() error = %v", err)
}
// Modify, add, and delete variables
envFile.Set("VAR1", "new_value1")
envFile.Set("NEW_VAR", "new_value")
envFile.Del("VAR2")
err = envFile.Save(tmpFile)
if err != nil {
t.Fatalf("Failed to save env file: %v", err)
if port, _ := envFile.Get("SERVER_PORT"); port.Value != "9090" || port.Default != "8080" || !port.IsPresent() {
t.Errorf("SERVER_PORT = %+v, want the file's 9090 with default 8080", port)
}
if debug, ok := envFile.Get("DEBUG"); !ok || debug.Default != "false" {
t.Errorf("DEBUG = %+v, %v; want default false", debug, ok)
}
if db, ok := envFile.Get("DATABASE_URL"); !ok || db.Default != "postgres://pentagiuser:pentagipass@pgvector:5432/pentagidb?sslmode=disable" {
t.Errorf("DATABASE_URL = %+v, %v; want the bundled database default", db, ok)
}
if _, ok := envFile.Get("STATIC_URL"); ok {
t.Error("STATIC_URL declares no default and is not in the file, yet it was added")
}
// Check file content
savedContent, err := os.ReadFile(tmpFile)
if err != nil {
t.Fatalf("Failed to read saved file: %v", err)
}
contentStr := string(savedContent)
// Should contain updated and new variables
if !containsLine(contentStr, "VAR1=new_value1") {
t.Error("Expected VAR1 to be updated in saved file")
}
if !containsLine(contentStr, "NEW_VAR=new_value") {
t.Error("Expected NEW_VAR to be added to saved file")
}
if !containsLine(contentStr, "VAR3=value3") {
t.Error("Expected VAR3 to remain unchanged in saved file")
}
// Should not contain deleted variable
if containsLine(contentStr, "VAR2=value2") {
t.Error("Expected VAR2 to be removed from saved file")
}
// Cleanup backup
backupDir := filepath.Join(filepath.Dir(tmpFile), ".bak")
os.RemoveAll(backupDir)
}
func TestSetDefaultVarsNilURL(t *testing.T) {
envFile := &envFile{
vars: make(map[string]*EnvVar),
mx: &sync.Mutex{},
}
// This should not panic even with nil URL
err := setDefaultVars(envFile)
if err != nil {
t.Fatalf("setDefaultVars failed: %v", err)
}
// Check that STATIC_URL exists (it has envDefault empty, so should be nil URL)
if envVar, exists := envFile.vars["STATIC_URL"]; exists {
if envVar.Default != "" {
t.Errorf("Expected empty default for STATIC_URL, got '%s'", envVar.Default)
for name, envVar := range envFile.GetAll() {
if name != "SERVER_PORT" && (envVar.IsPresent() || envVar.Value != "" || envVar.IsChanged) {
t.Errorf("%s = %+v; a default must stay absent, empty and unchanged", name, envVar)
}
}
}
func TestSetDefaultVars(t *testing.T) {
envFile := &envFile{
vars: make(map[string]*EnvVar),
mx: &sync.Mutex{},
}
// This should not panic even with nil URL
err := setDefaultVars(envFile)
if err != nil {
t.Fatalf("setDefaultVars failed: %v", err)
}
// Check that all variables are not present and have default value the same as current value
for name, envVar := range envFile.vars {
if envVar.IsPresent() {
t.Errorf("Expected variable %s to be not present", name)
}
if !envVar.IsDefault() {
t.Errorf("Expected variable %s to have default value", name)
}
}
}
func createTempFile(t *testing.T, content string) string {
tmpFile, err := os.CreateTemp("", "test*.env")
if err != nil {
t.Fatalf("Failed to create temp file: %v", err)
}
if _, err := tmpFile.WriteString(content); err != nil {
t.Fatalf("Failed to write temp file: %v", err)
}
if err := tmpFile.Close(); err != nil {
t.Fatalf("Failed to close temp file: %v", err)
}
return tmpFile.Name()
}
+8 -1
View File
@@ -2,6 +2,7 @@ package main
import (
"context"
"errors"
"flag"
"fmt"
"log"
@@ -94,7 +95,13 @@ func parseFlags(args []string) Config {
fmt.Fprintf(os.Stderr, " %s -v # Show version\n", name)
}
flagSet.Parse(args)
if err := flagSet.Parse(args); err != nil {
if errors.Is(err, flag.ErrHelp) {
os.Exit(0)
}
os.Exit(2)
}
return config
}
+73 -134
View File
@@ -3,42 +3,25 @@ package main
import (
"os"
"path/filepath"
"runtime"
"strings"
"testing"
"pentagi/cmd/installer/files"
"pentagi/pkg/version"
)
func TestParseFlags(t *testing.T) {
func TestMain_ParseFlags_ReadsTheEnvPathAndVersionFlags(t *testing.T) {
tests := []struct {
name string
args []string
expectedEnv string
expectedVersion bool
}{
{
name: "default values",
args: []string{},
expectedEnv: ".env",
expectedVersion: false,
},
{
name: "custom env path",
args: []string{"-e", "config/.env"},
expectedEnv: "config/.env",
expectedVersion: false,
},
{
name: "version flag",
args: []string{"-v"},
expectedEnv: ".env",
expectedVersion: true,
},
{
name: "both flags",
args: []string{"-e", "test.env", "-v"},
expectedEnv: "test.env",
expectedVersion: true,
},
{name: "default values", args: []string{}, expectedEnv: ".env"},
{name: "custom env path", args: []string{"-e", "config/.env"}, expectedEnv: "config/.env"},
{name: "version flag", args: []string{"-v"}, expectedEnv: ".env", expectedVersion: true},
{name: "both flags", args: []string{"-e", "test.env", "-v"}, expectedEnv: "test.env", expectedVersion: true},
}
for _, tt := range tests {
@@ -46,144 +29,100 @@ func TestParseFlags(t *testing.T) {
config := parseFlags(append([]string{"test"}, tt.args...))
if config.envPath != tt.expectedEnv {
t.Errorf("Expected envPath %s, got %s", tt.expectedEnv, config.envPath)
t.Errorf("envPath = %q, want %q", config.envPath, tt.expectedEnv)
}
if config.showVersion != tt.expectedVersion {
t.Errorf("Expected showVersion %v, got %v", tt.expectedVersion, config.showVersion)
t.Errorf("showVersion = %v, want %v", config.showVersion, tt.expectedVersion)
}
})
}
}
func TestValidateEnvPath(t *testing.T) {
tmpDir := t.TempDir()
func TestMain_ValidateEnvPath_CreatesAMissingFileAndRefusesADirectory(t *testing.T) {
template, err := files.NewFiles().GetContent(".env")
if err != nil {
t.Fatalf("read the .env template: %v", err)
}
header := "# PentAGI Environment Configuration\n# Generated by PentAGI Installer v" + version.GetBinaryVersion() + "\n"
tmpDir := t.TempDir()
tests := []struct {
name string
path string
setup func() string
expectError bool
name string
path string
setup func(path string) error
created bool
wantErr string
}{
{
name: "existing file",
setup: func() string {
path := filepath.Join(tmpDir, "existing.env")
os.WriteFile(path, []byte("VAR=value"), 0644)
return path
},
expectError: false,
name: "an existing file is kept as it is",
path: "existing.env",
setup: func(path string) error { return os.WriteFile(path, []byte("VAR=value"), 0o600) },
},
{name: "a missing file is created from the template", path: "new.env", created: true},
{name: "a missing directory is created with it", path: "nonexistent/file.env", created: true},
{
name: "non-existent file in existing directory",
setup: func() string {
return filepath.Join(tmpDir, "new.env")
},
expectError: false,
},
{
name: "non-existent directory",
setup: func() string {
return filepath.Join(tmpDir, "nonexistent", "file.env")
},
expectError: false,
},
{
name: "directory instead of file",
setup: func() string {
os.Mkdir(filepath.Join(tmpDir, "dir"), 0755)
return filepath.Join(tmpDir, "dir")
},
expectError: true,
name: "a directory in place of the file is refused",
path: "dir",
setup: func(path string) error { return os.Mkdir(path, 0o755) },
wantErr: "is a directory",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
path := tt.setup()
path := filepath.Join(tmpDir, filepath.FromSlash(tt.path))
if tt.setup != nil {
if err := tt.setup(path); err != nil {
t.Fatalf("setup: %v", err)
}
}
result, err := validateEnvPath(path)
got, err := validateEnvPath(path)
if tt.wantErr != "" {
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
t.Fatalf("validateEnvPath() error = %v, want it to mention %q", err, tt.wantErr)
}
return
}
if err != nil || got != path {
t.Fatalf("validateEnvPath() = %q, %v; want %q", got, err, path)
}
if tt.expectError {
if err == nil {
t.Error("Expected error but got none")
}
} else {
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
if result == "" {
t.Error("Expected non-empty result path")
}
// Check that file exists after validation
if _, err := os.Stat(result); os.IsNotExist(err) {
t.Error("Expected file to exist after validation")
content, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read env file: %v", err)
}
if !tt.created {
if string(content) != "VAR=value" {
t.Errorf("existing env file was rewritten: %q", content)
}
return
}
if !strings.HasPrefix(string(content), header) || !strings.HasSuffix(string(content), string(template)) {
t.Errorf("created env file is not the header followed by the template:\n%.200s", content)
}
info, err := os.Stat(path)
if err != nil {
t.Fatalf("stat env file: %v", err)
}
if runtime.GOOS != "windows" && info.Mode().Perm() != 0o600 {
t.Errorf("created env file mode = %v, want -rw-------", info.Mode().Perm())
}
})
}
}
func TestCreateEmptyEnvFile(t *testing.T) {
tmpDir := t.TempDir()
path := filepath.Join(tmpDir, "test.env")
err := createInitialEnvFile(path)
if err != nil {
t.Fatalf("Failed to create empty env file: %v", err)
}
// Check file exists
if _, err := os.Stat(path); os.IsNotExist(err) {
t.Error("Expected file to be created")
}
// Check file content
content, err := os.ReadFile(path)
if err != nil {
t.Fatalf("Failed to read created file: %v", err)
}
contentStr := string(content)
if !containsString(contentStr, "PentAGI Environment Configuration") {
t.Error("Expected file to contain header comment")
}
if !containsString(contentStr, version.GetBinaryVersion()) {
t.Error("Expected file to contain version")
}
}
func TestInitializeState(t *testing.T) {
tmpDir := t.TempDir()
envPath := filepath.Join(tmpDir, "test.env")
// Create test env file
err := os.WriteFile(envPath, []byte("VAR1=value1"), 0644)
if err != nil {
t.Fatalf("Failed to create test env file: %v", err)
func TestMain_InitializeState_LoadsTheEnvFile(t *testing.T) {
envPath := filepath.Join(t.TempDir(), "test.env")
if err := os.WriteFile(envPath, []byte("VAR1=value1"), 0o600); err != nil {
t.Fatalf("write env file: %v", err)
}
state, err := initializeState(envPath)
if err != nil {
t.Fatalf("Failed to initialize state: %v", err)
if err != nil || state == nil {
t.Fatalf("initializeState() = %v, %v", state, err)
}
if state == nil {
t.Error("Expected non-nil state")
}
// Test that state can access variables
envVar, exists := state.GetVar("VAR1")
if !exists {
t.Error("Expected VAR1 to exist in state")
}
if envVar.Value != "value1" {
t.Errorf("Expected VAR1 value 'value1', got '%s'", envVar.Value)
if envVar, exists := state.GetVar("VAR1"); !exists || envVar.Value != "value1" {
t.Errorf("GetVar(VAR1) = %q, %v; want %q, true", envVar.Value, exists, "value1")
}
}
func containsString(s, substr string) bool {
return len(s) >= len(substr) &&
(s == substr ||
containsString(s[1:], substr) ||
(len(s) > 0 && s[:len(substr)] == substr))
}
+3 -3
View File
@@ -42,7 +42,7 @@ func NewNavigator(state state.State, checkResult checker.CheckResult) Navigator
logger.Log("[Nav] NEW: %s", strings.Join(state.GetStack(), " -> "))
if !checkResult.IsReadyToContinue() {
state.SetStack([]string{string(models.WelcomeScreen)})
_ = state.SetStack([]string{string(models.WelcomeScreen)})
return &navigator{
stack: []models.ScreenID{models.WelcomeScreen},
stateManager: state,
@@ -63,7 +63,7 @@ func NewNavigator(state state.State, checkResult checker.CheckResult) Navigator
func (n *navigator) Push(screenID models.ScreenID) {
logger.Log("[Nav] PUSH: %s -> %s", n.Current(), screenID)
n.stack = append(n.stack, screenID)
n.stateManager.SetStack(n.stack.Strings())
_ = n.stateManager.SetStack(n.stack.Strings())
}
func (n *navigator) Pop() models.ScreenID {
@@ -74,7 +74,7 @@ func (n *navigator) Pop() models.ScreenID {
n.stack = n.stack[:len(n.stack)-1]
previous := n.Current()
n.stateManager.SetStack(n.stack.Strings())
_ = n.stateManager.SetStack(n.stack.Strings())
logger.Log("[Nav] POP: %s -> %s", current, previous)
return previous
}
@@ -319,3 +319,5 @@ func TestStateIntegrationWithExistingStack(t *testing.T) {
t.Errorf("expected 2 screens in navigator stack, got %v", nav.GetStack())
}
}
func (m *mockState) WriteVars(map[string]string) error { return nil }
+66 -1
View File
@@ -6,6 +6,7 @@ import (
"os"
"os/exec"
"path/filepath"
"strings"
"time"
)
@@ -60,11 +61,28 @@ func (c *composeOperationsImpl) restartStack(ctx context.Context, stack ProductS
}
// updateStack performs rolling update with health checks (also used for install)
// updateStack and downloadStack are the only two compose operations that FETCH anything,
// and both write the image references the server chose into the environment file first.
//
// Here rather than at each call site, because there are five of them — update, download,
// install and the three apply-changes phases — and the one that forgets is not a compile
// error: `${COMPONENT_IMAGE:-default}` quietly resolves to the default the compose file
// ships with, the pull fetches that, and the operation reports success having fetched
// something the update server never offered.
//
// The tear-down operations below deliberately do not: `down` needs no reference, and
// writing one while removing a stack would be a side effect nobody asked for.
func (c *composeOperationsImpl) updateStack(ctx context.Context, stack ProductStack, state *operationState) error {
if err := c.processor.applyPullReferences(stack); err != nil {
return err
}
return c.performStackOperation(ctx, stack, state, ProcessorOperationUpdate, "up", "-d")
}
func (c *composeOperationsImpl) downloadStack(ctx context.Context, stack ProductStack, state *operationState) error {
if err := c.processor.applyPullReferences(stack); err != nil {
return err
}
return c.performStackOperation(ctx, stack, state, ProcessorOperationDownload, "pull")
}
@@ -86,13 +104,29 @@ func (c *composeOperationsImpl) performStackOperation(
) error {
switch stack {
case ProductStackPentagi:
// destructive operations cannot run without the compose file and have
// nothing to act on when the stack was never extracted
if isDestructiveComposeOperation(operation) && !c.composeFileExists(stack) {
return nil
}
return c.wrapPerformStackCommand(ctx, stack, state, operation, args...)
case ProductStackLangfuse, ProductStackObservability, ProductStackGraphiti:
switch operation {
// for destructive operations we must always allow compose to run, even if stack is disabled/external now
case ProcessorOperationRemove, ProcessorOperationPurge, ProcessorOperationStop:
return c.wrapPerformStackCommand(ctx, stack, state, operation, args...)
// but only if the compose file exists; a missing file means the stack
// was never extracted and there is nothing for compose to remove
if !c.composeFileExists(stack) {
return nil
}
// execute the operation, but if it fails due to missing compose file, treat as success
// (this handles race conditions or path calculation issues)
err := c.wrapPerformStackCommand(ctx, stack, state, operation, args...)
if err != nil && c.isComposeMissingError(err) {
return nil
}
return err
// for non-destructive operations (start/update/download) honor embedded mode only
default:
if c.processor.isEmbeddedDeployment(stack) {
@@ -163,6 +197,37 @@ func (c *composeOperationsImpl) performStackCommand(
return c.processor.runCommand(cmd, stack, state)
}
// isDestructiveComposeOperation reports whether the operation tears a stack down
// (and therefore may target a stack that is disabled/external/never extracted)
func isDestructiveComposeOperation(operation ProcessorOperation) bool {
switch operation {
case ProcessorOperationRemove, ProcessorOperationPurge, ProcessorOperationStop:
return true
default:
return false
}
}
// composeFileExists reports whether the stack's compose file is present on disk;
// destructive operations cannot run (and have nothing to remove) without it
func (c *composeOperationsImpl) composeFileExists(stack ProductStack) bool {
composeFile, err := c.determineComposeFile(stack)
if err != nil {
return false
}
composePath := filepath.Join(filepath.Dir(c.processor.state.GetEnvPath()), composeFile)
return c.processor.isFileExists(composePath) == nil
}
// isComposeMissingError checks if an error is due to a missing compose file
func (c *composeOperationsImpl) isComposeMissingError(err error) bool {
if err == nil {
return false
}
errMsg := err.Error()
return strings.Contains(errMsg, "does not exist") || strings.Contains(errMsg, "no such file")
}
func (c *composeOperationsImpl) determineComposeFile(stack ProductStack) (string, error) {
switch stack {
case ProductStackPentagi:
@@ -0,0 +1,69 @@
package processor
import (
"context"
"errors"
"os"
"path/filepath"
"testing"
"pentagi/cmd/installer/state"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestCompose_IsComposeMissingError_RecognisesOnlyAMissingFile(t *testing.T) {
c := &composeOperationsImpl{}
for _, tc := range []struct {
name string
err error
want bool
}{
{"no error", nil, false},
{"a file that does not exist", os.ErrNotExist, true},
{"a path that does not exist", &os.PathError{Op: "open", Path: "/path/to/file", Err: os.ErrNotExist}, true},
{"docker compose naming a missing file", errors.New("open docker-compose-graphiti.yml: no such file or directory"), true},
{"permission denied", os.ErrPermission, false},
} {
t.Run(tc.name, func(t *testing.T) {
assert.Equal(t, tc.want, c.isComposeMissingError(tc.err))
})
}
}
func TestCompose_PerformStackOperation_SkipsATearDownWithNoComposeFile(t *testing.T) {
envPath := filepath.Join(t.TempDir(), ".env")
require.NoError(t, os.WriteFile(envPath, []byte("GRAPHITI_URL=http://localhost:8000\n"), 0o644))
appState, err := state.NewState(envPath)
require.NoError(t, err)
c := newComposeOperations(&processor{state: appState}).(*composeOperationsImpl)
require.False(t, c.composeFileExists(ProductStackGraphiti), "no docker-compose-graphiti.yml was written")
opState := testOperationState(t)
require.NoError(t, c.performStackOperation(t.Context(), ProductStackGraphiti, opState, ProcessorOperationStop, "stop"))
assert.Empty(t, opState.msgs, "the stop was announced, so compose was about to run without its file")
}
// Subtests are keyed by unit: the two that fetch write the server's references, the two that tear down none.
func TestCompose_OnlyTheFetchingOperationsWriteThePullReferences(t *testing.T) {
chosen := map[string]string{"PENTAGI_IMAGE": "vxcontrol/pentagi:2.3.4"}
for _, tc := range []struct {
name string
run func(composeOperations, context.Context, ProductStack, *operationState) error
want map[string]string
}{
{"an update writes the reference before pulling", composeOperations.updateStack, chosen},
{"a download writes the reference before pulling", composeOperations.downloadStack, chosen},
{"a removal writes nothing", composeOperations.removeStack, nil},
{"a purge writes nothing", composeOperations.purgeStack, nil},
} {
t.Run(tc.name, func(t *testing.T) {
p, state := processorWithPullReference(t)
// No compose file exists, so `.env` is asserted as it stood when compose was reached.
_ = tc.run(p.composeOps, t.Context(), ProductStackPentagi, testOperationState(t))
assert.Equal(t, tc.want, state.written)
})
}
}
+62 -36
View File
@@ -8,12 +8,12 @@ import (
"path/filepath"
"strings"
"pentagi/pkg/docker"
"pentagi/pkg/tools"
cerrdefs "github.com/containerd/errdefs"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/image"
"github.com/docker/docker/api/types/network"
"github.com/docker/docker/api/types/volume"
"github.com/docker/docker/client"
"github.com/moby/moby/api/types/container"
"github.com/moby/moby/client"
)
type dockerOperationsImpl struct {
@@ -56,15 +56,24 @@ func (d *dockerOperationsImpl) removeWorkerContainers(ctx context.Context, state
d.processor.appendLog(MsgRemovingWorkerContainers, ProductStackWorker, state)
allContainers, err := cli.ContainerList(ctx, container.ListOptions{All: true})
allContainers, err := cli.ContainerList(ctx, client.ContainerListOptions{All: true})
if err != nil {
return fmt.Errorf("failed to list worker containers: %w", err)
}
// NOTE: docker returns names with a leading slash ("/pentagi-terminal-1"), so
// this predicate has never matched anything and the sweep is effectively a
// no-op today. It is left that way deliberately — "fixing" the slash would
// silently turn a dormant no-op into force-removal of running containers,
// which is a behavior change well beyond tenant isolation.
//
// The prefix is anchored on the tenant regardless, so that if the slash is
// ever handled the sweep can only ever reach this instance's own containers.
workerPrefix := d.tenantPrefix() + "pentagi-"
var containers []container.Summary
for _, c := range allContainers {
for _, c := range allContainers.Items {
for _, name := range c.Names {
if strings.HasPrefix(name, "pentagi-") {
if strings.HasPrefix(name, workerPrefix) {
containers = append(containers, c)
break
}
@@ -80,13 +89,13 @@ func (d *dockerOperationsImpl) removeWorkerContainers(ctx context.Context, state
for _, cont := range containers {
if cont.State == "running" {
d.processor.appendLog(fmt.Sprintf(MsgStoppingContainer, cont.ID[:12]), ProductStackWorker, state)
if err := cli.ContainerStop(ctx, cont.ID, container.StopOptions{}); err != nil {
if _, err := cli.ContainerStop(ctx, cont.ID, client.ContainerStopOptions{}); err != nil {
return fmt.Errorf("failed to stop worker container %s: %w", cont.ID, err)
}
}
d.processor.appendLog(fmt.Sprintf(MsgRemovingContainer, cont.ID[:12]), ProductStackWorker, state)
if err := cli.ContainerRemove(ctx, cont.ID, container.RemoveOptions{
if _, err := cli.ContainerRemove(ctx, cont.ID, client.ContainerRemoveOptions{
Force: true,
}); err != nil {
return fmt.Errorf("failed to remove worker container %s: %w", cont.ID, err)
@@ -100,21 +109,21 @@ func (d *dockerOperationsImpl) removeWorkerContainers(ctx context.Context, state
}
func (d *dockerOperationsImpl) removeWorkerImages(ctx context.Context, state *operationState) error {
return d.removeImages(ctx, state, image.RemoveOptions{
return d.removeImages(ctx, state, client.ImageRemoveOptions{
Force: false,
PruneChildren: false,
})
}
func (d *dockerOperationsImpl) purgeWorkerImages(ctx context.Context, state *operationState) error {
return d.removeImages(ctx, state, image.RemoveOptions{
return d.removeImages(ctx, state, client.ImageRemoveOptions{
Force: true,
PruneChildren: true,
})
}
func (d *dockerOperationsImpl) removeImages(
ctx context.Context, state *operationState, options image.RemoveOptions,
ctx context.Context, state *operationState, options client.ImageRemoveOptions,
) error {
if err := d.removeWorkerContainers(ctx, state); err != nil {
return err
@@ -146,19 +155,16 @@ func (d *dockerOperationsImpl) removeImages(
// createMainDockerClient creates docker client for the main stack (non-worker) using current process env
func (d *dockerOperationsImpl) createMainDockerClient() (*client.Client, error) {
return client.NewClientWithOpts(
client.FromEnv,
client.WithAPIVersionNegotiation(),
)
return client.New(client.FromEnv)
}
// checkMainDockerNetwork returns true if a docker network with given name exists
func (d *dockerOperationsImpl) checkMainDockerNetwork(ctx context.Context, cli *client.Client, name string) (bool, error) {
nets, err := cli.NetworkList(ctx, network.ListOptions{})
nets, err := cli.NetworkList(ctx, client.NetworkListOptions{})
if err != nil {
return false, fmt.Errorf("failed to list docker networks: %w", err)
}
for _, n := range nets {
for _, n := range nets.Items {
if n.Name == name {
return true, nil
}
@@ -174,8 +180,9 @@ func (d *dockerOperationsImpl) createMainDockerNetwork(ctx context.Context, cli
}
if exists {
// inspect to validate labels
nw, err := cli.NetworkInspect(ctx, name, network.InspectOptions{})
inspectResult, err := cli.NetworkInspect(ctx, name, client.NetworkInspectOptions{})
if err == nil {
nw := inspectResult.Network
wantProject := ""
if envPath := d.processor.state.GetEnvPath(); envPath != "" {
wantProject = filepath.Base(filepath.Dir(envPath))
@@ -192,7 +199,7 @@ func (d *dockerOperationsImpl) createMainDockerNetwork(ctx context.Context, cli
return nil
}
d.processor.appendLog(fmt.Sprintf(MsgRecreatingDockerNetwork, name), ProductStackInstaller, state)
if err := cli.NetworkRemove(ctx, nw.ID); err != nil {
if _, err := cli.NetworkRemove(ctx, nw.ID, client.NetworkRemoveOptions{}); err != nil {
d.processor.appendLog(fmt.Sprintf(MsgDockerNetworkRemoveFailed, name, err), ProductStackInstaller, state)
return fmt.Errorf("failed to remove network %s: %w", name, err)
}
@@ -213,7 +220,7 @@ func (d *dockerOperationsImpl) createMainDockerNetwork(ctx context.Context, cli
labels["com.docker.compose.project"] = projectName
}
// driver: bridge (compose default for local networks)
_, err = cli.NetworkCreate(ctx, name, network.CreateOptions{
_, err = cli.NetworkCreate(ctx, name, client.NetworkCreateOptions{
Driver: "bridge",
Labels: labels,
})
@@ -267,17 +274,21 @@ func (d *dockerOperationsImpl) removeMainDockerNetwork(ctx context.Context, stat
defer cli.Close()
// try inspect; if not found just return
nw, err := cli.NetworkInspect(ctx, name, network.InspectOptions{})
inspectResult, err := cli.NetworkInspect(ctx, name, client.NetworkInspectOptions{})
if err != nil {
return nil
}
// attempt to disconnect all containers first (best effort)
nw := inspectResult.Network
for id := range nw.Containers {
_ = cli.NetworkDisconnect(ctx, nw.ID, id, true)
_, _ = cli.NetworkDisconnect(ctx, nw.ID, client.NetworkDisconnectOptions{
Container: id,
Force: true,
})
}
if err := cli.NetworkRemove(ctx, nw.ID); err != nil {
if _, err := cli.NetworkRemove(ctx, nw.ID, client.NetworkRemoveOptions{}); err != nil {
return err
}
d.processor.appendLog(fmt.Sprintf(MsgDockerNetworkRemoved, name), ProductStackInstaller, state)
@@ -296,7 +307,7 @@ func (d *dockerOperationsImpl) removeMainImages(ctx context.Context, state *oper
}
defer cli.Close()
opts := image.RemoveOptions{Force: state.force, PruneChildren: state.force}
opts := client.ImageRemoveOptions{Force: state.force, PruneChildren: state.force}
for _, img := range images {
if img == "" {
continue
@@ -319,22 +330,26 @@ func (d *dockerOperationsImpl) removeWorkerVolumes(ctx context.Context, state *o
}
defer cli.Close()
vols, err := cli.VolumeList(ctx, volume.ListOptions{})
vols, err := cli.VolumeList(ctx, client.VolumeListOptions{})
if err != nil {
return err
}
for _, v := range vols.Volumes {
if strings.HasPrefix(v.Name, "pentagi-terminal-") && strings.HasSuffix(v.Name, "-data") {
_ = cli.VolumeRemove(ctx, v.Name, true)
// Anchor on this instance's own prefix. Because the tenant segment leads the
// name ("acme-pentagi-terminal-1-data"), a default installation's sweep does
// not match a tenant's volumes and vice versa — each purge reaches exactly
// its own resources. With TENANT_ID unset this is the original predicate.
workerPrefix := d.tenantPrefix() + tools.PrimaryTerminalNamePrefix
workerSuffix := docker.WorkerVolumeNameSuffix
for _, v := range vols.Items {
if strings.HasPrefix(v.Name, workerPrefix) && strings.HasSuffix(v.Name, workerSuffix) {
_, _ = cli.VolumeRemove(ctx, v.Name, client.VolumeRemoveOptions{Force: true})
}
}
return nil
}
func (d *dockerOperationsImpl) createWorkerDockerClient() (*client.Client, error) {
opts := []client.Opt{
client.WithAPIVersionNegotiation(),
}
var opts []client.Opt
envVar, exists := d.processor.state.GetVar(client.EnvOverrideHost)
if exists && (envVar.Value != "" || envVar.IsChanged) {
@@ -363,15 +378,15 @@ func (d *dockerOperationsImpl) createWorkerDockerClient() (*client.Client, error
envVar, exists = d.processor.state.GetVar("PENTAGI_" + client.EnvOverrideCertPath)
if exists && (envVar.Value != "" || envVar.IsChanged) {
cfg := getTLSConfig(envVar.Value)
opts = append(opts, client.WithTLSClientConfig(cfg.certPath, cfg.keyPath, cfg.caPath))
opts = append(opts, client.WithTLSClientConfig(cfg.caPath, cfg.certPath, cfg.keyPath))
} else if envVar.Default != "" {
cfg := getTLSConfig(envVar.Default)
opts = append(opts, client.WithTLSClientConfig(cfg.certPath, cfg.keyPath, cfg.caPath))
opts = append(opts, client.WithTLSClientConfig(cfg.caPath, cfg.certPath, cfg.keyPath))
} else {
opts = append(opts, client.WithTLSClientConfigFromEnv())
}
return client.NewClientWithOpts(opts...)
return client.New(opts...)
}
func (d *dockerOperationsImpl) getWorkerDockerEnv() []string {
@@ -407,6 +422,17 @@ func (d *dockerOperationsImpl) getWorkerDockerEnv() []string {
return env
}
// tenantPrefix returns this installation's tenant prefix ("acme-") or "" when
// TENANT_ID is unset. Every daemon-wide sweep must anchor on it so that a purge
// run for one instance cannot reach another instance's resources.
func (d *dockerOperationsImpl) tenantPrefix() string {
envVar, exists := d.processor.state.GetVar("TENANT_ID")
if !exists || envVar.Value == "" {
return ""
}
return envVar.Value + "-"
}
func (d *dockerOperationsImpl) getWorkerImageName() string {
envVar, exists := d.processor.state.GetVar("DOCKER_DEFAULT_IMAGE_FOR_PENTEST")
if exists && envVar.Value != "" {
@@ -0,0 +1,651 @@
package processor
import (
"context"
"io/fs"
"os"
"path/filepath"
"sync"
"testing"
"time"
"pentagi/cmd/installer/checker"
"pentagi/cmd/installer/files"
"pentagi/cmd/installer/loader"
"github.com/stretchr/testify/require"
)
// mockState implements state.State over a map, with the environment file in a temp dir.
type mockState struct {
vars map[string]loader.EnvVar
envPath string
stack []string
dirty bool
// written stands in for the environment file on disk — the one `docker compose
// --env-file` reads. Only WriteVars puts anything here; SetVars stages.
written map[string]string
// onReset runs inside Reset: the real Reset re-reads the file, so when it runs matters.
onReset func()
}
func newMockState(t *testing.T) *mockState {
t.Helper()
envPath := filepath.Join(t.TempDir(), ".env")
require.NoError(t, os.WriteFile(envPath, []byte("PENTAGI_VERSION=1.0.0\n"), 0o644))
return &mockState{vars: make(map[string]loader.EnvVar), envPath: envPath}
}
func (m *mockState) Reset() error {
if m.onReset != nil {
m.onReset()
}
m.dirty = false
return nil
}
func (m *mockState) Exists() bool { return true }
func (m *mockState) Commit() error { m.dirty = false; return nil }
func (m *mockState) IsDirty() bool { return m.dirty }
func (m *mockState) GetEulaConsent() bool { return true }
func (m *mockState) SetEulaConsent() error { return nil }
func (m *mockState) SetStack(stack []string) error { m.stack = stack; return nil }
func (m *mockState) GetStack() []string { return m.stack }
func (m *mockState) GetVar(name string) (loader.EnvVar, bool) { v, ok := m.vars[name]; return v, ok }
func (m *mockState) SetVar(name, value string) error {
m.vars[name] = loader.EnvVar{Name: name, Value: value}
m.dirty = true
return nil
}
func (m *mockState) ResetVar(name string) error { delete(m.vars, name); return nil }
func (m *mockState) GetVars(names []string) (map[string]loader.EnvVar, map[string]bool) {
result := make(map[string]loader.EnvVar)
present := make(map[string]bool)
for _, name := range names {
v, ok := m.vars[name]
result[name] = v
present[name] = ok
}
return result, present
}
func (m *mockState) SetVars(vars map[string]string) error {
for name, value := range vars {
m.vars[name] = loader.EnvVar{Name: name, Value: value}
}
m.dirty = true
return nil
}
// WriteVars records into `written` and leaves the state clean: a double that cannot tell
// staging from writing cannot catch a staged image reference compose never sees.
func (m *mockState) WriteVars(vars map[string]string) error {
if m.written == nil {
m.written = make(map[string]string, len(vars))
}
for name, value := range vars {
m.written[name] = value
m.vars[name] = loader.EnvVar{Name: name, Value: value}
}
return nil
}
func (m *mockState) ResetVars(names []string) error {
for _, name := range names {
delete(m.vars, name)
}
return nil
}
func (m *mockState) GetAllVars() map[string]loader.EnvVar { return m.vars }
func (m *mockState) GetEnvPath() string { return m.envPath }
// mockFiles implements files.Files: `lists` are embedded directories, `content` embedded
// files, `statuses` what Check answers (OK when unset), and every Copy is recorded and
// answers `copyErr`.
type mockFiles struct {
content map[string][]byte
statuses map[string]files.FileStatus
lists map[string][]string
copyErr error
copies []struct {
Src, Dst string
Rewrite bool
}
}
func newMockFiles() *mockFiles {
return &mockFiles{
content: make(map[string][]byte),
statuses: make(map[string]files.FileStatus),
lists: make(map[string][]string),
}
}
func (m *mockFiles) GetContent(name string) ([]byte, error) {
if content, ok := m.content[name]; ok {
return content, nil
}
return nil, &os.PathError{Op: "read", Path: name, Err: os.ErrNotExist}
}
func (m *mockFiles) Exists(name string) bool {
_, isFile := m.content[name]
_, isDir := m.lists[name]
return isFile || isDir
}
func (m *mockFiles) ExistsInFS(name string) bool { return false }
func (m *mockFiles) Stat(name string) (fs.FileInfo, error) {
if _, exists := m.lists[name]; exists {
return &mockFileInfo{name: name, isDir: true}, nil
}
if _, exists := m.content[name]; exists {
return &mockFileInfo{name: name, isDir: false}, nil
}
return nil, &os.PathError{Op: "stat", Path: name, Err: os.ErrNotExist}
}
func (m *mockFiles) Copy(src, dst string, rewrite bool) error {
m.copies = append(m.copies, struct {
Src, Dst string
Rewrite bool
}{Src: src, Dst: dst, Rewrite: rewrite})
return m.copyErr
}
func (m *mockFiles) Check(name string, workingDir string) files.FileStatus {
if status, exists := m.statuses[name]; exists {
return status
}
return files.FileStatusOK
}
func (m *mockFiles) List(prefix string) ([]string, error) {
return m.lists[prefix], nil
}
func (m *mockFiles) AddFile(name string, content []byte) {
m.content[name] = content
}
type mockFileInfo struct {
name string
isDir bool
}
func (m *mockFileInfo) Name() string { return m.name }
func (m *mockFileInfo) Size() int64 { return 100 }
func (m *mockFileInfo) Mode() fs.FileMode { return 0o644 }
func (m *mockFileInfo) ModTime() time.Time { return time.Now() }
func (m *mockFileInfo) IsDir() bool { return m.isDir }
func (m *mockFileInfo) Sys() interface{} { return nil }
// call is one recorded call on an operations double.
type call struct {
Method string
Stack ProductStack
Name string // the network, for docker network operations
Args []string // the compose arguments, for performStackCommand
Force bool // the operation state's force, for the file system operations
Error error
}
// processorCallRecorder is what every operations double shares: the calls it saw and the
// errors a test injected, keyed by method.
type processorCallRecorder struct {
mu sync.Mutex
calls []call
errOn map[string]error
}
func (m *processorCallRecorder) getCalls() []call {
m.mu.Lock()
defer m.mu.Unlock()
return append([]call(nil), m.calls...)
}
func (m *processorCallRecorder) setError(method string, err error) {
m.mu.Lock()
defer m.mu.Unlock()
if m.errOn == nil {
m.errOn = make(map[string]error)
}
m.errOn[method] = err
}
// do records c and answers ctxErr — a done context fails a command or a daemon call
// started under it — or else the injected error. An injected error is spent by its first
// use when oneShot is set.
func (m *processorCallRecorder) do(c call, ctxErr error, oneShot bool) error {
m.mu.Lock()
defer m.mu.Unlock()
c.Error = ctxErr
if c.Error == nil {
if err, ok := m.errOn[c.Method+"_"+string(c.Stack)]; ok {
c.Error = err
} else if err, ok := m.errOn[c.Method]; ok {
c.Error = err
if oneShot {
delete(m.errOn, c.Method)
}
}
}
m.calls = append(m.calls, c)
return c.Error
}
// baseMockFileSystemOperations ignores its context, as the real file operations do, and
// records force, which decides whether a file the user edited is overwritten. An error is
// injected for one method ("ensureStackIntegrity") or one stack of it
// ("ensureStackIntegrity_langfuse"), the latter taking precedence.
type baseMockFileSystemOperations struct{ processorCallRecorder }
func (m *baseMockFileSystemOperations) ensureStackIntegrity(_ context.Context, stack ProductStack, state *operationState) error {
return m.do(call{Method: "ensureStackIntegrity", Stack: stack, Force: state.force}, nil, false)
}
func (m *baseMockFileSystemOperations) verifyStackIntegrity(_ context.Context, stack ProductStack, state *operationState) error {
return m.do(call{Method: "verifyStackIntegrity", Stack: stack, Force: state.force}, nil, false)
}
func (m *baseMockFileSystemOperations) checkStackIntegrity(_ context.Context, stack ProductStack) (FilesCheckResult, error) {
if err := m.do(call{Method: "checkStackIntegrity", Stack: stack}, nil, false); err != nil {
return nil, err
}
return FilesCheckResult{}, nil
}
func (m *baseMockFileSystemOperations) cleanupStackFiles(_ context.Context, stack ProductStack, _ *operationState) error {
return m.do(call{Method: "cleanupStackFiles", Stack: stack}, nil, false)
}
// baseMockDockerOperations records the network name for the network operations.
type baseMockDockerOperations struct{ processorCallRecorder }
func (m *baseMockDockerOperations) pullWorkerImage(ctx context.Context, _ *operationState) error {
return m.do(call{Method: "pullWorkerImage"}, ctx.Err(), false)
}
func (m *baseMockDockerOperations) pullDefaultImage(ctx context.Context, _ *operationState) error {
return m.do(call{Method: "pullDefaultImage"}, ctx.Err(), false)
}
func (m *baseMockDockerOperations) removeWorkerContainers(ctx context.Context, _ *operationState) error {
return m.do(call{Method: "removeWorkerContainers"}, ctx.Err(), false)
}
func (m *baseMockDockerOperations) removeWorkerImages(ctx context.Context, _ *operationState) error {
return m.do(call{Method: "removeWorkerImages"}, ctx.Err(), false)
}
func (m *baseMockDockerOperations) purgeWorkerImages(ctx context.Context, _ *operationState) error {
return m.do(call{Method: "purgeWorkerImages"}, ctx.Err(), false)
}
func (m *baseMockDockerOperations) ensureMainDockerNetworks(ctx context.Context, _ *operationState) error {
return m.do(call{Method: "ensureMainDockerNetworks"}, ctx.Err(), false)
}
func (m *baseMockDockerOperations) removeMainDockerNetwork(ctx context.Context, _ *operationState, name string) error {
return m.do(call{Method: "removeMainDockerNetwork", Name: name}, ctx.Err(), false)
}
func (m *baseMockDockerOperations) removeMainImages(ctx context.Context, _ *operationState, _ []string) error {
return m.do(call{Method: "removeMainImages"}, ctx.Err(), false)
}
func (m *baseMockDockerOperations) removeWorkerVolumes(ctx context.Context, _ *operationState) error {
return m.do(call{Method: "removeWorkerVolumes"}, ctx.Err(), false)
}
// baseMockComposeOperations spends an injected error on its first use, so a fan-out fails
// on its first stack and goes on with the rest.
type baseMockComposeOperations struct{ processorCallRecorder }
func (m *baseMockComposeOperations) startStack(ctx context.Context, stack ProductStack, _ *operationState) error {
return m.do(call{Method: "startStack", Stack: stack}, ctx.Err(), true)
}
func (m *baseMockComposeOperations) stopStack(ctx context.Context, stack ProductStack, _ *operationState) error {
return m.do(call{Method: "stopStack", Stack: stack}, ctx.Err(), true)
}
func (m *baseMockComposeOperations) restartStack(ctx context.Context, stack ProductStack, _ *operationState) error {
return m.do(call{Method: "restartStack", Stack: stack}, ctx.Err(), true)
}
func (m *baseMockComposeOperations) updateStack(ctx context.Context, stack ProductStack, _ *operationState) error {
return m.do(call{Method: "updateStack", Stack: stack}, ctx.Err(), true)
}
func (m *baseMockComposeOperations) downloadStack(ctx context.Context, stack ProductStack, _ *operationState) error {
return m.do(call{Method: "downloadStack", Stack: stack}, ctx.Err(), true)
}
func (m *baseMockComposeOperations) removeStack(ctx context.Context, stack ProductStack, _ *operationState) error {
return m.do(call{Method: "removeStack", Stack: stack}, ctx.Err(), true)
}
func (m *baseMockComposeOperations) purgeStack(ctx context.Context, stack ProductStack, _ *operationState) error {
return m.do(call{Method: "purgeStack", Stack: stack}, ctx.Err(), true)
}
func (m *baseMockComposeOperations) purgeImagesStack(ctx context.Context, stack ProductStack, _ *operationState) error {
return m.do(call{Method: "purgeImagesStack", Stack: stack}, ctx.Err(), true)
}
func (m *baseMockComposeOperations) determineComposeFile(stack ProductStack) (string, error) {
return "test-compose.yml", m.do(call{Method: "determineComposeFile", Stack: stack}, nil, true)
}
// performStackCommand records its arguments: "restart jaeger" and "up -d" are otherwise
// the same call.
func (m *baseMockComposeOperations) performStackCommand(ctx context.Context, stack ProductStack, _ *operationState, args ...string) error {
return m.do(call{Method: "performStackCommand", Stack: stack, Args: args}, ctx.Err(), true)
}
// baseMockUpdateOperations reports jaegerPluginReplaced from updateJaegerPlugin, which
// decides whether the caller restarts the Jaeger service.
type baseMockUpdateOperations struct {
processorCallRecorder
jaegerPluginReplaced bool
}
func (m *baseMockUpdateOperations) checkUpdates(ctx context.Context, _ *operationState) error {
return m.do(call{Method: "checkUpdates"}, ctx.Err(), false)
}
func (m *baseMockUpdateOperations) downloadInstaller(ctx context.Context, _ *operationState) error {
return m.do(call{Method: "downloadInstaller"}, ctx.Err(), false)
}
func (m *baseMockUpdateOperations) updateInstaller(ctx context.Context, _ *operationState) error {
return m.do(call{Method: "updateInstaller"}, ctx.Err(), false)
}
func (m *baseMockUpdateOperations) removeInstaller(ctx context.Context, _ *operationState) error {
return m.do(call{Method: "removeInstaller"}, ctx.Err(), false)
}
func (m *baseMockUpdateOperations) updateJaegerPlugin(ctx context.Context, _ *operationState) (bool, error) {
if err := m.do(call{Method: "updateJaegerPlugin"}, ctx.Err(), false); err != nil {
return false, err
}
return m.jaegerPluginReplaced, nil
}
func (m *baseMockUpdateOperations) installerPackage(ctx context.Context) (*InstallerPackage, error) {
if err := m.do(call{Method: "installerPackage"}, ctx.Err(), false); err != nil {
return nil, err
}
return &InstallerPackage{Version: "1.2.3", OS: "linux", Arch: "amd64", Size: 1024, Path: "installer_1.2.3"}, nil
}
// mockCheckHandler implements checker.CheckHandler: every Gather* call is recorded and
// copies its part of config onto the result, so a refresh re-reads the configured state.
type mockCheckHandler struct {
mu sync.Mutex
calls []string
config mockCheckConfig
}
type mockCheckConfig struct {
EnvFileExists bool
DockerApiAccessible bool
WorkerEnvApiAccessible bool
WorkerImageExists bool
DockerInstalled bool
DockerComposeInstalled bool
DockerVersionOK bool
DockerComposeVersionOK bool
DockerVersion string
DockerComposeVersion string
PentagiScriptInstalled bool
PentagiExtracted bool
PentagiInstalled bool
PentagiRunning bool
GraphitiConnected bool
GraphitiExternal bool
GraphitiExtracted bool
GraphitiInstalled bool
GraphitiRunning bool
LangfuseConnected bool
LangfuseExternal bool
LangfuseExtracted bool
LangfuseInstalled bool
LangfuseRunning bool
ObservabilityConnected bool
ObservabilityExternal bool
ObservabilityExtracted bool
ObservabilityInstalled bool
ObservabilityRunning bool
SysNetworkOK bool
SysCPUOK bool
SysMemoryOK bool
SysDiskFreeSpaceOK bool
UpdateServerAccessible bool
InstallerIsUpToDate bool
PentagiIsUpToDate bool
GraphitiIsUpToDate bool
LangfuseIsUpToDate bool
ObservabilityIsUpToDate bool
}
func newMockCheckHandler() *mockCheckHandler {
return &mockCheckHandler{
config: mockCheckConfig{
EnvFileExists: true,
DockerApiAccessible: true,
WorkerEnvApiAccessible: true,
DockerInstalled: true,
DockerComposeInstalled: true,
DockerVersionOK: true,
DockerComposeVersionOK: true,
DockerVersion: "24.0.0",
DockerComposeVersion: "2.20.0",
SysNetworkOK: true,
SysCPUOK: true,
SysMemoryOK: true,
SysDiskFreeSpaceOK: true,
UpdateServerAccessible: true,
InstallerIsUpToDate: true,
PentagiIsUpToDate: true,
GraphitiIsUpToDate: true,
LangfuseIsUpToDate: true,
ObservabilityIsUpToDate: true,
},
}
}
func (m *mockCheckHandler) getCalls() []string {
m.mu.Lock()
defer m.mu.Unlock()
return append([]string(nil), m.calls...)
}
// apply records the call and copies the configured values under the lock.
func (m *mockCheckHandler) apply(method string, copyTo func(mockCheckConfig)) error {
m.mu.Lock()
defer m.mu.Unlock()
m.calls = append(m.calls, method)
copyTo(m.config)
return nil
}
func (m *mockCheckHandler) GatherAllInfo(ctx context.Context, c *checker.CheckResult) error {
_ = m.apply("GatherAllInfo", func(config mockCheckConfig) { c.EnvFileExists = config.EnvFileExists })
for _, gather := range []func(context.Context, *checker.CheckResult) error{
m.GatherDockerInfo, m.GatherWorkerInfo, m.GatherPentagiInfo, m.GatherGraphitiInfo,
m.GatherLangfuseInfo, m.GatherObservabilityInfo, m.GatherSystemInfo, m.GatherUpdatesInfo,
} {
if err := gather(ctx, c); err != nil {
return err
}
}
return nil
}
func (m *mockCheckHandler) GatherDockerInfo(_ context.Context, c *checker.CheckResult) error {
return m.apply("GatherDockerInfo", func(config mockCheckConfig) {
c.DockerApiAccessible = config.DockerApiAccessible
c.DockerInstalled = config.DockerInstalled
c.DockerComposeInstalled = config.DockerComposeInstalled
c.DockerVersion = config.DockerVersion
c.DockerVersionOK = config.DockerVersionOK
c.DockerComposeVersion = config.DockerComposeVersion
c.DockerComposeVersionOK = config.DockerComposeVersionOK
})
}
func (m *mockCheckHandler) GatherWorkerInfo(_ context.Context, c *checker.CheckResult) error {
return m.apply("GatherWorkerInfo", func(config mockCheckConfig) {
c.WorkerEnvApiAccessible = config.WorkerEnvApiAccessible
c.WorkerImageExists = config.WorkerImageExists
})
}
func (m *mockCheckHandler) GatherPentagiInfo(_ context.Context, c *checker.CheckResult) error {
return m.apply("GatherPentagiInfo", func(config mockCheckConfig) {
c.PentagiScriptInstalled = config.PentagiScriptInstalled
c.PentagiExtracted = config.PentagiExtracted
c.PentagiInstalled = config.PentagiInstalled
c.PentagiRunning = config.PentagiRunning
})
}
func (m *mockCheckHandler) GatherGraphitiInfo(_ context.Context, c *checker.CheckResult) error {
return m.apply("GatherGraphitiInfo", func(config mockCheckConfig) {
c.GraphitiConnected = config.GraphitiConnected
c.GraphitiExternal = config.GraphitiExternal
c.GraphitiExtracted = config.GraphitiExtracted
c.GraphitiInstalled = config.GraphitiInstalled
c.GraphitiRunning = config.GraphitiRunning
})
}
func (m *mockCheckHandler) GatherLangfuseInfo(_ context.Context, c *checker.CheckResult) error {
return m.apply("GatherLangfuseInfo", func(config mockCheckConfig) {
c.LangfuseConnected = config.LangfuseConnected
c.LangfuseExternal = config.LangfuseExternal
c.LangfuseExtracted = config.LangfuseExtracted
c.LangfuseInstalled = config.LangfuseInstalled
c.LangfuseRunning = config.LangfuseRunning
})
}
func (m *mockCheckHandler) GatherObservabilityInfo(_ context.Context, c *checker.CheckResult) error {
return m.apply("GatherObservabilityInfo", func(config mockCheckConfig) {
c.ObservabilityConnected = config.ObservabilityConnected
c.ObservabilityExternal = config.ObservabilityExternal
c.ObservabilityExtracted = config.ObservabilityExtracted
c.ObservabilityInstalled = config.ObservabilityInstalled
c.ObservabilityRunning = config.ObservabilityRunning
})
}
func (m *mockCheckHandler) GatherSystemInfo(_ context.Context, c *checker.CheckResult) error {
return m.apply("GatherSystemInfo", func(config mockCheckConfig) {
c.SysNetworkOK = config.SysNetworkOK
c.SysCPUOK = config.SysCPUOK
c.SysMemoryOK = config.SysMemoryOK
c.SysDiskFreeSpaceOK = config.SysDiskFreeSpaceOK
})
}
func (m *mockCheckHandler) GatherUpdatesInfo(_ context.Context, c *checker.CheckResult) error {
return m.apply("GatherUpdatesInfo", func(config mockCheckConfig) {
c.UpdateServerAccessible = config.UpdateServerAccessible
c.InstallerIsUpToDate = config.InstallerIsUpToDate
c.PentagiIsUpToDate = config.PentagiIsUpToDate
c.GraphitiIsUpToDate = config.GraphitiIsUpToDate
c.LangfuseIsUpToDate = config.LangfuseIsUpToDate
c.ObservabilityIsUpToDate = config.ObservabilityIsUpToDate
})
}
// processorHarness is a processor wired to recording doubles, with the check handler that
// answers its refreshes so a test can count what an operation asked the cloud.
type processorHarness struct {
p *processor
fs *baseMockFileSystemOperations
docker *baseMockDockerOperations
compose *baseMockComposeOperations
update *baseMockUpdateOperations
checks *mockCheckHandler
}
func processorHarnessWith(t *testing.T, configure func(*mockCheckConfig)) *processorHarness {
t.Helper()
h := &processorHarness{
fs: &baseMockFileSystemOperations{},
docker: &baseMockDockerOperations{},
compose: &baseMockComposeOperations{},
update: &baseMockUpdateOperations{},
checks: newMockCheckHandler(),
}
if configure != nil {
configure(&h.checks.config)
}
result, err := checker.GatherWithHandler(context.Background(), h.checks)
require.NoError(t, err)
h.p = &processor{
mu: &sync.Mutex{},
state: newMockState(t),
checker: &result,
files: newMockFiles(),
fsOps: h.fs,
dockerOps: h.docker,
composeOps: h.compose,
updateOps: h.update,
}
return h
}
func testOperationState(t *testing.T) *operationState {
t.Helper()
return &operationState{mx: &sync.Mutex{}, ctx: t.Context()}
}
// processorWithPullReference is a processor whose update answer names
// vxcontrol/pentagi:2.3.4 for the pentagi stack, with real compose operations.
func processorWithPullReference(t *testing.T) (*processor, *mockState) {
t.Helper()
state := newMockState(t)
p := &processor{
state: state,
checker: &checker.CheckResult{
StackUpdates: []checker.StackUpdate{{
Stack: "pentagi",
Components: []checker.ComponentUpdate{
{Component: "pentagi", Action: "upgrade", PullReference: "vxcontrol/pentagi:2.3.4"},
},
}},
},
}
p.composeOps = newComposeOperations(p)
return p, state
}
// repositoryRoot walks up to the directory holding the compose files.
func repositoryRoot(t *testing.T) string {
t.Helper()
dir, err := os.Getwd()
require.NoError(t, err)
for range 8 {
if _, err := os.Stat(filepath.Join(dir, "docker-compose.yml")); err == nil {
return dir
}
parent := filepath.Dir(dir)
require.NotEqual(t, parent, dir, "no docker-compose.yml above the test directory")
dir = parent
}
t.Fatal("could not find the repository root")
return ""
}
+97 -13
View File
@@ -14,16 +14,52 @@ import (
)
const (
observabilityDirectory = "observability"
pentagiExampleCustomConfigLLM = "example.custom.provider.yml"
pentagiExampleOllamaConfigLLM = "example.ollama.provider.yml"
observabilityDirectory = "observability"
graphitiConfigsDirectory = "graphiti"
neo4jDirectory = "neo4j"
pentagiExampleCustomConfigLLM = "example.custom.provider.yml"
pentagiExampleOllamaConfigLLM = "example.ollama.provider.yml"
pentagiExampleBedrockConfigLLM = "example.bedrock.provider.yml"
)
// pentagiExampleConfigs are the default sources of the provider config mounts in
// docker-compose.yml. Each has to be on disk as a file before the stack starts:
// Docker creates a directory in place of a bind-mount source that is missing.
var pentagiExampleConfigs = []string{
pentagiExampleCustomConfigLLM,
pentagiExampleOllamaConfigLLM,
pentagiExampleBedrockConfigLLM,
}
var filesToExcludeFromVerification = []string{
"observability/otel/config.yml",
"observability/grafana/config/grafana.ini",
pentagiExampleCustomConfigLLM,
pentagiExampleOllamaConfigLLM,
pentagiExampleBedrockConfigLLM,
// user-editable Neo4j/APOC static settings: created once if missing, never
// overwritten afterwards, even when the user forces a files update
"neo4j/conf/neo4j.conf",
"neo4j/conf/apoc.conf",
// user-editable Graphiti LLM provider presets: same "create once" policy
"graphiti/custom.yaml",
"graphiti/gemini.yaml",
"graphiti/litellm.yaml",
"graphiti/openai.yaml",
// The Jaeger storage plugin is updated over the network, so the embedded copy and the
// cloud are two sources of truth for one path and the priority has to be declared.
// Without this the update undoes itself: a downloaded plugin differs from what the
// installer ships, so verifyDirectoryContentIntegrity calls it modified. On every
// Apply Changes the user is then offered a "repair" — an offer to roll the update
// back, dressed up as tidying — and answering yes sets force, which copies the
// embedded version straight over the downloaded one. Factory reset does the same
// without asking.
//
// The exclusion policy is exactly the one this needs: still created when missing, so
// the embedded copy remains the source for a first install, and never overwritten
// afterwards, so the cloud becomes the source once it has answered.
"observability/jaeger/bin/jaeger-clickhouse-linux-amd64",
"observability/jaeger/bin/jaeger-clickhouse-linux-arm64",
}
var allStacks = []ProductStack{
@@ -47,13 +83,17 @@ func (fs *fileSystemOperationsImpl) ensureStackIntegrity(ctx context.Context, st
switch stack {
case ProductStackPentagi:
errCompose := fs.ensureFileFromEmbed(composeFilePentagi, state)
errCustom := fs.ensureFileFromEmbed(pentagiExampleCustomConfigLLM, state)
errOllama := fs.ensureFileFromEmbed(pentagiExampleOllamaConfigLLM, state)
return errors.Join(errCompose, errCustom, errOllama)
errs := []error{fs.ensureFileFromEmbed(composeFilePentagi, state)}
for _, name := range pentagiExampleConfigs {
errs = append(errs, fs.ensureFileFromEmbed(name, state))
}
return errors.Join(errs...)
case ProductStackGraphiti:
return fs.ensureFileFromEmbed(composeFileGraphiti, state)
errCompose := fs.ensureFileFromEmbed(composeFileGraphiti, state)
errConfigs := fs.ensureDirectoryFromEmbed(graphitiConfigsDirectory, state)
errNeo4j := fs.ensureDirectoryFromEmbed(neo4jDirectory, state)
return errors.Join(errCompose, errConfigs, errNeo4j)
case ProductStackLangfuse:
return fs.ensureFileFromEmbed(composeFileLangfuse, state)
@@ -83,10 +123,20 @@ func (fs *fileSystemOperationsImpl) verifyStackIntegrity(ctx context.Context, st
switch stack {
case ProductStackPentagi:
return fs.verifyFileIntegrity(composeFilePentagi, state)
if err := fs.verifyFileIntegrity(composeFilePentagi, state); err != nil {
return err
}
fs.restoreExampleConfigs(state)
return nil
case ProductStackGraphiti:
return fs.verifyFileIntegrity(composeFileGraphiti, state)
if err := fs.verifyFileIntegrity(composeFileGraphiti, state); err != nil {
return err
}
if err := fs.verifyDirectoryIntegrity(graphitiConfigsDirectory, state); err != nil {
return err
}
return fs.verifyDirectoryIntegrity(neo4jDirectory, state)
case ProductStackLangfuse:
return fs.verifyFileIntegrity(composeFileLangfuse, state)
@@ -111,7 +161,8 @@ func (fs *fileSystemOperationsImpl) verifyStackIntegrity(ctx context.Context, st
}
}
// checkStackIntegrity is a silent version of verifyStackIntegrity, used for getting files statuses
// checkStackIntegrity is the read-only counterpart of verifyStackIntegrity; it does not report
// the provider examples verifyStackIntegrity restores for pentagi.
func (fs *fileSystemOperationsImpl) checkStackIntegrity(ctx context.Context, stack ProductStack) (FilesCheckResult, error) {
result := make(FilesCheckResult)
@@ -121,6 +172,16 @@ func (fs *fileSystemOperationsImpl) checkStackIntegrity(ctx context.Context, sta
case ProductStackGraphiti:
result[composeFileGraphiti] = fs.checkFileIntegrity(composeFileGraphiti)
if r, err := fs.checkDirectoryIntegrity(graphitiConfigsDirectory); err != nil {
return result, err
} else {
maps.Copy(result, r)
}
if r, err := fs.checkDirectoryIntegrity(neo4jDirectory); err != nil {
return result, err
} else {
maps.Copy(result, r)
}
case ProductStackLangfuse:
result[composeFileLangfuse] = fs.checkFileIntegrity(composeFileLangfuse)
@@ -160,11 +221,14 @@ func (fs *fileSystemOperationsImpl) cleanupStackFiles(ctx context.Context, stack
switch stack {
case ProductStackPentagi:
filesToRemove = append(filesToRemove, filepath.Join(workingDir, composeFilePentagi))
filesToRemove = append(filesToRemove, filepath.Join(workingDir, pentagiExampleCustomConfigLLM))
filesToRemove = append(filesToRemove, filepath.Join(workingDir, pentagiExampleOllamaConfigLLM))
for _, name := range pentagiExampleConfigs {
filesToRemove = append(filesToRemove, filepath.Join(workingDir, name))
}
case ProductStackGraphiti:
filesToRemove = append(filesToRemove, filepath.Join(workingDir, composeFileGraphiti))
filesToRemove = append(filesToRemove, filepath.Join(workingDir, graphitiConfigsDirectory))
filesToRemove = append(filesToRemove, filepath.Join(workingDir, neo4jDirectory))
case ProductStackLangfuse:
filesToRemove = append(filesToRemove, filepath.Join(workingDir, composeFileLangfuse))
@@ -213,6 +277,26 @@ func (fs *fileSystemOperationsImpl) ensureFileFromEmbed(filename string, state *
return fs.processor.files.Copy(filename, workingDir, true)
}
// restoreExampleConfigs writes a provider example that is not on disk as a file,
// which covers the directory Docker left in its place, and never touches one that
// is, whatever state.force says: on a stack already extracted the examples are the
// user's. A failure is logged and not returned: the stack starts without the file,
// over the directory Docker makes for it.
func (fs *fileSystemOperationsImpl) restoreExampleConfigs(state *operationState) {
workingDir := filepath.Dir(fs.processor.state.GetEnvPath())
for _, name := range pentagiExampleConfigs {
if fs.fileExists(filepath.Join(workingDir, name)) {
continue
}
fs.processor.appendLog(fmt.Sprintf(MsgCreatingMissingFile, name), ProductStackAll, state)
if err := fs.processor.files.Copy(name, workingDir, true); err != nil {
fs.processor.appendLog(fmt.Sprintf(MsgMissingFileNotCreated, name, err), ProductStackAll, state)
}
}
}
func (fs *fileSystemOperationsImpl) ensureDirectoryFromEmbed(dirname string, state *operationState) error {
workingDir := filepath.Dir(fs.processor.state.GetEnvPath())
targetPath := filepath.Join(workingDir, dirname)
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,226 @@
package processor
import (
"context"
"fmt"
"io"
"os"
"path/filepath"
"pentagi/cmd/installer/checker"
"github.com/vxcontrol/cloud/models"
)
// stagingSuffix is what a plugin file is called while it is still arriving.
//
// The staging file sits in the SAME directory as its target, not in the system temp
// directory: os.Rename is only atomic within one filesystem, and /tmp is routinely a
// different one. It is also a directory antivirus and EDR products watch for executables
// being written and then moved, which is exactly the shape of this operation.
const stagingSuffix = ".new"
// jaegerServiceName is the compose service the plugin is mounted into. Restarting it is
// how a replaced plugin takes effect — the entrypoint exec's the file at start.
const jaegerServiceName = "jaeger"
// updateJaegerPlugin brings the Jaeger storage plugin up to what the server offers.
//
// The plugin is not an image: it is a binary mounted into the Jaeger container, which
// loads it over gRPC. Both architectures are kept in step because which one runs is
// decided inside the container by the architecture of the Docker VM — not by this host —
// and the compose entrypoint picks the file by `uname -m` at start.
//
// Runs BEFORE the images are pulled. A plugin that cannot be fetched then aborts the stack
// update with nothing else disturbed; doing it after would leave images pulled and the
// stack restarted around a plugin that never arrived.
//
// Reports whether anything was actually replaced, because the caller has to restart the
// Jaeger service when it was: `docker compose up -d` recreates a container only when its
// SPEC changes, and a different file inside a bind mount is not a spec change. The plugin
// is exec'd by the container's entrypoint at start, so without a restart the container
// goes on running the plugin it loaded when it came up, and the update looks applied while
// nothing about it is.
func (u *updateOperationsImpl) updateJaegerPlugin(
ctx context.Context, state *operationState,
) (bool, error) {
if u.processor.checker == nil {
return false, nil
}
base := filepath.Join(u.environmentDir(), checker.JaegerPluginDir)
// Always, even when there is nothing to fetch: an interrupted attempt leaves a ~28 MB
// file that nothing else will ever remove. Integrity verification walks the files the
// installer ships and does not see strangers, so this is the only thing that looks.
u.removeStagedPlugins(base, state)
offered := jaegerPluginUpdates(u.processor.checker.StackUpdates)
if len(offered) == 0 {
return false, nil
}
for _, component := range offered {
if err := u.fetchJaegerPlugin(ctx, base, component, state); err != nil {
return false, err
}
}
return true, nil
}
// jaegerPluginUpdates picks the plugin components that actually need fetching.
//
// Membership in the answer is not the test — under a curated release the server names
// every artefact it knows about, whether or not it differs from what is installed. What
// makes a component here is the digest comparison the checker already did.
func jaegerPluginUpdates(updates []checker.StackUpdate) []checker.ComponentUpdate {
var wanted []checker.ComponentUpdate
for _, update := range updates {
for _, component := range update.Components {
if component.Component != string(models.ComponentTypeJaegerClickhouse) {
continue
}
// An offered file always carries a version — a published binary cannot exist
// without one — so the empty case is defence, not a scenario: the package
// request requires a version and has no field for a hash, so asking without
// one buys a guaranteed rejection instead of a download.
if !component.Outdated || component.TargetVersion == "" {
continue
}
// The file name says "linux" in it, so an answer for another platform would
// put non-linux content under a linux name. The server has never sent one;
// this makes sure a change on that side is skipped rather than written.
if component.OS != string(models.OSTypeLinux) {
continue
}
wanted = append(wanted, component)
}
}
return wanted
}
// removeStagedPlugins deletes leftovers from an interrupted attempt.
//
// By exact name rather than by globbing "*.new": this directory is mounted into a
// container and an operator may keep their own files in it, and a delete that guesses is
// how a tool destroys something it was never asked to touch.
func (u *updateOperationsImpl) removeStagedPlugins(base string, state *operationState) {
for _, name := range checker.JaegerPluginBinaries {
staged := filepath.Join(base, name+stagingSuffix)
if _, err := os.Stat(staged); err != nil {
continue
}
if err := os.Remove(staged); err != nil {
u.processor.appendLog(
fmt.Sprintf(MsgJaegerPluginStaleRemoveFailed, staged, err),
ProductStackObservability, state)
continue
}
u.processor.appendLog(fmt.Sprintf(MsgJaegerPluginStaleRemoved, staged),
ProductStackObservability, state)
}
}
// fetchJaegerPlugin downloads one architecture's plugin and puts it in place.
func (u *updateOperationsImpl) fetchJaegerPlugin(
ctx context.Context, base string, component checker.ComponentUpdate, state *operationState,
) error {
arch := models.ArchType(component.Arch)
name, known := checker.JaegerPluginBinaries[arch]
if !known {
return fmt.Errorf("no jaeger plugin file is defined for architecture %s", component.Arch)
}
u.processor.appendLog(fmt.Sprintf(MsgJaegerPluginDownloading, name, component.TargetVersion),
ProductStackObservability, state)
client, err := u.cloudClient()
if err != nil {
return err
}
request := models.PackageInfoRequest{
Component: models.ComponentTypeJaegerClickhouse,
Version: component.TargetVersion,
OS: models.OSTypeLinux,
Arch: arch,
}
info, err := client.PackageInfo(ctx, request)
if err != nil {
return fmt.Errorf("failed to get jaeger plugin package info for %s: %w", arch, err)
}
progress := &progressWriter{total: info.Size, report: func(percent int, written, total int64) {
u.processor.appendLog(
fmt.Sprintf(MsgJaegerPluginProgress, name, percent, FormatSize(written), FormatSize(total)),
ProductStackObservability, state)
}}
target := filepath.Join(base, name)
err = installPluginFile(target, func(w io.Writer) error {
return client.DownloadPackage(ctx, models.DownloadPackageRequest{
Component: models.ComponentTypeJaegerClickhouse,
Version: component.TargetVersion,
OS: models.OSTypeLinux,
Arch: arch,
}, *info, io.MultiWriter(w, progress))
})
if err != nil {
return fmt.Errorf("failed to install jaeger plugin for %s: %w", arch, err)
}
u.processor.appendLog(fmt.Sprintf(MsgJaegerPluginInstalled, target),
ProductStackObservability, state)
return nil
}
// installPluginFile streams into <target>.new and moves it over target only once write
// has returned without complaint.
//
// Staged rather than written in place, because the file being replaced is the one a
// running Jaeger loads: a download that dies halfway would otherwise leave a truncated
// plugin, and the container would come back up unable to start with an opaque gRPC error.
// The staging file is a sibling of the target so the rename stays within one filesystem,
// where it is atomic.
func installPluginFile(target string, write func(io.Writer) error) error {
// The stack may never have been installed, in which case the directory the mount
// expects does not exist yet.
if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
return fmt.Errorf("failed to create %s: %w", filepath.Dir(target), err)
}
staged := target + stagingSuffix
// 0755 at CREATION and not afterwards: os.Rename does not preserve the destination's
// mode — the result keeps the staging file's — so a plugin created 0644 and renamed
// over an executable one ends up not executable, and Jaeger fails to start with an
// opaque gRPC plugin error rather than a permission one.
file, err := os.OpenFile(staged, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o755)
if err != nil {
return fmt.Errorf("failed to create %s: %w", staged, err)
}
writeErr := write(file)
if closeErr := file.Close(); closeErr != nil && writeErr == nil {
writeErr = fmt.Errorf("failed to finish writing %s: %w", staged, closeErr)
}
if writeErr != nil {
// The length, the sha256 and the signature are only decided once the last byte has
// arrived, so what is on disk here is unverified. The target is untouched — that is
// the entire reason for staging — and the installation keeps the plugin it had.
_ = os.Remove(staged)
return writeErr
}
if err := os.Rename(staged, target); err != nil {
_ = os.Remove(staged)
return fmt.Errorf("failed to put %s in place: %w", target, err)
}
return nil
}
@@ -0,0 +1,122 @@
package processor
import (
"errors"
"io"
"os"
"path/filepath"
"testing"
"pentagi/cmd/installer/checker"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// A curated release names current artefacts too, and the file name says "linux" whatever the host.
func TestJaegerPlugin_JaegerPluginUpdates_PicksOnlyOutdatedLinuxPlugins(t *testing.T) {
updates := []checker.StackUpdate{
{
Stack: "observability",
Components: []checker.ComponentUpdate{
{Component: "jaeger-clickhouse", OS: "linux", Arch: "amd64", Outdated: true, TargetVersion: "0.13.0"},
{Component: "jaeger-clickhouse", OS: "linux", Arch: "arm64", Outdated: true, TargetVersion: "0.13.0"},
{Component: "jaeger", OS: "linux", Arch: "amd64", Outdated: true, TargetVersion: "1.56.0"},
},
},
{
Stack: "pentagi",
Components: []checker.ComponentUpdate{
{Component: "pentagi", OS: "linux", Arch: "amd64", Outdated: true, TargetVersion: "2.3.4"},
},
},
}
wanted := jaegerPluginUpdates(updates)
require.Len(t, wanted, 2, "both architectures are kept in step: %+v", wanted)
assert.Equal(t, "amd64", wanted[0].Arch)
assert.Equal(t, "arm64", wanted[1].Arch)
for name, component := range map[string]checker.ComponentUpdate{
"already current": {Component: "jaeger-clickhouse", OS: "linux", Arch: "amd64", Outdated: false, TargetVersion: "0.13.0"},
"no version to ask": {Component: "jaeger-clickhouse", OS: "linux", Arch: "amd64", Outdated: true, TargetVersion: ""},
"not linux": {Component: "jaeger-clickhouse", OS: "darwin", Arch: "amd64", Outdated: true, TargetVersion: "0.13.0"},
"another component": {Component: "installer", OS: "linux", Arch: "amd64", Outdated: true, TargetVersion: "0.13.0"},
} {
got := jaegerPluginUpdates([]checker.StackUpdate{
{Stack: "observability", Components: []checker.ComponentUpdate{component}},
})
assert.Empty(t, got, "%s must not be fetched", name)
}
}
// os.Rename keeps the staging file's mode, and a running Jaeger loads whatever sits at the target.
func TestJaegerPlugin_InstallPluginFile_PutsOnlyACompleteExecutableFileInPlace(t *testing.T) {
for _, tc := range []struct {
name string
target string
existing string
write func(io.Writer) error
wantErr string
want string
}{
{name: "a failed download leaves the running plugin alone",
target: "jaeger-clickhouse-linux-amd64", existing: "the plugin currently in use",
write: func(w io.Writer) error {
if _, err := w.Write([]byte("partial")); err != nil {
return err
}
return errors.New("connection reset")
},
wantErr: "connection reset", want: "the plugin currently in use"},
{name: "a complete download lands executable in a directory never created before",
target: filepath.Join("sub", "jaeger-clickhouse-linux-arm64"),
write: func(w io.Writer) error {
_, err := w.Write([]byte("plugin bytes"))
return err
},
want: "plugin bytes"},
} {
t.Run(tc.name, func(t *testing.T) {
target := filepath.Join(t.TempDir(), tc.target)
if tc.existing != "" {
require.NoError(t, os.WriteFile(target, []byte(tc.existing), 0o755))
}
err := installPluginFile(target, tc.write)
if tc.wantErr == "" {
require.NoError(t, err)
} else {
require.EqualError(t, err, tc.wantErr)
}
content, readErr := os.ReadFile(target)
require.NoError(t, readErr)
assert.Equal(t, tc.want, string(content))
info, statErr := os.Stat(target)
require.NoError(t, statErr)
assert.NotZero(t, info.Mode()&0o111, "mode is %v; Jaeger cannot exec a plugin without the bit", info.Mode())
assert.NoFileExists(t, target+stagingSuffix, "a ~28 MB leftover that nothing else ever removes")
})
}
}
// The directory is mounted into a container and may hold an operator's own *.new files.
func TestJaegerPlugin_RemoveStagedPlugins_RemovesOnlyItsOwnLeftovers(t *testing.T) {
base := filepath.Join(t.TempDir(), checker.JaegerPluginDir)
require.NoError(t, os.MkdirAll(base, 0o755))
for _, name := range checker.JaegerPluginBinaries {
require.NoError(t, os.WriteFile(filepath.Join(base, name+stagingSuffix), []byte("half"), 0o755))
}
somebodyElses := filepath.Join(base, "operators-own-notes.new")
require.NoError(t, os.WriteFile(somebodyElses, []byte("keep me"), 0o644))
u := &updateOperationsImpl{processor: &processor{}}
u.removeStagedPlugins(base, newOperationState(nil))
for _, name := range checker.JaegerPluginBinaries {
assert.NoFileExists(t, filepath.Join(base, name+stagingSuffix), "%s leftover survived", name)
}
assert.FileExists(t, somebodyElses)
}
+32 -2
View File
@@ -43,6 +43,7 @@ const (
MsgStackIntegrityVerified = "Stack %s integrity verified"
MsgUpdatingExistingFile = "Updating existing file: %s"
MsgCreatingMissingFile = "Creating missing file: %s"
MsgMissingFileNotCreated = "Missing file %s was not created: %s"
MsgFileIntegrityValid = "File integrity valid: %s"
MsgSkippingModifiedFile = "Skipping modified files: %s"
MsgDirectoryCheckedWithModified = "Directory checked with modified files present: %s"
@@ -56,8 +57,37 @@ const (
MsgUpdatingInstaller = "Updating installer"
MsgRemovingInstaller = "Removing installer"
MsgInstallerUpdateCompleted = "Installer update completed"
MsgVerifyingBinaryChecksum = "Verifying binary checksum"
MsgReplacingInstallerBinary = "Replacing installer binary"
// Past tense: the length, the sha256 and the Ed25519 signature are all checked as the
// stream arrives, so by the time this is printed the verdict is already in.
MsgVerifyingBinaryChecksum = "Checksum and signature verified"
MsgInstallerSavedTo = "Installer saved to %s"
MsgInstallerDownloadProgress = "Downloaded %d%% (%s of %s)"
// The installer binary outlives the removal on purpose: a process cannot delete the
// file it is running from, and trying would leave the user with neither.
MsgInstallerNotRemoved = "The installer itself is left in place at %s — delete it yourself when you no longer need it"
MsgInstallerNotRemovedUnknownPath = "The installer itself is left in place — delete it yourself when you no longer need it"
)
// Jaeger storage plugin messages. The plugin is a file mounted into the Jaeger container,
// not an image, so none of the compose output covers it.
const (
MsgJaegerPluginDownloading = "Downloading Jaeger storage plugin %s (%s)"
MsgJaegerPluginProgress = " %s: %d%% (%s of %s)"
MsgJaegerPluginInstalled = "Jaeger storage plugin in place: %s"
MsgJaegerPluginStaleRemoved = "Removed leftover from an interrupted download: %s"
MsgJaegerPluginStaleRemoveFailed = "Could not remove leftover %s: %v"
MsgJaegerPluginRestarting = "Restarting Jaeger so it loads the new storage plugin"
)
// Post-update verification messages
const (
MsgVerifyingUpdatedComponents = "Verifying updated %s components"
MsgComponentUpToDate = " %s: matches the published build"
MsgComponentNewerThanOffered = " %s: newer than the offered build (registry moved ahead)"
MsgComponentMismatch = " %s: expected %s, got %s"
MsgComponentNotVerifiable = " %s: no published digest to compare against"
MsgVerificationPassed = "All updated %s components match the published build"
MsgVerificationMismatch = "%d %s component(s) do not match the published build"
)
// Remove operations messages
+131 -26
View File
@@ -2,12 +2,14 @@ package processor
import (
"context"
"errors"
"fmt"
"maps"
"os"
"os/exec"
"path/filepath"
"runtime"
"slices"
"sync"
"pentagi/cmd/installer/checker"
@@ -149,8 +151,8 @@ func (p *processor) applyChanges(ctx context.Context, state *operationState) (er
return
}
// refresh state for updates
if err := p.checker.GatherUpdatesInfo(ctx); err != nil {
err = fmt.Errorf("failed to gather info after update: %w", err)
if gatherErr := p.checker.GatherUpdatesInfo(ctx); gatherErr != nil {
err = fmt.Errorf("failed to gather info after update: %w", gatherErr)
}
}()
@@ -337,9 +339,10 @@ func (p *processor) applyPentagiChanges(ctx context.Context, state *operationSta
return nil
}
// checkFiles computes file statuses for a given stack, honoring the same
// rules as verifyStackIntegrity: active stacks only and excluded files policy.
// It serves as a dry-run for file operations without performing any writes.
// checkFiles computes file statuses for a given stack under the rules the apply
// path follows: embedded stacks only, and the excluded files policy of
// verifyStackIntegrity. It writes nothing; the provider examples
// verifyStackIntegrity restores for pentagi are not reported.
func (p *processor) checkFiles(
ctx context.Context, stack ProductStack, state *operationState,
) (result map[string]files.FileStatus, err error) {
@@ -446,8 +449,8 @@ func (p *processor) install(ctx context.Context, state *operationState) (err err
return
}
// refresh state for updates
if err := p.checker.GatherUpdatesInfo(ctx); err != nil {
err = fmt.Errorf("failed to gather info after update: %w", err)
if gatherErr := p.checker.GatherUpdatesInfo(ctx); gatherErr != nil {
err = fmt.Errorf("failed to gather info after update: %w", gatherErr)
}
}()
@@ -491,19 +494,72 @@ func (p *processor) install(ctx context.Context, state *operationState) (err err
return nil
}
// update is the entry point for an update operation: it announces itself, does the work,
// and then asks the cloud ONCE what is left.
//
// That single question used to be five. The fresh check lived in a deferred call inside
// the recursive worker, so `compose` — four stacks — spent four nested checks plus this
// one, and a stack with nothing to do paid for a check too, because the defer was
// registered before the early return. One press of "Update PentAGI" cost five requests
// out of a daily budget, and told the cloud nothing it had not been told four times
// already: GatherUpdatesInfo reports the WHOLE installation, not one stack.
func (p *processor) update(ctx context.Context, stack ProductStack, state *operationState) (err error) {
state.sendStarted(stack)
defer func() { state.sendCompletion(stack, err) }()
defer func() {
if err != nil {
return
}
// refresh state for updates
if err := p.checker.GatherUpdatesInfo(ctx); err != nil {
err = fmt.Errorf("failed to gather info after update: %w", err)
}
}()
// What the cloud currently offers, captured before the update replaces the answer with
// a newer one, for every stack this operation will touch. Only stacks whose update
// actually swaps what is installed are verified: the installer operation downloads a
// build without applying it, so comparing against the running binary would report a
// mismatch that is the intended outcome.
targets := make(map[ProductStack][]componentTarget)
for _, touched := range stacksTouchedByUpdate(stack) {
if verifiableUpdateStacks[touched] {
targets[touched] = captureStackTargets(p.checker, string(touched))
}
}
if err = p.updateStacks(ctx, stack, state); err != nil {
return err
}
// The fresh answer is what decides whether anything is still pending, so it comes
// after all the work and before the comparison.
if gatherErr := p.checker.GatherUpdatesInfo(ctx); gatherErr != nil {
err = fmt.Errorf("failed to gather info after update: %w", gatherErr)
return err
}
for _, touched := range stacksTouchedByUpdate(stack) {
p.verifyStackUpdate(touched, targets[touched], state)
}
return nil
}
// stacksTouchedByUpdate expands a requested stack into the ones an update of it actually
// runs, so their targets can be captured before anything changes.
//
// A stack that is not installed still appears here and costs nothing: captureStackTargets
// finds it in no answer and returns nil, and verifyStackUpdate returns immediately on an
// empty target list.
func stacksTouchedByUpdate(stack ProductStack) []ProductStack {
switch stack {
case ProductStackCompose:
return composeOperationAllStacksOrder[ProcessorOperationUpdate]
case ProductStackAll:
return append(
slices.Clone(composeOperationAllStacksOrder[ProcessorOperationUpdate]),
ProductStackWorker, ProductStackInstaller,
)
default:
return []ProductStack{stack}
}
}
// updateStacks does the work and recurses without announcing itself or asking the cloud
// anything: both belong to the operation as a whole, which is update() above.
func (p *processor) updateStacks(ctx context.Context, stack ProductStack, state *operationState) (err error) {
allStacks := append(composeOperationAllStacksOrder[ProcessorOperationUpdate],
ProductStackWorker,
ProductStackInstaller,
@@ -532,6 +588,23 @@ func (p *processor) update(ctx context.Context, stack ProductStack, state *opera
return nil
}
// The image references the server chose are written by downloadStack and
// updateStack themselves — every path that fetches goes through one of them,
// and a call site that forgot would fetch the compose default in silence.
// The Jaeger storage plugin is a FILE mounted into the jaeger container, so no
// amount of pulling images brings it up to date. Fetched before the images
// because a plugin that cannot be downloaded should abort the update with
// nothing else disturbed.
pluginReplaced := false
if stack == ProductStackObservability {
replaced, err := p.updateOps.updateJaegerPlugin(ctx, state)
if err != nil {
return err
}
pluginReplaced = replaced
}
if err := p.composeOps.downloadStack(ctx, stack, state); err != nil {
return fmt.Errorf("failed to download stack: %w", err)
}
@@ -541,6 +614,21 @@ func (p *processor) update(ctx context.Context, stack ProductStack, state *opera
return fmt.Errorf("failed to update stack: %w", err)
}
// `up -d` above recreates a container only when its SPEC changed, and a different
// file inside a bind mount is not a spec change — so when the plugin was replaced
// but the jaeger image was not, the container above was left running, still
// holding the plugin it exec'd when it started. Without this the update reports
// success and Jaeger goes on writing traces through the old plugin until
// something else happens to restart it.
if pluginReplaced {
p.appendLog(MsgJaegerPluginRestarting, stack, state)
if err := p.composeOps.performStackCommand(
ctx, stack, state, "restart", jaegerServiceName,
); err != nil {
return fmt.Errorf("failed to restart jaeger after replacing its storage plugin: %w", err)
}
}
if err := composeStacksGatherInfo[stack](ctx); err != nil {
return fmt.Errorf("failed to gather info after update: %w", err)
}
@@ -568,7 +656,7 @@ func (p *processor) update(ctx context.Context, stack ProductStack, state *opera
case ProductStackCompose:
for _, s := range composeOperationAllStacksOrder[ProcessorOperationUpdate] {
if err := p.update(ctx, s, state); err != nil {
if err := p.updateStacks(ctx, s, state); err != nil {
return err
}
}
@@ -576,7 +664,7 @@ func (p *processor) update(ctx context.Context, stack ProductStack, state *opera
case ProductStackAll:
// update all applicable stacks
for _, s := range allStacks {
if err := p.update(ctx, s, state); err != nil {
if err := p.updateStacks(ctx, s, state); err != nil {
return err
}
}
@@ -694,7 +782,7 @@ func (p *processor) remove(ctx context.Context, stack ProductStack, state *opera
return fmt.Errorf("failed to gather worker info after remove: %w", err)
}
if err := p.checker.GatherUpdatesInfo(ctx); err != nil {
err = fmt.Errorf("failed to gather info after update: %w", err)
return fmt.Errorf("failed to gather info after update: %w", err)
}
case ProductStackInstaller:
@@ -711,12 +799,18 @@ func (p *processor) remove(ctx context.Context, stack ProductStack, state *opera
}
case ProductStackAll:
// remove all stacks
// Every stack is attempted even when one fails: the user asked for all of them
// gone, and stopping halfway leaves an installation in a state nobody chose.
// errors.Join reports every failure rather than only the first.
var failures []error
for _, s := range allStacks {
if err := p.remove(ctx, s, state); err != nil {
return err
failures = append(failures, err)
}
}
if len(failures) > 0 {
return errors.Join(failures...)
}
default:
return fmt.Errorf("operation remove not applicable for stack %s", stack)
@@ -733,8 +827,8 @@ func (p *processor) purge(ctx context.Context, stack ProductStack, state *operat
return
}
// refresh state for updates
if err := p.checker.GatherUpdatesInfo(ctx); err != nil {
err = fmt.Errorf("failed to gather info after update: %w", err)
if gatherErr := p.checker.GatherUpdatesInfo(ctx); gatherErr != nil {
err = fmt.Errorf("failed to gather info after update: %w", gatherErr)
}
}()
@@ -774,7 +868,7 @@ func (p *processor) purge(ctx context.Context, stack ProductStack, state *operat
return fmt.Errorf("failed to gather worker info after purge: %w", err)
}
if err := p.checker.GatherUpdatesInfo(ctx); err != nil {
err = fmt.Errorf("failed to gather info after update: %w", err)
return fmt.Errorf("failed to gather info after update: %w", err)
}
case ProductStackInstaller:
@@ -791,10 +885,17 @@ func (p *processor) purge(ctx context.Context, stack ProductStack, state *operat
}
case ProductStackAll:
// purge all stacks
// Every stack is attempted even when one fails, and the networks go regardless.
//
// Both used to depend on nothing going wrong. The loop returned on the first
// error, and the network removal below it was simply skipped — so one stack that
// could not be purged left three custom docker networks behind, on an operation
// whose whole purpose is to leave nothing. Which stacks exist varies per
// installation, so "the first failure" is not a rare path.
var failures []error
for _, s := range allStacks {
if err := p.purge(ctx, s, state); err != nil {
return err
failures = append(failures, err)
}
}
@@ -803,6 +904,10 @@ func (p *processor) purge(ctx context.Context, stack ProductStack, state *operat
_ = p.dockerOps.removeMainDockerNetwork(ctx, state, string(ProductDockerNetworkObservability))
_ = p.dockerOps.removeMainDockerNetwork(ctx, state, string(ProductDockerNetworkLangfuse))
if len(failures) > 0 {
return errors.Join(failures...)
}
default:
return fmt.Errorf("operation purge not applicable for stack %s", stack)
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+20 -4
View File
@@ -30,6 +30,13 @@ type ProcessorModel interface {
Restart(ctx context.Context, stack ProductStack, opts ...OperationOption) tea.Cmd
ResetPassword(ctx context.Context, stack ProductStack, opts ...OperationOption) tea.Cmd
HandleMsg(msg tea.Msg) tea.Cmd
// InstallerPackage describes the installer build on offer without downloading it.
//
// Blocking rather than a tea.Cmd, unlike everything above it: this is one short
// request with one answer, not an operation that streams output into a terminal
// panel, and the screen that needs it already wraps it in a command of its own.
InstallerPackage(ctx context.Context) (*InstallerPackage, error)
}
func NewProcessorModel(state state.State, checker *checker.CheckResult, files files.Files) ProcessorModel {
@@ -211,10 +218,19 @@ func (pm *processorModel) HandleMsg(msg tea.Msg) tea.Cmd {
switch msg := msg.(type) {
case ProcessorWaitMsg:
if msg.Error != nil {
// stop polling after error
return nil
}
// Polling continues even when this message carries an error, and that is the
// whole point of it.
//
// An error here means the operation ENDED — wrapCommand's select received it from
// the operation's channel, or the context was cancelled. Either way the operation
// has already appended its completion message to the queue, and the completion is
// what tells the screen to stop the spinner and show what happened. Returning nil
// here stopped the polling that would have delivered it, so an operation that
// failed faster than wrapCommand's 500 ms window left the screen saying "in
// progress" forever, with the error displayed nowhere.
//
// The chain still terminates: ProcessorCompletionMsg below returns nil, and every
// operation sends one from a deferred call.
return pollMsg(msg.num, msg.Stack, msg.state)
case ProcessorOutputMsg:
return pollMsg(msg.num, msg.Stack, msg.state)
@@ -0,0 +1,28 @@
package processor
import (
"errors"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// A failure inside wrapCommand's 500 ms window arrives as a wait message ahead of its completion.
func TestModel_HandleMsg_KeepsPollingAfterAnErrorUntilTheCompletion(t *testing.T) {
model := &processorModel{processor: &processor{}}
state := testOperationState(t)
state.sendCompletion(ProductStackAll, errors.New("failed before the window closed"))
next := model.HandleMsg(ProcessorWaitMsg{
Error: errors.New("failed before the window closed"),
Stack: ProductStackAll, state: state,
})
require.NotNil(t, next, "polling stopped, so the completion already in the queue is never delivered")
completion, ok := next().(ProcessorCompletionMsg)
require.True(t, ok, "expected the queued completion")
assert.EqualError(t, completion.Error, "failed before the window closed")
assert.Nil(t, model.HandleMsg(completion), "polling must stop once the completion is delivered")
}
+109 -18
View File
@@ -3,7 +3,15 @@ package processor
import (
"context"
"database/sql"
"errors"
"fmt"
"slices"
"strconv"
"strings"
"pentagi/pkg/config"
"pentagi/pkg/database"
"pentagi/pkg/password"
_ "github.com/lib/pq"
"golang.org/x/crypto/bcrypt"
@@ -28,8 +36,28 @@ const (
EnvPostgreSQLDatabase = "PENTAGI_POSTGRES_DB"
)
var (
errPasswordTooLong = fmt.Errorf("password is longer than the %d bytes bcrypt hashes", password.MaxBytes)
errPasswordTooWeak = errors.New("password does not meet the password policy")
)
func checkPasswordPolicy(newPassword string) error {
switch {
case !password.FitsHashLimit(newPassword):
return errPasswordTooLong
case !password.IsStrong(newPassword):
return errPasswordTooWeak
default:
return nil
}
}
// performPasswordReset updates the admin password in PostgreSQL
func (p *processor) performPasswordReset(ctx context.Context, newPassword string, state *operationState) error {
if err := checkPasswordPolicy(newPassword); err != nil {
return err
}
// get database configuration from state
dbUser := DefaultPostgreSQLUser
if envVar, ok := p.state.GetVar(EnvPostgreSQLUser); ok && envVar.Value != "" {
@@ -46,41 +74,66 @@ func (p *processor) performPasswordReset(ctx context.Context, newPassword string
dbName = envVar.Value
}
// create connection string
connStr := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=disable",
PostgreSQLHost, PostgreSQLPort, dbUser, dbPassword, dbName)
cfg := &config.Config{
DatabaseURL: fmt.Sprintf(
"host=%s port=%s user=%s password=%s dbname=%s sslmode=disable",
PostgreSQLHost, PostgreSQLPort, dbUser, dbPassword, dbName,
),
}
// open database connection
db, err := sql.Open("postgres", connStr)
if envVar, ok := p.state.GetVar("TENANT_ID"); ok {
cfg.TenantID = strings.TrimSpace(envVar.Value)
}
if err := cfg.ValidateTenantID(); err != nil {
return err
}
if envVar, ok := p.state.GetVar("DATABASE_EXTENSIONS_SCHEMA"); ok {
cfg.DatabaseExtensionsSchema = strings.TrimSpace(envVar.Value)
}
if envVar, ok := p.state.GetVar("DATABASE_SEARCH_PATH_VIA_OPTIONS"); ok && envVar.Value != "" {
viaOptions, err := strconv.ParseBool(envVar.Value)
if err != nil {
return fmt.Errorf("invalid DATABASE_SEARCH_PATH_VIA_OPTIONS %q: %w", envVar.Value, err)
}
cfg.DatabaseSearchPathViaOptions = viaOptions
}
// Point the DSN at the tenant schema before opening a connection. Without
// this, an UPDATE on unqualified "users" would hit public.users while the
// running instance owns <tenant>.users — a silent no-op or wrong-tenant write.
if err := database.RewriteDatabaseURLForTenant(cfg); err != nil {
return fmt.Errorf("failed to apply tenant search_path: %w", err)
}
db, err := sql.Open("postgres", cfg.DatabaseURL)
if err != nil {
return fmt.Errorf("failed to connect to database: %w", err)
}
defer db.Close()
// test connection
db.SetMaxOpenConns(1)
if err := db.PingContext(ctx); err != nil {
return fmt.Errorf("failed to ping database: %w", err)
}
p.appendLog(fmt.Sprintf("Connected to PostgreSQL at %s:%s (database: %s)", PostgreSQLHost, PostgreSQLPort, dbName), ProductStackPentagi, state)
if err := database.VerifySearchPath(ctx, db, cfg); err != nil {
return fmt.Errorf("tenant schema verification failed: %w", err)
}
p.appendLog(fmt.Sprintf(
"Connected to PostgreSQL at %s:%s (database: %s, schema: %s)",
PostgreSQLHost, PostgreSQLPort, dbName, cfg.SchemaName(),
), ProductStackPentagi, state)
// hash the new password
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(newPassword), bcrypt.DefaultCost)
if err != nil {
return fmt.Errorf("failed to hash password: %w", err)
}
// update the admin user password and status
query := `UPDATE users SET password = $1, status = 'active' WHERE mail = $2`
result, err := db.ExecContext(ctx, query, string(hashedPassword), AdminEmail)
rowsAffected, err := resetAdminPassword(ctx, db, string(hashedPassword))
if err != nil {
return fmt.Errorf("failed to update password: %w", err)
}
// check if any rows were affected
rowsAffected, err := result.RowsAffected()
if err != nil {
return fmt.Errorf("failed to get rows affected: %w", err)
return err
}
if rowsAffected == 0 {
@@ -91,3 +144,41 @@ func (p *processor) performPasswordReset(ctx context.Context, newPassword string
return nil
}
func resetAdminPassword(ctx context.Context, db *sql.DB, hashedPassword string) (int64, error) {
hasGenerations, err := usersHaveSessionGeneration(ctx, db)
if err != nil {
return 0, err
}
query := `UPDATE users SET password = $1, status = 'active', session_generation = session_generation + 1 WHERE mail = $2`
if !hasGenerations {
query = `UPDATE users SET password = $1, status = 'active' WHERE mail = $2`
}
result, err := db.ExecContext(ctx, query, hashedPassword, AdminEmail)
if err != nil {
return 0, fmt.Errorf("failed to update password: %w", err)
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return 0, fmt.Errorf("failed to get rows affected: %w", err)
}
return rowsAffected, nil
}
func usersHaveSessionGeneration(ctx context.Context, db *sql.DB) (bool, error) {
rows, err := db.QueryContext(ctx, `SELECT * FROM users LIMIT 0`)
if err != nil {
return false, fmt.Errorf("failed to read the users columns: %w", err)
}
defer rows.Close()
columns, err := rows.Columns()
if err != nil {
return false, fmt.Errorf("failed to read the users columns: %w", err)
}
return slices.Contains(columns, "session_generation"), nil
}
@@ -0,0 +1,89 @@
package processor
import (
"database/sql"
"strings"
"testing"
_ "github.com/mattn/go-sqlite3"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestPg_ResetAdminPassword_ReplacesThePasswordAndEndsSessionsWhereTracked(t *testing.T) {
for _, tc := range []struct {
name string
generations bool
}{
{"a stack with session generations", true},
{"a stack older than session generations", false},
} {
t.Run(tc.name, func(t *testing.T) {
db, err := sql.Open("sqlite3", ":memory:")
require.NoError(t, err)
defer db.Close()
db.SetMaxOpenConns(1)
schema := `CREATE TABLE users (id INTEGER PRIMARY KEY, mail TEXT NOT NULL, password TEXT, status TEXT NOT NULL`
if tc.generations {
schema += `, session_generation INTEGER NOT NULL DEFAULT 1`
}
_, err = db.Exec(schema + `)`)
require.NoError(t, err)
_, err = db.Exec(`INSERT INTO users (mail, password, status) VALUES (?, 'old', 'blocked'), ('other@pentagi.com', 'x', 'active')`,
AdminEmail)
require.NoError(t, err)
rows, err := resetAdminPassword(t.Context(), db, "new-hash")
require.NoError(t, err)
assert.EqualValues(t, 1, rows)
var password, status string
require.NoError(t, db.QueryRow(`SELECT password, status FROM users WHERE mail = ?`, AdminEmail).
Scan(&password, &status))
assert.Equal(t, "new-hash", password)
assert.Equal(t, "active", status)
if !tc.generations {
return
}
var admin, other int
require.NoError(t, db.QueryRow(`SELECT session_generation FROM users WHERE mail = ?`, AdminEmail).Scan(&admin))
require.NoError(t, db.QueryRow(`SELECT session_generation FROM users WHERE mail = 'other@pentagi.com'`).Scan(&other))
assert.Equal(t, 2, admin, "a cookie issued before the reset, which is why the reset is run, must stop working")
assert.Equal(t, 1, other)
})
}
}
func TestPg_PerformPasswordReset_RefusesWhatThePolicyRefuses(t *testing.T) {
for _, tc := range []struct {
label, password string
want error
}{
{"short and plain", "admin", errPasswordTooWeak},
{"eight characters without every class", "abcdefgh", errPasswordTooWeak},
{"fifteen characters without every class", strings.Repeat("a", 15), errPasswordTooWeak},
{"longer than bcrypt hashes", strings.Repeat("a", 73), errPasswordTooLong},
} {
t.Run(tc.label, func(t *testing.T) {
h := processorHarnessWith(t, func(c *mockCheckConfig) { c.PentagiRunning = true })
// A role no database has, so a missing refusal fails at login instead of writing.
require.NoError(t, h.p.state.SetVar(EnvPostgreSQLUser, "pagi-policy-test-no-such-role"))
require.NoError(t, h.p.state.SetVar(EnvPostgreSQLPassword, "not-a-password-of-any-database"))
err := h.p.ResetPassword(t.Context(), ProductStackPentagi, WithPasswordValue(tc.password))
require.ErrorIs(t, err, tc.want)
})
}
}
func TestPg_CheckPasswordPolicy_LetsThroughWhatThePolicyAccepts(t *testing.T) {
for _, pw := range []string{
strings.Repeat("a", 16),
"Abcdef1!",
strings.Repeat("a", 72),
} {
require.NoError(t, checkPasswordPolicy(pw), pw)
}
}
+17 -2
View File
@@ -63,6 +63,9 @@ type Processor interface {
Stop(ctx context.Context, stack ProductStack, opts ...OperationOption) error
Restart(ctx context.Context, stack ProductStack, opts ...OperationOption) error
ResetPassword(ctx context.Context, stack ProductStack, opts ...OperationOption) error
// InstallerPackage describes the installer build on offer without downloading it.
InstallerPackage(ctx context.Context) (*InstallerPackage, error)
}
// WithForce skips validation checks and attempts maximum operations
@@ -70,7 +73,6 @@ func WithForce() OperationOption {
return func(c *operationState) { c.force = true }
}
// WithTerminalModel enables embedded terminal model integration
func WithTerminal(term terminal.Terminal) OperationOption {
return func(c *operationState) {
if term != nil {
@@ -120,10 +122,12 @@ type composeOperations interface {
}
type updateOperations interface {
checkUpdates(ctx context.Context, state *operationState) (*checker.CheckUpdatesResponse, error)
checkUpdates(ctx context.Context, state *operationState) error
downloadInstaller(ctx context.Context, state *operationState) error
updateInstaller(ctx context.Context, state *operationState) error
removeInstaller(ctx context.Context, state *operationState) error
installerPackage(ctx context.Context) (*InstallerPackage, error)
updateJaegerPlugin(ctx context.Context, state *operationState) (bool, error)
}
type processor struct {
@@ -251,3 +255,14 @@ func (p *processor) ResetPassword(ctx context.Context, stack ProductStack, opts
opts = append(opts, withContext(ctx), withOperation(ProcessorOperationResetPassword))
return p.resetPassword(ctx, stack, newOperationState(opts))
}
// InstallerPackage asks the update server what it offers for this host.
//
// It takes the same lock as the operations even though it changes nothing: the answer is
// remembered for the download that follows, and the download runs under this lock.
func (p *processor) InstallerPackage(ctx context.Context) (*InstallerPackage, error) {
p.mu.Lock()
defer p.mu.Unlock()
return p.updateOps.installerPackage(ctx)
}
@@ -0,0 +1,89 @@
package processor
import (
"fmt"
"strings"
"pentagi/cmd/installer/checker"
"pentagi/cmd/installer/wizard/logger"
)
// Every `image:` in the compose files is `${<COMPONENT>_IMAGE:-<default>}`, and
// this is the other half of that: before a pull, the reference the server chose
// is written into `.env` so compose resolves it.
//
// The installer does NOT pick a tag. Which tag to pull is the cloud's decision
// and varies with the update strategy, so a client that rebuilt `repository:tag`
// out of the repository and tag fields would silently override the answer with a
// guess — and land on an artefact it was never offered.
//
// The `:-` default in compose is what makes this safe to skip: an absent or
// EMPTY variable falls back to the reference the file shipped with, so an
// installation that never got an answer behaves exactly as before.
// composeImageVar is the environment variable a component's image reference goes
// into.
//
// Derived from the component name rather than kept in a table: the compose files
// use exactly this spelling, so a new component needs no second registration
// that could be forgotten — and a mismatch shows up as "the default was used",
// which is visible in `docker compose config`.
func composeImageVar(component string) string {
return strings.ToUpper(strings.ReplaceAll(strings.TrimSpace(component), "-", "_")) + "_IMAGE"
}
// pullReferencesForStack collects the variables to write for one stack.
//
// Only components the server actually resolved: an `unknown` one carries no
// reference, and writing an empty value would be worse than writing nothing —
// `${VAR:-default}` treats empty as absent, so it would work, but it would also
// erase a reference a previous answer had pinned.
func pullReferencesForStack(updates []checker.StackUpdate, stack string) map[string]string {
vars := map[string]string{}
for _, update := range updates {
if update.Stack != stack {
continue
}
for _, component := range update.Components {
if component.PullReference == "" || component.Component == "" {
continue
}
vars[composeImageVar(component.Component)] = component.PullReference
}
}
return vars
}
// applyPullReferences writes them, and reports what it wrote so an operator can
// see in the log which reference a pull was about to use.
//
// A failure here is returned rather than logged and swallowed: the whole point
// is that the pull uses the reference the server named, and a pull that quietly
// used the compose default instead is an update that reports success while
// changing nothing.
func (p *processor) applyPullReferences(stack ProductStack) error {
if p.checker == nil || p.state == nil {
return nil
}
vars := pullReferencesForStack(p.checker.StackUpdates, string(stack))
if len(vars) == 0 {
return nil
}
names := make([]string, 0, len(vars))
for name, reference := range vars {
names = append(names, fmt.Sprintf("%s=%s", name, reference))
}
logger.Log("[processor] PULL REFERENCES for %s: %s", stack, strings.Join(names, " "))
// WriteVars and not SetVars. SetVars STAGES a change: it lands in the installer's own
// state file and only reaches `.env` when the user applies their changes. But the pull
// that follows is `docker compose --env-file <.env>`, so a staged variable is one
// compose has never heard of — it falls back to the default the compose file ships
// with, pulls that, and the update reports success having fetched something the server
// never offered. The whole mechanism was inert until this line said WriteVars.
if err := p.state.WriteVars(vars); err != nil {
return fmt.Errorf("failed to write image references for %s: %w", stack, err)
}
return nil
}
@@ -0,0 +1,101 @@
package processor
import (
"os"
"path/filepath"
"regexp"
"testing"
"pentagi/cmd/installer/checker"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestPullReference_ComposeImageVar_UppercasesTheComponentAndTurnsDashesIntoUnderscores(t *testing.T) {
for component, want := range map[string]string{
"pentagi": "PENTAGI_IMAGE",
"langfuse-worker": "LANGFUSE_WORKER_IMAGE",
"node-exporter": "NODE_EXPORTER_IMAGE",
"clickstore": "CLICKSTORE_IMAGE",
"otel": "OTEL_IMAGE",
} {
assert.Equal(t, want, composeImageVar(component))
}
}
// An empty value would erase a reference a previous answer pinned.
func TestPullReference_PullReferencesForStack_KeepsOnlyResolvedComponentsOfThatStack(t *testing.T) {
updates := []checker.StackUpdate{
{
Stack: "pentagi",
Components: []checker.ComponentUpdate{
{Component: "pentagi", Action: "upgrade", PullReference: "vxcontrol/pentagi:2.3.4"},
// Written too, or the next `compose up` falls back to the file's default.
{Component: "pgvector", Action: "current", PullReference: "vxcontrol/pgvector:latest"},
{Component: "scraper", Action: "unknown", Reason: "tag_not_published"},
},
},
{
Stack: "langfuse",
Components: []checker.ComponentUpdate{
{Component: "langfuse-web", Action: "current", PullReference: "langfuse/langfuse:3"},
},
},
}
assert.Equal(t, map[string]string{
"PENTAGI_IMAGE": "vxcontrol/pentagi:2.3.4",
"PGVECTOR_IMAGE": "vxcontrol/pgvector:latest",
}, pullReferencesForStack(updates, "pentagi"),
"an unresolved component must not be written, and another stack must not leak in")
assert.Equal(t, map[string]string{"LANGFUSE_WEB_IMAGE": "langfuse/langfuse:3"},
pullReferencesForStack(updates, "langfuse"))
assert.Empty(t, pullReferencesForStack(updates, "observability"))
}
// `docker compose --env-file` reads the file, not the installer's staging area.
func TestPullReference_ApplyPullReferences_WritesTheEnvFileWithoutMakingTheStateDirty(t *testing.T) {
p, state := processorWithPullReference(t)
require.NoError(t, p.applyPullReferences(ProductStackPentagi))
assert.Equal(t, map[string]string{"PENTAGI_IMAGE": "vxcontrol/pentagi:2.3.4"}, state.written,
"the reference was staged instead of written")
assert.False(t, state.IsDirty())
}
// A hardcoded `image:` cannot be steered by the server's answer; this walks the real files.
func TestPullReference_EveryComposeImageIsParameterised(t *testing.T) {
root := repositoryRoot(t)
imageLine := regexp.MustCompile(`(?m)^\s*image:\s*(\S+)\s*$`)
parameterised := regexp.MustCompile(`^\$\{([A-Z0-9_]+):-(\S+)\}$`)
seen := 0
for _, name := range []string{
"docker-compose.yml",
"docker-compose-langfuse.yml",
"docker-compose-observability.yml",
"docker-compose-graphiti.yml",
} {
body, err := os.ReadFile(filepath.Join(root, name))
require.NoError(t, err, "the compose files are part of the contract with the server")
for _, match := range imageLine.FindAllStringSubmatch(string(body), -1) {
seen++
reference := match[1]
parts := parameterised.FindStringSubmatch(reference)
require.NotNil(t, parts,
"%s: %q is hardcoded, so the server cannot steer what this service pulls", name, reference)
// `:-` and not `-`: only the first substitutes the default for an EMPTY variable.
assert.True(t, len(parts) == 3 && parts[2] != "",
"%s: %s must keep a default so an installation with no answer behaves as before",
name, parts[1])
assert.True(t, len(parts[1]) > len("_IMAGE") && parts[1][len(parts[1])-len("_IMAGE"):] == "_IMAGE",
"%s: %q does not follow <COMPONENT>_IMAGE, so composeImageVar will never write it",
name, parts[1])
}
}
assert.GreaterOrEqual(t, seen, 20, "the walk found only %d images; it is not reading the files", seen)
}
@@ -0,0 +1,138 @@
package processor
import (
"fmt"
"regexp"
"sort"
"strings"
)
// The cloud does not steer an installation back to a supported reference, and
// deliberately: it would need a copy of these compose defaults kept in step with
// them, and `postgres:15 → 16` is a major upgrade with a data migration behind
// it — not something a routine update check may cause as a side effect. It
// answers `unknown` with a reason instead.
//
// The installer is the side that CAN say it, because it ships the reference
// defaults itself. What it does with that is report the difference and let the
// user decide, separately from updating.
// composeImagePattern matches `image: ${VAR:-default}` in a compose file, which
// is the only form these files use — TestPullReference_EveryComposeImageIsParameterised
// is what keeps that true.
var composeImagePattern = regexp.MustCompile(`(?m)^\s*image:\s*\$\{([A-Z0-9_]+):-(\S+)\}\s*$`)
// composeFiles are the four the installer ships and the variables in them are
// the reference defaults of this build.
var composeFiles = []string{
"docker-compose.yml",
"docker-compose-langfuse.yml",
"docker-compose-observability.yml",
"docker-compose-graphiti.yml",
}
// ReferenceDrift is one variable whose value is not what this build of the
// installer would have used.
type ReferenceDrift struct {
// Variable is the compose variable, Configured what `.env` says, Default what
// this installer ships.
Variable string
Configured string
Default string
}
func (d ReferenceDrift) String() string {
return fmt.Sprintf("%s=%s (this build ships %s)", d.Variable, d.Configured, d.Default)
}
// composeReferenceDefaults reads the shipped defaults out of the compose files.
//
// From the files rather than from a table in Go: the files are what `docker
// compose` actually reads, so a table would be a second source of truth able to
// disagree with the thing it describes.
func composeReferenceDefaults(read func(string) ([]byte, error)) (map[string]string, error) {
defaults := map[string]string{}
for _, name := range composeFiles {
body, err := read(name)
if err != nil {
return nil, fmt.Errorf("reading %s: %w", name, err)
}
for _, match := range composeImagePattern.FindAllStringSubmatch(string(body), -1) {
defaults[match[1]] = match[2]
}
}
if len(defaults) == 0 {
return nil, fmt.Errorf("no parameterised images found in the compose files")
}
return defaults, nil
}
// referenceDrift lists the variables `.env` sets to something other than the
// shipped default.
//
// A variable the update path wrote is NOT drift: it is the server's answer, and
// under `stable` it is deliberately a more specific tag than the file's default
// (`vxcontrol/pentagi:2.3.4` against `vxcontrol/pentagi:latest`). Only a
// different REPOSITORY is a configuration this installer cannot support —
// a different tag of the same repository is the mechanism working.
func referenceDrift(defaults, configured map[string]string) []ReferenceDrift {
var drift []ReferenceDrift
for variable, shipped := range defaults {
value := strings.TrimSpace(configured[variable])
if value == "" || value == shipped {
continue
}
if repositoryOf(value) == repositoryOf(shipped) {
continue
}
drift = append(drift, ReferenceDrift{
Variable: variable, Configured: value, Default: shipped,
})
}
sort.Slice(drift, func(i, j int) bool { return drift[i].Variable < drift[j].Variable })
return drift
}
// repositoryOf drops the tag. A colon separates a tag only after the last slash,
// so a registry port survives; a digest reference contributes no tag.
func repositoryOf(reference string) string {
if at := strings.LastIndex(reference, "@"); at >= 0 {
reference = reference[:at]
}
colon := strings.LastIndex(reference, ":")
if colon < 0 || colon < strings.LastIndex(reference, "/") {
return reference
}
return reference[:colon]
}
// ReferenceDrift reports the compose variables this installation sets to a
// repository this build of the installer does not ship.
//
// Exposed as a query rather than folded into the update: realignment is a
// deliberate act, not a side effect of a routine update check. What
// the interface does with the answer — show it, offer to reset those variables —
// is its decision; what this guarantees is that the difference is visible at all,
// which it was not before: the server answers `unknown` with a reason and the
// installation simply never updates that component.
func (p *processor) ReferenceDrift() ([]ReferenceDrift, error) {
if p.files == nil || p.state == nil {
return nil, nil
}
defaults, err := composeReferenceDefaults(p.files.GetContent)
if err != nil {
return nil, err
}
names := make([]string, 0, len(defaults))
for variable := range defaults {
names = append(names, variable)
}
vars, _ := p.state.GetVars(names)
configured := make(map[string]string, len(vars))
for variable, envVar := range vars {
configured[variable] = envVar.Value
}
return referenceDrift(defaults, configured), nil
}
@@ -0,0 +1,52 @@
package processor
import (
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// A sharper tag of the shipped repository is what a working update pins, not drift.
func TestReferenceDrift_ReferenceDrift_ReportsOnlyADifferentRepository(t *testing.T) {
defaults := map[string]string{
"PENTAGI_IMAGE": "vxcontrol/pentagi:latest",
"POSTGRES_IMAGE": "postgres:16",
"NEO4J_IMAGE": "neo4j:5.26.2",
"REDIS_IMAGE": "redis:7",
}
drift := referenceDrift(defaults, map[string]string{
"PENTAGI_IMAGE": "vxcontrol/pentagi:2.3.4",
// Another major of the same repository is a data migration, not drift.
"POSTGRES_IMAGE": "postgres:15",
"NEO4J_IMAGE": "acme/neo4j-fork:5.26.2",
"REDIS_IMAGE": "",
})
require.Len(t, drift, 1, "only a different repository is drift: %+v", drift)
assert.Equal(t, "NEO4J_IMAGE", drift[0].Variable)
assert.Equal(t, "acme/neo4j-fork:5.26.2", drift[0].Configured)
assert.Equal(t, "neo4j:5.26.2", drift[0].Default)
}
func TestReferenceDrift_ComposeReferenceDefaults_ReadsTheShippedComposeFiles(t *testing.T) {
root := repositoryRoot(t)
defaults, err := composeReferenceDefaults(func(name string) ([]byte, error) {
return os.ReadFile(filepath.Join(root, name))
})
require.NoError(t, err)
assert.GreaterOrEqual(t, len(defaults), 20, "every image is parameterised, so every one has a default")
assert.Equal(t, "vxcontrol/pentagi:latest", defaults["PENTAGI_IMAGE"])
assert.Equal(t, "postgres:16", defaults["POSTGRES_IMAGE"])
// Two services ship the same image under different variables, so the variable is the key.
assert.Equal(t, "clickhouse/clickhouse-server:24", defaults["CLICKHOUSE_IMAGE"])
assert.Equal(t, "clickhouse/clickhouse-server:24", defaults["CLICKSTORE_IMAGE"])
// Finding nothing would make every installation look perfectly aligned.
_, err = composeReferenceDefaults(func(string) ([]byte, error) { return []byte("services:\n"), nil })
assert.EqualError(t, err, "no parameterised images found in the compose files")
}
+28 -4
View File
@@ -19,6 +19,19 @@ type operationState struct {
operation ProcessorOperation
passwordValue string // password value for reset password operation
// announced is the stack the CALLER asked about — the first one to announce itself.
// Started and completion messages are sent for it and for nothing else.
//
// The operations fan out: an update of `compose` runs four stacks, an update of `all`
// runs six, and each nested call used to announce its own completion. The screen takes
// the first completion as the end of the whole operation — it stops the terminal, prints
// the result and, because HandleMsg returns nil for a completion, stops polling. So the
// first stack to finish reported success on behalf of all of them, and every error
// after it was never drained. Which stacks are installed does not change this: the
// fan-out lists are fixed, and a stack with nothing to do finishes fastest of all.
announced ProductStack
announcedSet bool
// message chain for reply
mx *sync.Mutex
ctx context.Context
@@ -87,10 +100,6 @@ type ProcessorFilesCheckMsg struct {
type OperationOption func(c *operationState)
func withID(id string) OperationOption {
return func(c *operationState) { c.id = id }
}
func withOperation(operation ProcessorOperation) OperationOption {
return func(c *operationState) { c.operation = operation }
}
@@ -153,6 +162,12 @@ func (state *operationState) sendCompletion(stack ProductStack, err error) {
state.mx.Lock()
defer state.mx.Unlock()
// A nested stack finishing is not the operation finishing. Its error is not lost by
// staying silent here — the caller returns it, and the announced stack carries it.
if state.announcedSet && state.announced != stack {
return
}
state.msgs = append(state.msgs, ProcessorCompletionMsg{
ID: state.id,
Error: err,
@@ -168,6 +183,15 @@ func (state *operationState) sendStarted(stack ProductStack) {
state.mx.Lock()
defer state.mx.Unlock()
// The first stack to announce itself is the one the caller asked about; everything
// after it is the fan-out this operation performs internally.
if !state.announcedSet {
state.announced, state.announcedSet = stack, true
}
if state.announced != stack {
return
}
state.msgs = append(state.msgs, ProcessorStartedMsg{
ID: state.id,
Operation: state.operation,
@@ -0,0 +1,65 @@
package processor
import (
"context"
"errors"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// Pins sendStarted and sendCompletion through each operation that fans out; subtests are keyed by operation.
func TestState_AnOperationIsAnnouncedOnceUnderTheStackAskedFor(t *testing.T) {
for _, tc := range []struct {
name string
run func(*processor, context.Context, ProductStack, *operationState) error
stack ProductStack
wantErr string
}{
{name: "an update of every compose stack", run: (*processor).update, stack: ProductStackCompose},
{name: "an update of everything", run: (*processor).update, stack: ProductStackAll},
{name: "an update of a single stack", run: (*processor).update, stack: ProductStackObservability},
{name: "a download of every compose stack", run: (*processor).download, stack: ProductStackCompose},
{name: "a removal of every compose stack", run: (*processor).remove, stack: ProductStackCompose},
{name: "a start of every compose stack", run: (*processor).start, stack: ProductStackCompose},
{name: "a stop of every compose stack", run: (*processor).stop, stack: ProductStackCompose},
{name: "an update whose first stack fails", run: (*processor).update, stack: ProductStackCompose,
wantErr: "failed to update stack: compose exploded"},
} {
t.Run(tc.name, func(t *testing.T) {
h := processorHarnessWith(t, func(c *mockCheckConfig) {
c.PentagiIsUpToDate, c.GraphitiIsUpToDate, c.ObservabilityIsUpToDate = false, false, false
})
if tc.wantErr != "" {
h.compose.setError("updateStack", errors.New("compose exploded"))
}
state := testOperationState(t)
err := tc.run(h.p, t.Context(), tc.stack, state)
var started []ProcessorStartedMsg
var completed []ProcessorCompletionMsg
for _, msg := range state.msgs {
switch msg := msg.(type) {
case ProcessorStartedMsg:
started = append(started, msg)
case ProcessorCompletionMsg:
completed = append(completed, msg)
}
}
require.Len(t, started, 1, "started announced %d times", len(started))
require.Len(t, completed, 1, "the screen was told the operation finished %d times", len(completed))
assert.Equal(t, tc.stack, started[0].Stack)
assert.Equal(t, tc.stack, completed[0].Stack, "the completion must name the stack asked about, not a nested one")
if tc.wantErr == "" {
require.NoError(t, err)
assert.NoError(t, completed[0].Error)
return
}
require.EqualError(t, err, tc.wantErr)
assert.EqualError(t, completed[0].Error, tc.wantErr, "the one completion the screen sees must carry the failure")
})
}
}
Loaded 100 of 1379 files, more files were not shown because too many files have changed in this diff. Show more