Files
clice/tests/unit/server/pch_worker_tests.cpp
ykiko 75b9ea05b8 refactor(server): split into service layer, add agentic protocol, adopt task_group (#437)
## Summary

- **Restructure `src/server/` into subdirectories** (`service/`,
`compiler/`, `worker/`, `workspace/`, `protocol/`) to separate concerns:
transport/session management, compilation, worker orchestration, and
persistent workspace state.
- **Decouple MasterServer from transport**: MasterServer no longer holds
a `JsonPeer&` reference or registers handlers itself. New `LSPClient`
and `AgentClient` classes own their peer references and register
protocol handlers, accessing MasterServer internals via `friend class`.
- **Add agentic protocol**: A TCP-based side channel
(`agentic/compileCommand`) that lets external tools (AI agents, build
systems) query compile commands from a running clice server. Includes a
CLI client mode (`--mode agentic --port N --path FILE`), server-side
listener when `--port` is specified in pipe mode, and integration tests
for happy path, fallback, concurrency, and connection-refused.
- **Replace fire-and-forget `loop.schedule()` with `kota::task_group`**:
Compiler compile tasks, Indexer background indexing + resource monitor,
WorkerPool worker monitors, and socket accept loops now use structured
concurrency. This eliminates manual `alive_count_`/generation counters
and ensures all spawned tasks are joined on shutdown.
- **Fix flaky integration test**: `CliceClient.initialize()` now always
sets `cache_dir` to a workspace-local `.clice/` directory, preventing
stale PCH artifacts from the global `~/.cache/clice/` from polluting
test runs.

## Details

**Compiler peer lifetime**: `Compiler` and `Indexer` previously took
`JsonPeer&` in their constructors, coupling them to a single connection.
They now store a `JsonPeer*` set via `set_peer()`, with null checks
before sending diagnostics/progress. This supports the multi-connection
model where agentic clients don't need diagnostics.

**Socket mode single-LSP enforcement**: `accept_connections()` takes a
`register_lsp` flag; when true, only the first connection gets an
`LSPClient`. All connections get an `AgentClient`. This prevents
multiple LSP sessions from racing on shared server state.

**Structured shutdown**: `Compiler::stop()` cancels in-flight compile
tasks and joins them. `WorkerPool::stop()` signals workers and joins the
monitor task group. `Indexer` uses a `cancellation_source` to stop its
resource monitor when a background indexing run completes.

**Pin kotatsu**: Changed from `GIT_TAG main` + `GIT_SHALLOW TRUE` to an
exact commit hash for reproducible builds.

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-02 01:06:18 +08:00

152 lines
4.3 KiB
C++

#include <string>
#include <vector>
#include "test/test.h"
#include "server/protocol/worker.h"
#include "server/worker_test_helpers.h"
#include "syntax/scan.h"
namespace clice::testing {
namespace {
// ============================================================================
// End-to-end PCH compilation through real workers:
// 1. Stateless worker builds PCH for preamble headers
// 2. Stateful worker compiles a file using the PCH
// ============================================================================
TEST_SUITE(PCHWorker) {
TEST_CASE(BuildPCHThenCompile) {
TempDir tmp;
tmp.touch("common.h", R"cpp(struct Point { int x, y; };)cpp" "\n");
auto header = tmp.path("common.h");
std::string main_text = "#include \"common.h\"\nPoint p{1,2};\n";
tmp.touch("main.cpp", main_text);
auto main_file = tmp.path("main.cpp");
auto dir = std::string(tmp.root);
WorkerHandle sl;
ASSERT_TRUE(sl.spawn("stateless-worker"));
std::string pch_path;
bool phase1_done = false;
sl.run([&]() -> kota::task<> {
worker::BuildParams params;
params.kind = worker::BuildKind::BuildPCH;
params.file = main_file;
params.directory = dir;
params.arguments = {"clang++",
"-resource-dir",
std::string(resource_dir()),
"-x",
"c++-header",
"-I",
dir,
main_file};
params.text = main_text;
params.output_path = tmp.path("preamble.pch");
auto result = co_await sl.peer->send_request(params);
CO_ASSERT_TRUE(result.has_value());
CO_ASSERT_TRUE(result.value().success);
pch_path = result.value().output_path;
EXPECT_FALSE(pch_path.empty());
phase1_done = true;
sl.peer->close_output();
});
ASSERT_TRUE(phase1_done);
ASSERT_FALSE(pch_path.empty());
// Verify the PCH file exists on disk.
ASSERT_TRUE(llvm::sys::fs::exists(pch_path));
WorkerHandle sf;
ASSERT_TRUE(sf.spawn("stateful-worker"));
bool phase2_done = false;
auto preamble_bound = compute_preamble_bound(main_text);
sf.run([&]() -> kota::task<> {
worker::CompileParams params;
params.path = main_file;
params.version = 1;
params.text = main_text;
params.directory = dir;
params.arguments = {"clang++",
"-resource-dir",
std::string(resource_dir()),
"-fsyntax-only",
"-I",
dir,
main_file};
params.pch = {pch_path, preamble_bound};
auto result = co_await sf.peer->send_request(params);
CO_ASSERT_TRUE(result.has_value());
EXPECT_EQ(result.value().version, 1);
phase2_done = true;
sf.peer->close_output();
});
ASSERT_TRUE(phase2_done);
// Cleanup PCH temp file.
std::remove(pch_path.c_str());
}
TEST_CASE(CompileWithoutPCHStillWorks) {
TempDir tmp;
tmp.touch("common.h", R"cpp(struct Point { int x, y; };)cpp" "\n");
std::string main_text = "#include \"common.h\"\nPoint p{1,2};\n";
tmp.touch("main.cpp", main_text);
auto main_file = tmp.path("main.cpp");
auto dir = std::string(tmp.root);
WorkerHandle sf;
ASSERT_TRUE(sf.spawn("stateful-worker"));
bool compile_done = false;
sf.run([&]() -> kota::task<> {
worker::CompileParams params;
params.path = main_file;
params.version = 1;
params.text = main_text;
params.directory = dir;
params.arguments = {"clang++",
"-resource-dir",
std::string(resource_dir()),
"-fsyntax-only",
"-I",
dir,
main_file};
// pch left as default (empty path, 0 bound).
auto result = co_await sf.peer->send_request(params);
CO_ASSERT_TRUE(result.has_value());
EXPECT_EQ(result.value().version, 1);
compile_done = true;
sf.peer->close_output();
});
ASSERT_TRUE(compile_done);
}
}; // TEST_SUITE(PCHWorker)
} // namespace
} // namespace clice::testing