write_filefilePath="glm52_write_probe.md"'
- 'content="GLM 5.2 写文件验证"文件已创建。'
- ),
- ],
-)
-async def test_model_client_recovers_real_glm52_malformed_write_call(monkeypatch, content):
- monkeypatch.setenv("MODEL_API_KEY", "secret-value")
- body = (
- "data: "
- + __import__("json").dumps(
- {
- "choices": [
- {
- "delta": {"content": content},
- "finish_reason": "stop",
- }
- ]
- },
- ensure_ascii=False,
- )
- + "\n\n"
- ).encode()
- client = OpenAICompatibleModelClient(
- network_guard=AllowNetwork(),
- transport=httpx.MockTransport(
- lambda _request: httpx.Response(
- 200, headers={"content-type": "text/event-stream"}, content=body
- )
- ),
- )
- chunks = [
- chunk
- async for chunk in client.stream(
- _model(),
- messages=[],
- network_policy=NetworkPolicy(allowed_hosts=["model.example.com"]),
- timeout_seconds=10,
- tools=[
- {
- "type": "function",
- "function": {
- "name": "write_workspace_file",
- "parameters": {
- "type": "object",
- "properties": {
- "path": {"type": "string"},
- "content": {"type": "string"},
- },
- "required": ["path", "content"],
- },
- },
- }
- ],
- )
- ]
-
- assert "".join(chunk.text for chunk in chunks) == "准备创建。"
- assert chunks[-1].done is True
- assert chunks[-1].tool_calls[0].name == "write_workspace_file"
- assert __import__("json").loads(chunks[-1].tool_calls[0].arguments) == {
- "path": "glm52_write_probe.md",
- "content": "GLM 5.2 写文件验证",
- }
-
-
-@pytest.mark.asyncio
-async def test_model_client_repairs_glm_residue_in_native_tool_argument_key(monkeypatch):
- monkeypatch.setenv("MODEL_API_KEY", "secret-value")
- payloads = [
- {
- "choices": [
- {
- "delta": {
- "tool_calls": [
- {
- "index": 0,
- "id": "call-adk",
- "function": {
- "name": "delegate_task",
- "arguments": (
- '{"label":"ADK","task":"research ADK",'
- ),
- },
- }
- ]
- },
- "finish_reason": None,
- }
- ]
- },
- {
- "choices": [
- {
- "delta": {
- "tool_calls": [
- {
- "index": 0,
- "function": {"arguments": '"task_kind":"general"}'},
- }
- ]
- },
- "finish_reason": "tool_calls",
- }
- ]
- },
- ]
- body = b"".join(
- f"data: {__import__('json').dumps(payload)}\n\n".encode() for payload in payloads
- )
- client = OpenAICompatibleModelClient(
- network_guard=AllowNetwork(),
- transport=httpx.MockTransport(
- lambda _request: httpx.Response(
- 200, headers={"content-type": "text/event-stream"}, content=body
- )
- ),
- )
- chunks = [
- chunk
- async for chunk in client.stream(
- _model(),
- messages=[],
- network_policy=NetworkPolicy(allowed_hosts=["model.example.com"]),
- timeout_seconds=10,
- tools=[
- {
- "type": "function",
- "function": {
- "name": "delegate_task",
- "parameters": {
- "type": "object",
- "properties": {
- "label": {"type": "string"},
- "task": {"type": "string"},
- "task_kind": {"type": "string"},
- },
- },
- },
- }
- ],
- )
- ]
-
- assert chunks[-1].done is True
- assert __import__("json").loads(chunks[-1].tool_calls[0].arguments) == {
- "label": "ADK",
- "task": "research ADK",
- "task_kind": "general",
- }
-
-
-@pytest.mark.asyncio
-async def test_model_client_recovers_final_message_tool_call_snapshot(monkeypatch):
- monkeypatch.setenv("MODEL_API_KEY", "secret-value")
- payloads = [
- {
- "choices": [
- {
- "delta": {
- "tool_calls": [
- {
- "index": 0,
- "id": "call-write",
- "function": {"name": "write_workspace_file"},
- }
- ]
- },
- "finish_reason": None,
- }
- ]
- },
- {
- "choices": [
- {
- "delta": {},
- "finish_reason": "tool_calls",
- }
- ]
- },
- {
- "choices": [
- {
- "delta": {},
- "message": {
- "tool_calls": [
- {
- "index": 0,
- "id": "call-write",
- "function": {
- "name": "write_workspace_file",
- "arguments": {
- "path": "report.md",
- "content": "# Report\ncomplete",
- },
- },
- }
- ]
- },
- "finish_reason": None,
- }
- ]
- },
- ]
- body = (
- b"".join(f"data: {__import__('json').dumps(payload)}\n\n".encode() for payload in payloads)
- + b"data: [DONE]\n\n"
- )
- client = OpenAICompatibleModelClient(
- network_guard=AllowNetwork(),
- transport=httpx.MockTransport(
- lambda _request: httpx.Response(
- 200, headers={"content-type": "text/event-stream"}, content=body
- )
- ),
- )
- chunks = [
- chunk
- async for chunk in client.stream(
- _model(),
- messages=[],
- network_policy=NetworkPolicy(allowed_hosts=["model.example.com"]),
- timeout_seconds=10,
- tools=[
- {
- "type": "function",
- "function": {
- "name": "write_workspace_file",
- "parameters": {
- "type": "object",
- "properties": {
- "path": {"type": "string"},
- "content": {"type": "string"},
- },
- "required": ["path", "content"],
- },
- },
- }
- ],
- )
- ]
-
- assert chunks[-1].done is True
- assert chunks[-1].tool_calls[0].id == "call-write"
- assert __import__("json").loads(chunks[-1].tool_calls[0].arguments) == {
- "path": "report.md",
- "content": "# Report\ncomplete",
- }
-
-
-@pytest.mark.asyncio
-async def test_model_client_keeps_unindexed_parallel_tool_call_snapshots(monkeypatch):
- monkeypatch.setenv("MODEL_API_KEY", "secret-value")
- payloads = [
- {
- "choices": [
- {
- "delta": {},
- "message": {
- "tool_calls": [
- {
- "id": "call-one",
- "function": {
- "name": "delegate_task",
- "arguments": {"task": "one"},
- },
- }
- ]
- },
- }
- ]
- },
- {
- "choices": [
- {
- "delta": {},
- "message": {
- "tool_calls": [
- {
- "id": "call-two",
- "function": {
- "name": "delegate_task",
- "arguments": {"task": "two"},
- },
- }
- ]
- },
- "finish_reason": "tool_calls",
- }
- ]
- },
- ]
- body = (
- b"".join(f"data: {__import__('json').dumps(payload)}\n\n".encode() for payload in payloads)
- + b"data: [DONE]\n\n"
- )
- client = OpenAICompatibleModelClient(
- network_guard=AllowNetwork(),
- transport=httpx.MockTransport(
- lambda _request: httpx.Response(
- 200, headers={"content-type": "text/event-stream"}, content=body
- )
- ),
- )
- chunks = [
- chunk
- async for chunk in client.stream(
- _model(),
- messages=[],
- network_policy=NetworkPolicy(allowed_hosts=["model.example.com"]),
- timeout_seconds=10,
- tools=[
- {
- "type": "function",
- "function": {
- "name": "delegate_task",
- "parameters": {"type": "object"},
- },
- }
- ],
- )
- ]
-
- assert [call.id for call in chunks[-1].tool_calls] == ["call-one", "call-two"]
- assert [__import__("json").loads(call.arguments)["task"] for call in chunks[-1].tool_calls] == [
- "one",
- "two",
- ]
-
-
-@pytest.mark.asyncio
-async def test_model_client_rejects_reasoning_only_stream(monkeypatch):
- monkeypatch.setenv("MODEL_API_KEY", "secret-value")
- body = (
- b'data: {"choices":[{"delta":{"reasoning_content":"still thinking"},'
- b'"finish_reason":null}]}\n\n'
- b'data: {"choices":[{"delta":{},"finish_reason":"stop"}]}\n\n'
- )
- requests = []
-
- def handler(request: httpx.Request) -> httpx.Response:
- payload = __import__("json").loads(request.content)
- requests.append(payload)
- if payload.get("stream"):
- return httpx.Response(200, headers={"content-type": "text/event-stream"}, content=body)
- return httpx.Response(
- 200,
- json={
- "choices": [
- {"message": {"role": "assistant", "content": ""}, "finish_reason": "stop"}
- ]
- },
- )
-
- client = OpenAICompatibleModelClient(
- network_guard=AllowNetwork(),
- transport=httpx.MockTransport(handler),
- )
-
- with pytest.raises(StudioError) as captured:
- async for _chunk in client.stream(
- _model(),
- messages=[],
- network_policy=NetworkPolicy(allowed_hosts=["model.example.com"]),
- timeout_seconds=10,
- ):
- pass
-
- assert captured.value.code == "MODEL_EMPTY_RESPONSE"
- assert len(requests) == 2
- assert "reasoning alone" in requests[1]["messages"][-1]["content"]
-
-
-@pytest.mark.asyncio
-async def test_model_client_repairs_reasoning_only_stream_once(monkeypatch):
- monkeypatch.setenv("MODEL_API_KEY", "secret-value")
- body = (
- b'data: {"choices":[{"delta":{"reasoning_content":"still thinking"},'
- b'"finish_reason":null}]}\n\n'
- b'data: {"choices":[{"delta":{},"finish_reason":"stop"}]}\n\n'
- )
- requests = []
-
- def handler(request: httpx.Request) -> httpx.Response:
- payload = __import__("json").loads(request.content)
- requests.append(payload)
- if payload.get("stream"):
- return httpx.Response(200, headers={"content-type": "text/event-stream"}, content=body)
- return httpx.Response(
- 200,
- json={
- "choices": [
- {
- "message": {"role": "assistant", "content": "可用的最终答案"},
- "finish_reason": "stop",
- }
- ],
- "usage": {"prompt_tokens": 5, "completion_tokens": 4, "total_tokens": 9},
- },
- )
-
- client = OpenAICompatibleModelClient(
- network_guard=AllowNetwork(), transport=httpx.MockTransport(handler)
- )
- chunks = [
- chunk
- async for chunk in client.stream(
- _model(),
- messages=[],
- network_policy=NetworkPolicy(allowed_hosts=["model.example.com"]),
- timeout_seconds=10,
- )
- ]
-
- assert len(requests) == 2
- assert "".join(chunk.text for chunk in chunks) == "可用的最终答案"
- assert chunks[-1].done is True
- assert chunks[-1].usage is not None
- assert chunks[-1].usage.total_tokens == 9
-
-
-@pytest.mark.asyncio
-async def test_model_client_can_leave_empty_stream_recovery_to_native_loop(monkeypatch):
- monkeypatch.setenv("MODEL_API_KEY", "secret-value")
- requests = []
- body = (
- b'data: {"choices":[{"delta":{"reasoning_content":"thinking"},'
- b'"finish_reason":null}]}\n\n'
- b'data: {"choices":[{"delta":{},"finish_reason":"stop"}]}\n\n'
- )
-
- def handler(request: httpx.Request) -> httpx.Response:
- requests.append(__import__("json").loads(request.content))
- return httpx.Response(200, headers={"content-type": "text/event-stream"}, content=body)
-
- client = OpenAICompatibleModelClient(
- network_guard=AllowNetwork(), transport=httpx.MockTransport(handler)
- )
- chunks = [
- chunk
- async for chunk in client.stream(
- _model(),
- messages=[],
- network_policy=NetworkPolicy(allowed_hosts=["model.example.com"]),
- timeout_seconds=10,
- retry_empty_stream=False,
- )
- ]
- assert len(requests) == 1
- assert chunks[-1].done is True
- assert chunks[-1].finish_reason == "stop"
- assert not any(chunk.text or chunk.tool_calls for chunk in chunks)
-
-
-@pytest.mark.asyncio
-async def test_model_client_requests_usage_for_compatible_chat_stream(monkeypatch):
- monkeypatch.setenv("MODEL_API_KEY", "secret-value")
- requests: list[dict] = []
- body = (
- b'data: {"choices":[{"delta":{"content":"OK"},"finish_reason":null}]}\n\n'
- b'data: {"choices":[{"delta":{},"finish_reason":"stop"}]}\n\n'
- b'data: {"choices":[],"usage":{"prompt_tokens":5,'
- b'"completion_tokens":2,"total_tokens":7}}\n\n'
- b"data: [DONE]\n\n"
- )
-
- def handler(request: httpx.Request) -> httpx.Response:
- requests.append(__import__("json").loads(request.content))
- return httpx.Response(200, headers={"content-type": "text/event-stream"}, content=body)
-
- client = OpenAICompatibleModelClient(
- network_guard=AllowNetwork(),
- transport=httpx.MockTransport(handler),
- )
- chunks = [
- chunk
- async for chunk in client.stream(
- _model(),
- messages=[],
- network_policy=NetworkPolicy(allowed_hosts=["model.example.com"]),
- timeout_seconds=10,
- )
- ]
-
- assert requests[0]["stream_options"] == {"include_usage": True}
- assert any(chunk.usage and chunk.usage.total_tokens == 7 for chunk in chunks)
-
-
-@pytest.mark.asyncio
-async def test_model_client_rejects_dsml_for_undeclared_tool(monkeypatch):
- monkeypatch.setenv("MODEL_API_KEY", "secret-value")
- body = (
- b'data: {"choices":[{"delta":{"content":"<||DSML||invoke name=\\"danger\\">"}}]}\n\n'
- b'data: {"choices":[{"delta":{"content":"1<||DSML||/invoke>"},'
- b'"finish_reason":"stop"}]}\n\n'
- )
- client = OpenAICompatibleModelClient(
- network_guard=AllowNetwork(),
- transport=httpx.MockTransport(
- lambda _request: httpx.Response(
- 200, headers={"content-type": "text/event-stream"}, content=body
- )
- ),
- )
-
- with pytest.raises(StudioError) as captured:
- _ = [
- chunk
- async for chunk in client.stream(
- _model(),
- messages=[],
- network_policy=NetworkPolicy(allowed_hosts=["model.example.com"]),
- timeout_seconds=10,
- tools=[
- {
- "type": "function",
- "function": {
- "name": "web_search",
- "parameters": {"type": "object"},
- },
- }
- ],
- )
- ]
-
- assert captured.value.code == "MODEL_TOOL_PROTOCOL_INVALID"
-
-
-@pytest.mark.asyncio
-async def test_model_client_streams_responses_events_and_tool_calls(monkeypatch):
- monkeypatch.setenv("MODEL_API_KEY", "secret-value")
- captured = {}
-
- def handler(request: httpx.Request) -> httpx.Response:
- captured["json"] = __import__("json").loads(request.content)
- body = (
- b'data: {"type":"response.output_text.delta","delta":"Hi"}\n\n'
- b'data: {"type":"response.output_item.added","item":'
- b'{"type":"function_call","id":"item_1","call_id":"call_1",'
- b'"name":"lookup"}}\n\n'
- b'data: {"type":"response.function_call_arguments.delta",'
- b'"item_id":"item_1","delta":"{\\"q\\":\\"x\\"}"}\n\n'
- b'data: {"type":"response.output_item.done","item":'
- b'{"type":"function_call","id":"item_1","call_id":"call_1",'
- b'"name":"lookup","arguments":"{\\"q\\":\\"x\\"}"}}\n\n'
- b'data: {"type":"response.completed","response":{"usage":'
- b'{"input_tokens":2,"output_tokens":3,"total_tokens":5}}}\n\n'
- )
- return httpx.Response(200, headers={"content-type": "text/event-stream"}, content=body)
-
- model = _model().model_copy(
- update={"wire_api": "responses", "endpoint_url": "https://model.example.com/v1/responses"}
- )
- client = OpenAICompatibleModelClient(
- network_guard=AllowNetwork(), transport=httpx.MockTransport(handler)
- )
- chunks = [
- chunk
- async for chunk in client.stream(
- model,
- messages=[{"role": "user", "content": "test"}],
- network_policy=NetworkPolicy(allowed_hosts=["model.example.com"]),
- timeout_seconds=10,
- tools=[
- {
- "type": "function",
- "function": {"name": "lookup", "parameters": {"type": "object"}},
- }
- ],
- )
- ]
- assert captured["json"]["stream"] is True
- assert captured["json"]["tools"][0]["name"] == "lookup"
- assert [chunk.text for chunk in chunks if chunk.text] == ["Hi"]
- assert chunks[-2].tool_calls[0].name == "lookup"
- assert chunks[-1].done is True
-
-
-@pytest.mark.asyncio
-async def test_model_client_retries_5xx_without_leaking_secret(monkeypatch):
- monkeypatch.setenv("MODEL_API_KEY", "top-secret")
- attempts = 0
- sleeps = []
-
- def handler(_request: httpx.Request) -> httpx.Response:
- nonlocal attempts
- attempts += 1
- if attempts == 1:
- return httpx.Response(503, text="upstream failed")
- return httpx.Response(
- 200,
- json={"choices": [{"message": {"content": "OK"}, "finish_reason": "stop"}]},
- )
-
- async def fake_sleep(value):
- sleeps.append(value)
-
- client = OpenAICompatibleModelClient(
- network_guard=AllowNetwork(),
- transport=httpx.MockTransport(handler),
- sleep=fake_sleep,
- )
- result = await client.complete(
- _model(),
- messages=[],
- network_policy=NetworkPolicy(allowed_hosts=["model.example.com"]),
- timeout_seconds=10,
- max_attempts=2,
- backoff_seconds=0.5,
- )
-
- assert result.content == "OK"
- assert attempts == 2
- assert sleeps == [0.5]
-
-
-@pytest.mark.asyncio
-async def test_model_client_surfaces_rate_limit_without_relabeling_it_as_gateway_failure(
- monkeypatch,
-):
- monkeypatch.setenv("MODEL_API_KEY", "secret-value")
- client = OpenAICompatibleModelClient(
- network_guard=AllowNetwork(),
- transport=httpx.MockTransport(lambda _request: httpx.Response(429, text="busy")),
- sleep=lambda _seconds: asyncio.sleep(0),
- )
-
- with pytest.raises(StudioError) as captured:
- await client.complete(
- _model(),
- messages=[],
- network_policy=NetworkPolicy(allowed_hosts=["model.example.com"]),
- timeout_seconds=10,
- max_attempts=1,
- backoff_seconds=0,
- )
-
- assert captured.value.code == "MODEL_RATE_LIMITED"
- assert captured.value.status_code == 429
- assert captured.value.message == "所选生成模型当前限流,请稍后重试或切换模型 Profile"
- assert captured.value.details == {"upstreamStatus": 429}
-
-
-@pytest.mark.asyncio
-async def test_model_client_rejects_redirect(monkeypatch):
- monkeypatch.setenv("MODEL_API_KEY", "secret-value")
- client = OpenAICompatibleModelClient(
- network_guard=AllowNetwork(),
- transport=httpx.MockTransport(
- lambda _request: httpx.Response(302, headers={"Location": "https://attacker.invalid"})
- ),
- )
-
- with pytest.raises(StudioError) as captured:
- await client.complete(
- _model(),
- messages=[],
- network_policy=NetworkPolicy(allowed_hosts=["model.example.com"]),
- timeout_seconds=10,
- max_attempts=1,
- backoff_seconds=0,
- )
-
- assert captured.value.code == "NETWORK_TARGET_DENIED"
- assert "secret-value" not in str(captured.value.as_dict())
-
-
-@pytest.mark.asyncio
-async def test_model_client_rejects_reasoning_only_length_response(monkeypatch):
- monkeypatch.setenv("MODEL_API_KEY", "secret-value")
- client = OpenAICompatibleModelClient(
- network_guard=AllowNetwork(),
- transport=httpx.MockTransport(
- lambda _request: httpx.Response(
- 200,
- json={
- "choices": [
- {
- "message": {
- "role": "assistant",
- "content": "",
- "reasoning_content": "internal reasoning",
- },
- "finish_reason": "length",
- }
- ],
- "usage": {"total_tokens": 64},
- },
- )
- ),
- )
-
- with pytest.raises(StudioError) as captured:
- await client.complete(
- _model(),
- messages=[],
- network_policy=NetworkPolicy(allowed_hosts=["model.example.com"]),
- timeout_seconds=10,
- max_attempts=1,
- backoff_seconds=0,
- )
-
- assert captured.value.code == "MODEL_EMPTY_RESPONSE"
- assert captured.value.details == {"finishReason": "length"}
-
-
-def test_credential_resolver_never_accepts_plaintext_or_missing_env(monkeypatch):
- resolver = CredentialResolver()
- monkeypatch.delenv("MODEL_API_KEY", raising=False)
-
- with pytest.raises(StudioError) as missing:
- resolver.resolve("env://MODEL_API_KEY")
- assert missing.value.code == "SECRET_NOT_FOUND"
-
- with pytest.raises(StudioError) as invalid:
- resolver.resolve("plain-secret")
- assert invalid.value.code == "SECRET_BACKEND_UNAVAILABLE"
-
-
-def test_credential_resolver_session_overlay_precedes_environment(monkeypatch):
- resolver = CredentialResolver()
- monkeypatch.setenv("MODEL_API_KEY", "environment-secret")
-
- assert resolver.status("env://MODEL_API_KEY") == {
- "reference": "env://MODEL_API_KEY",
- "name": "MODEL_API_KEY",
- "configured": True,
- "source": "environment",
- "persistence": "environment",
- }
-
- configured = resolver.put_session("MODEL_API_KEY", "session-secret")
- assert configured["source"] == "session"
- assert resolver.resolve("env://MODEL_API_KEY") == "session-secret"
- assert "session-secret" not in str(configured)
-
- restored = resolver.delete_session("MODEL_API_KEY")
- assert restored["source"] == "environment"
- assert resolver.resolve("env://MODEL_API_KEY") == "environment-secret"
-
-
-def test_credential_resolver_applies_alias_to_workspace_secret(tmp_path: Path):
- """Break caught: Studio sees a persisted model key but Codex receives no auth."""
-
- from ksadk.studio.workspace import Workspace
-
- workspace = Workspace(tmp_path)
- workspace.initialize()
- resolver = CredentialResolver(workspace)
- resolver.put_session("AGENTKIT_MODEL_API_KEY", "workspace-model-key")
- resolver = CredentialResolver(workspace)
-
- assert resolver.resolve("env://OPENAI_API_KEY") == "workspace-model-key"
- status = resolver.status("env://OPENAI_API_KEY")
- assert status["configured"] is True
- assert status["source"] == "workspace-alias"
-
-
-def test_credential_resolver_prefers_workspace_alias_over_process_primary(
- tmp_path: Path,
- monkeypatch: pytest.MonkeyPatch,
-):
- """A host OPENAI_API_KEY must not shadow a Studio-configured model credential."""
-
- from ksadk.studio.workspace import Workspace
-
- monkeypatch.setenv("OPENAI_API_KEY", "host-primary-key")
- workspace = Workspace(tmp_path)
- workspace.initialize()
- workspace.atomic_write_text(
- ".agentkit/secrets.env",
- "AGENTKIT_MODEL_API_KEY=workspace-profile-key\n",
- )
-
- resolver = CredentialResolver(workspace)
-
- assert resolver.resolve("env://OPENAI_API_KEY") == "workspace-profile-key"
-
-
-def test_credential_resolver_session_overlay_reports_session_over_workspace(
- tmp_path: Path,
- monkeypatch: pytest.MonkeyPatch,
-):
- """put_session with a workspace configuration must report source == "session"."""
-
- from ksadk.studio.workspace import Workspace
-
- monkeypatch.delenv("MODEL_API_KEY", raising=False)
- workspace = Workspace(tmp_path)
- workspace.initialize()
- resolver = CredentialResolver(workspace)
-
- assert resolver.status("env://MODEL_API_KEY")["source"] == "missing"
-
- configured = resolver.put_session("MODEL_API_KEY", "session-secret")
- assert configured["source"] == "session"
- assert resolver.status("env://MODEL_API_KEY")["source"] == "session"
-
- restored = resolver.delete_session("MODEL_API_KEY")
- assert restored["source"] != "session"
- assert resolver.status("env://MODEL_API_KEY")["source"] == "missing"
-
-
-def test_credential_resolver_rejects_unsafe_session_values():
- resolver = CredentialResolver()
-
- for value in {"", " leading", "trailing ", "line\nbreak"}:
- with pytest.raises(StudioError) as captured:
- resolver.put_session("MODEL_API_KEY", value)
- assert captured.value.code == "SECRET_VALUE_INVALID"
-
- with pytest.raises(StudioError) as invalid_name:
- resolver.put_session("lowercase-key", "secret")
- assert invalid_name.value.code == "SECRET_REFERENCE_INVALID"
-
-
-def test_credential_resolver_clears_all_session_values(monkeypatch):
- resolver = CredentialResolver()
- monkeypatch.delenv("FIRST_KEY", raising=False)
- monkeypatch.delenv("SECOND_KEY", raising=False)
- resolver.put_session("FIRST_KEY", "first-secret")
- resolver.put_session("SECOND_KEY", "second-secret")
-
- resolver.clear_session()
-
- assert resolver.status("env://FIRST_KEY")["configured"] is False
- assert resolver.status("env://SECOND_KEY")["configured"] is False
-
-
-@pytest.mark.asyncio
-async def test_network_guard_denies_metadata_and_private_dns(monkeypatch):
- guard = NetworkGuard()
- policy = NetworkPolicy(allowed_hosts=["model.example.com"])
-
- monkeypatch.setattr(
- socket,
- "getaddrinfo",
- lambda *_args, **_kwargs: [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("10.0.0.2", 443))],
- )
- with pytest.raises(StudioError) as private:
- await guard.check(
- "https://model.example.com/v1/chat/completions",
- policy,
- )
- assert private.value.code == "NETWORK_TARGET_DENIED"
-
- with pytest.raises(StudioError) as metadata:
- await guard.check(
- "http://169.254.169.254/latest/meta-data",
- NetworkPolicy(
- allowed_hosts=["169.254.169.254"],
- allow_private_network=True,
- ),
- )
- assert metadata.value.code == "NETWORK_TARGET_DENIED"
-
-
-@pytest.mark.asyncio
-async def test_network_guard_allows_explicit_private_target(monkeypatch):
- monkeypatch.setattr(
- socket,
- "getaddrinfo",
- lambda *_args, **_kwargs: [
- (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("127.0.0.1", 8000))
- ],
- )
-
- await NetworkGuard().check(
- "http://localhost:8000/v1/chat/completions",
- NetworkPolicy(
- allowed_hosts=["localhost"],
- allow_private_network=True,
- ),
- )
-
-
-@pytest.mark.asyncio
-async def test_model_client_sends_response_format_when_allowed(monkeypatch):
- monkeypatch.setenv("MODEL_API_KEY", "secret-value")
- captured = []
-
- def handler(request: httpx.Request) -> httpx.Response:
- captured.append(__import__("json").loads(request.content))
- return httpx.Response(
- 200,
- json={"choices": [{"message": {"content": "{}"}, "finish_reason": "stop"}]},
- )
-
- client = OpenAICompatibleModelClient(
- network_guard=AllowNetwork(),
- transport=httpx.MockTransport(handler),
- )
- await client.complete(
- _model(),
- messages=[{"role": "user", "content": "compose"}],
- network_policy=NetworkPolicy(allowed_hosts=["model.example.com"]),
- timeout_seconds=10,
- max_attempts=1,
- backoff_seconds=0,
- response_format={"type": "json_object"},
- )
-
- assert captured[0]["response_format"] == {"type": "json_object"}
-
-
-@pytest.mark.asyncio
-async def test_model_client_omits_response_format_when_disabled(monkeypatch):
- monkeypatch.setenv("MODEL_API_KEY", "secret-value")
- captured = []
-
- def handler(request: httpx.Request) -> httpx.Response:
- captured.append(__import__("json").loads(request.content))
- return httpx.Response(
- 200,
- json={"choices": [{"message": {"content": "{}"}, "finish_reason": "stop"}]},
- )
-
- model = _model()
- model.parameters = model.parameters.model_copy(update={"allow_json_response_format": False})
- client = OpenAICompatibleModelClient(
- network_guard=AllowNetwork(),
- transport=httpx.MockTransport(handler),
- )
- await client.complete(
- model,
- messages=[],
- network_policy=NetworkPolicy(allowed_hosts=["model.example.com"]),
- timeout_seconds=10,
- max_attempts=1,
- backoff_seconds=0,
- response_format={"type": "json_object"},
- )
-
- assert "response_format" not in captured[0]
-
-
-@pytest.mark.asyncio
-async def test_model_client_retries_400_without_response_format(monkeypatch):
- monkeypatch.setenv("MODEL_API_KEY", "secret-value")
- captured = []
-
- def handler(request: httpx.Request) -> httpx.Response:
- payload = __import__("json").loads(request.content)
- captured.append(payload)
- if "response_format" in payload:
- return httpx.Response(
- 400,
- json={"error": {"message": "response_format is not supported"}},
- )
- return httpx.Response(
- 200,
- json={"choices": [{"message": {"content": "{}"}, "finish_reason": "stop"}]},
- )
-
- client = OpenAICompatibleModelClient(
- network_guard=AllowNetwork(),
- transport=httpx.MockTransport(handler),
- )
- result = await client.complete(
- _model(),
- messages=[],
- network_policy=NetworkPolicy(allowed_hosts=["model.example.com"]),
- timeout_seconds=10,
- max_attempts=1,
- backoff_seconds=0,
- response_format={"type": "json_object"},
- )
-
- assert result.content == "{}"
- assert len(captured) == 2
- assert "response_format" in captured[0]
- assert "response_format" not in captured[1]
-
-
-@pytest.mark.asyncio
-async def test_model_client_retries_length_truncation_with_larger_budget(monkeypatch):
- monkeypatch.setenv("MODEL_API_KEY", "secret-value")
- requests: list[dict] = []
-
- def handler(request: httpx.Request) -> httpx.Response:
- body = __import__("json").loads(request.content)
- requests.append(body)
- if len(requests) == 1:
- return httpx.Response(
- 200,
- json={
- "choices": [
- {
- "message": {"role": "assistant", "content": ""},
- "finish_reason": "length",
- }
- ],
- "usage": {"total_tokens": 64},
- },
- )
- return httpx.Response(
- 200,
- json={
- "choices": [
- {
- "message": {"role": "assistant", "content": '{"ok": true}'},
- "finish_reason": "stop",
- }
- ],
- "usage": {"total_tokens": 128},
- },
- )
-
- client = OpenAICompatibleModelClient(
- network_guard=AllowNetwork(),
- transport=httpx.MockTransport(handler),
- )
- result = await client.complete(
- _model(),
- messages=[],
- network_policy=NetworkPolicy(allowed_hosts=["model.example.com"]),
- timeout_seconds=10,
- max_attempts=1,
- backoff_seconds=0,
- retry_on_length=True,
- )
-
- assert result.content == '{"ok": true}'
- assert len(requests) == 2
- assert requests[0]["max_tokens"] == 64
- assert requests[1]["max_tokens"] == 16384
-
-
-@pytest.mark.asyncio
-async def test_model_client_length_retry_exhausted_raises_empty_response(monkeypatch):
- monkeypatch.setenv("MODEL_API_KEY", "secret-value")
-
- def handler(_request: httpx.Request) -> httpx.Response:
- return httpx.Response(
- 200,
- json={
- "choices": [
- {
- "message": {"role": "assistant", "content": ""},
- "finish_reason": "length",
- }
- ],
- "usage": {"total_tokens": 64},
- },
- )
-
- client = OpenAICompatibleModelClient(
- network_guard=AllowNetwork(),
- transport=httpx.MockTransport(handler),
- )
- with pytest.raises(StudioError) as captured:
- await client.complete(
- _model(),
- messages=[],
- network_policy=NetworkPolicy(allowed_hosts=["model.example.com"]),
- timeout_seconds=10,
- max_attempts=1,
- backoff_seconds=0,
- retry_on_length=True,
- )
- assert captured.value.code == "MODEL_EMPTY_RESPONSE"
- assert captured.value.details == {"finishReason": "length"}
-
-
-@pytest.mark.asyncio
-async def test_model_client_no_length_retry_by_default(monkeypatch):
- monkeypatch.setenv("MODEL_API_KEY", "secret-value")
- calls = []
-
- def handler(_request: httpx.Request) -> httpx.Response:
- calls.append(1)
- return httpx.Response(
- 200,
- json={
- "choices": [
- {
- "message": {"role": "assistant", "content": ""},
- "finish_reason": "length",
- }
- ],
- "usage": {"total_tokens": 64},
- },
- )
-
- client = OpenAICompatibleModelClient(
- network_guard=AllowNetwork(),
- transport=httpx.MockTransport(handler),
- )
- with pytest.raises(StudioError) as captured:
- await client.complete(
- _model(),
- messages=[],
- network_policy=NetworkPolicy(allowed_hosts=["model.example.com"]),
- timeout_seconds=10,
- max_attempts=2,
- backoff_seconds=0,
- )
- assert captured.value.code == "MODEL_EMPTY_RESPONSE"
- assert len(calls) == 1
-
-
-@pytest.mark.asyncio
-async def test_model_client_omits_unset_sampling_parameters(monkeypatch):
- """未显式配置的 temperature/max_tokens/top_p 一律不出现在 payload。"""
-
- monkeypatch.setenv("MODEL_API_KEY", "secret-value")
- captured: dict = {}
-
- def handler(request: httpx.Request) -> httpx.Response:
- captured["json"] = __import__("json").loads(request.content)
- return httpx.Response(
- 200,
- json={
- "choices": [
- {"message": {"role": "assistant", "content": "OK"}, "finish_reason": "stop"}
- ]
- },
- )
-
- client = OpenAICompatibleModelClient(
- network_guard=AllowNetwork(),
- transport=httpx.MockTransport(handler),
- )
- await client.complete(
- ResolvedModel(
- provider="openai-compatible",
- model="kimi-k2",
- endpoint_url="https://model.example.com/v1/chat/completions",
- credential_ref="env://MODEL_API_KEY",
- parameters=ModelParameters(),
- ),
- messages=[],
- network_policy=NetworkPolicy(allowed_hosts=["model.example.com"]),
- timeout_seconds=10,
- max_attempts=1,
- backoff_seconds=0,
- )
-
- body = captured["json"]
- assert "temperature" not in body
- assert "max_tokens" not in body
- assert "top_p" not in body
-
-
-@pytest.mark.asyncio
-async def test_model_client_sends_explicitly_configured_sampling_parameters(monkeypatch):
- monkeypatch.setenv("MODEL_API_KEY", "secret-value")
- captured: dict = {}
-
- def handler(request: httpx.Request) -> httpx.Response:
- captured["json"] = __import__("json").loads(request.content)
- return httpx.Response(
- 200,
- json={
- "choices": [
- {"message": {"role": "assistant", "content": "OK"}, "finish_reason": "stop"}
- ]
- },
- )
-
- client = OpenAICompatibleModelClient(
- network_guard=AllowNetwork(),
- transport=httpx.MockTransport(handler),
- )
- await client.complete(
- ResolvedModel(
- provider="openai-compatible",
- model="glm-5-3",
- endpoint_url="https://model.example.com/v1/chat/completions",
- credential_ref="env://MODEL_API_KEY",
- parameters=ModelParameters(temperature=0.7, max_tokens=8192, top_p=0.9),
- ),
- messages=[],
- network_policy=NetworkPolicy(allowed_hosts=["model.example.com"]),
- timeout_seconds=10,
- max_attempts=1,
- backoff_seconds=0,
- )
-
- body = captured["json"]
- assert body["temperature"] == 0.7
- assert body["max_tokens"] == 8192
- assert body["top_p"] == 0.9
-
-
-@pytest.mark.asyncio
-async def test_model_client_captures_reasoning_content(monkeypatch):
- """chat-completions 响应的 reasoning_content 必须进入 ModelResponse.reasoning。"""
-
- monkeypatch.setenv("MODEL_API_KEY", "secret-value")
-
- def handler(_request: httpx.Request) -> httpx.Response:
- return httpx.Response(
- 200,
- json={
- "choices": [
- {
- "message": {
- "role": "assistant",
- "content": "12,093",
- "reasoning_content": "先计算 417*29=12093。",
- },
- "finish_reason": "stop",
- }
- ],
- "usage": {"prompt_tokens": 5, "completion_tokens": 2, "total_tokens": 7},
- },
- )
-
- client = OpenAICompatibleModelClient(
- network_guard=AllowNetwork(),
- transport=httpx.MockTransport(handler),
- )
- result = await client.complete(
- _model(),
- messages=[{"role": "user", "content": "test"}],
- network_policy=NetworkPolicy(allowed_hosts=["model.example.com"]),
- timeout_seconds=10,
- max_attempts=1,
- backoff_seconds=0,
- )
-
- assert result.reasoning == "先计算 417*29=12093。"
-
-
-@pytest.mark.asyncio
-async def test_model_client_repairs_non_streaming_reasoning_only_tool_turn(monkeypatch):
- monkeypatch.setenv("MODEL_API_KEY", "secret-value")
- requests: list[dict] = []
-
- def handler(request: httpx.Request) -> httpx.Response:
- payload = __import__("json").loads(request.content)
- requests.append(payload)
- if len(requests) == 1:
- return httpx.Response(
- 200,
- json={
- "choices": [
- {
- "message": {
- "role": "assistant",
- "content": "",
- "reasoning_content": "I should delegate this task.",
- },
- "finish_reason": "stop",
- }
- ]
- },
- )
- return httpx.Response(
- 200,
- json={
- "choices": [
- {
- "message": {
- "role": "assistant",
- "content": "",
- "tool_calls": [
- {
- "id": "call-delegate",
- "type": "function",
- "function": {
- "name": "delegate_task",
- "arguments": '{"task":"build core"}',
- },
- }
- ],
- },
- "finish_reason": "tool_calls",
- }
- ]
- },
- )
-
- client = OpenAICompatibleModelClient(
- network_guard=AllowNetwork(), transport=httpx.MockTransport(handler)
- )
- result = await client.complete(
- _model(),
- messages=[{"role": "user", "content": "delegate the implementation"}],
- network_policy=NetworkPolicy(allowed_hosts=["model.example.com"]),
- timeout_seconds=10,
- max_attempts=1,
- backoff_seconds=0,
- tools=[
- {
- "type": "function",
- "function": {
- "name": "delegate_task",
- "parameters": {
- "type": "object",
- "properties": {"task": {"type": "string"}},
- "required": ["task"],
- },
- },
- }
- ],
- allow_empty=True,
- )
-
- assert len(requests) == 2
- assert requests[0]["tool_choice"] == "auto"
- assert requests[0]["parallel_tool_calls"] is True
- # 修复轮不再强推 tool_choice=required(那正是"只回 reasoning"的诱因),
- # 改为按兼容档位关闭思考;glm 命中 zai 档,支持 thinking 字段。
- assert requests[1]["tool_choice"] == "auto"
- assert requests[1]["parallel_tool_calls"] is True
- assert requests[1]["thinking"] == {"type": "disabled"} # 修复轮关思考
- assert "reasoning only" in requests[1]["messages"][-1]["content"]
- assert [(call.id, call.name) for call in result.tool_calls] == [
- ("call-delegate", "delegate_task")
- ]
-
-
-@pytest.mark.asyncio
-async def test_model_client_can_leave_reasoning_only_recovery_to_native_loop(monkeypatch):
- monkeypatch.setenv("MODEL_API_KEY", "secret-value")
- requests = []
-
- def handler(request: httpx.Request) -> httpx.Response:
- requests.append(__import__("json").loads(request.content))
- return httpx.Response(
- 200,
- json={
- "choices": [
- {
- "message": {
- "role": "assistant",
- "content": "",
- "reasoning_content": "thinking",
- },
- "finish_reason": "stop",
- }
- ]
- },
- )
-
- client = OpenAICompatibleModelClient(
- network_guard=AllowNetwork(), transport=httpx.MockTransport(handler)
- )
- result = await client.complete(
- _model(),
- messages=[{"role": "user", "content": "read value"}],
- network_policy=NetworkPolicy(allowed_hosts=["model.example.com"]),
- timeout_seconds=10,
- max_attempts=1,
- backoff_seconds=0,
- tools=[{"type": "function", "function": {"name": "read_value", "parameters": {}}}],
- allow_empty=True,
- retry_reasoning_only=False,
- )
- assert len(requests) == 1
- assert result.empty_reasoning_only is True
-
-
-@pytest.mark.asyncio
-async def test_model_client_tolerates_repeated_reasoning_only_tool_turn(monkeypatch):
- """回归(2026-09-18):思考型端点在工具回合连续只回 reasoning_content 时,
- 不得升级成 MODEL_EMPTY_RESPONSE——那会被 provider 重试链放大成整轮 ABORT。
- 正确语义是"可见空回合":返回空 content、保留 reasoning,交由上层循环决定。
- """
-
- monkeypatch.setenv("MODEL_API_KEY", "secret-value")
- calls: list[dict] = []
-
- def handler(request: httpx.Request) -> httpx.Response:
- calls.append(__import__("json").loads(request.content))
- return httpx.Response(
- 200,
- json={
- "choices": [
- {
- "message": {
- "role": "assistant",
- "content": "",
- "reasoning_content": "still thinking",
- },
- "finish_reason": "stop",
- }
- ],
- "usage": {"total_tokens": 12},
- },
- )
-
- client = OpenAICompatibleModelClient(
- network_guard=AllowNetwork(), transport=httpx.MockTransport(handler)
- )
- result = await client.complete(
- _model(),
- messages=[{"role": "user", "content": "delegate the implementation"}],
- network_policy=NetworkPolicy(allowed_hosts=["model.example.com"]),
- timeout_seconds=10,
- max_attempts=1,
- backoff_seconds=0,
- tools=[
- {
- "type": "function",
- "function": {
- "name": "delegate_task",
- "parameters": {
- "type": "object",
- "properties": {"task": {"type": "string"}},
- "required": ["task"],
- },
- },
- }
- ],
- allow_empty=True,
- )
-
- assert len(calls) == 2 # 原始请求 + 一次修复
- assert calls[1]["tool_choice"] == "auto"
- assert result.content == ""
- assert result.tool_calls == []
- assert result.reasoning == "still thinking"
-
-
-@pytest.mark.asyncio
-async def test_model_client_disables_thinking_when_budget_cannot_hold_it(monkeypatch):
- """回归(2026-09-18):始终思考的端点在"输出预算 <= 思考预算"时必须关思考。
-
- 事故形态:委派决策回合被压到 2048,模型把 2048 全花在 reasoning 上,
- 正文与工具调用为 0,单次调用耗 100-160 秒且零产出。
- """
-
- monkeypatch.setenv("MODEL_API_KEY", "secret-value")
- seen: list[dict] = []
-
- def handler(request: httpx.Request) -> httpx.Response:
- seen.append(__import__("json").loads(request.content))
- return httpx.Response(
- 200,
- json={
- "choices": [
- {"message": {"role": "assistant", "content": "OK"}, "finish_reason": "stop"}
- ]
- },
- )
-
- client = OpenAICompatibleModelClient(
- network_guard=AllowNetwork(), transport=httpx.MockTransport(handler)
- )
- # 无工具 + 小预算(glm 命中 zai 档,思考预算 32000)→ 关思考
- await client.complete(
- _model(),
- messages=[{"role": "user", "content": "x"}],
- network_policy=NetworkPolicy(allowed_hosts=["model.example.com"]),
- timeout_seconds=10,
- max_attempts=1,
- backoff_seconds=0,
- max_output_tokens=2_048,
- )
- # 该 fixture 走 zai 档(官方语义):预算 2048 < 思考预算 32000 → 关思考;
- # 预算不被擅自抬高(slot 优化只对声明了 preferred_output_tokens 的端点生效)
- assert seen[0]["thinking"] == {"type": "disabled"}
- assert seen[0]["max_tokens"] == 2_048
-
- # 无工具 + 大预算(> 思考预算)→ 保持原预算
- await client.complete(
- _model(),
- messages=[{"role": "user", "content": "x"}],
- network_policy=NetworkPolicy(allowed_hosts=["model.example.com"]),
- timeout_seconds=10,
- max_attempts=1,
- backoff_seconds=0,
- max_output_tokens=64_000,
- )
- assert "thinking" not in seen[1]
- assert seen[1]["max_tokens"] == 64_000
-
-
-@pytest.mark.asyncio
-async def test_model_client_reasoning_absent_is_empty(monkeypatch):
- monkeypatch.setenv("MODEL_API_KEY", "secret-value")
-
- def handler(_request: httpx.Request) -> httpx.Response:
- return httpx.Response(
- 200,
- json={
- "choices": [
- {"message": {"role": "assistant", "content": "OK"}, "finish_reason": "stop"}
- ],
- },
- )
-
- client = OpenAICompatibleModelClient(
- network_guard=AllowNetwork(),
- transport=httpx.MockTransport(handler),
- )
- result = await client.complete(
- _model(),
- messages=[{"role": "user", "content": "test"}],
- network_policy=NetworkPolicy(allowed_hosts=["model.example.com"]),
- timeout_seconds=10,
- max_attempts=1,
- backoff_seconds=0,
- )
-
- assert not result.reasoning
-
-
-def _anthropic_model() -> ResolvedModel:
- return ResolvedModel(
- provider="openai-compatible",
- model="claude-sonnet-5",
- endpoint_url="https://model.example.com/v1/messages",
- credential_ref="env://MODEL_API_KEY",
- parameters=ModelParameters(temperature=0.1),
- wire_api="anthropic",
- )
-
-
-@pytest.mark.asyncio
-async def test_model_client_sends_anthropic_messages_request(monkeypatch):
- monkeypatch.setenv("MODEL_API_KEY", "secret-value")
- captured = {}
-
- def handler(request: httpx.Request) -> httpx.Response:
- captured["x-api-key"] = request.headers["x-api-key"]
- captured["anthropic-version"] = request.headers["anthropic-version"]
- captured["json"] = __import__("json").loads(request.content)
- return httpx.Response(
- 200,
- json={
- "content": [
- {"type": "text", "text": "OK"},
- {
- "type": "tool_use",
- "id": "toolu_1",
- "name": "lookup",
- "input": {"q": "ksadk"},
- },
- ],
- "stop_reason": "tool_use",
- "usage": {"input_tokens": 12, "output_tokens": 5},
- },
- )
-
- client = OpenAICompatibleModelClient(
- network_guard=AllowNetwork(),
- transport=httpx.MockTransport(handler),
- )
- result = await client.complete(
- _anthropic_model(),
- messages=[
- {"role": "system", "content": "be brief"},
- {"role": "user", "content": "test"},
- ],
- network_policy=NetworkPolicy(allowed_hosts=["model.example.com"]),
- timeout_seconds=10,
- max_attempts=1,
- backoff_seconds=0,
- tools=[
- {
- "type": "function",
- "function": {
- "name": "lookup",
- "description": "search",
- "parameters": {"type": "object", "properties": {}},
- },
- }
- ],
- )
-
- assert captured["x-api-key"] == "secret-value"
- assert captured["anthropic-version"] == "2023-06-01"
- payload = captured["json"]
- assert payload["model"] == "claude-sonnet-5"
- assert payload["system"] == "be brief"
- # Anthropic Messages wire 把 max_tokens 设为必填,profile 未配置时用安全默认。
- assert payload["max_tokens"] == 8192
- assert payload["tools"][0]["name"] == "lookup"
- assert payload["tools"][0]["input_schema"] == {"type": "object", "properties": {}}
- assert result.content == "OK"
- assert result.finish_reason == "tool_calls"
- assert [call.name for call in result.tool_calls] == ["lookup"]
- assert __import__("json").loads(result.tool_calls[0].arguments) == {"q": "ksadk"}
- assert result.usage.input_tokens == 12
-
-
-@pytest.mark.asyncio
-async def test_model_client_streams_anthropic_events(monkeypatch):
- monkeypatch.setenv("MODEL_API_KEY", "secret-value")
- captured = {}
-
- def handler(request: httpx.Request) -> httpx.Response:
- captured["json"] = __import__("json").loads(request.content)
- body = (
- b'event: message_start\n'
- b'data: {"type":"message_start","message":{"usage":{"input_tokens":7}}}\n\n'
- b'event: content_block_start\n'
- b'data: {"type":"content_block_start","index":0,'
- b'"content_block":{"type":"text","text":""}}\n\n'
- b'event: content_block_delta\n'
- b'data: {"type":"content_block_delta","index":0,'
- b'"delta":{"type":"text_delta","text":"Hel"}}\n\n'
- b'event: content_block_delta\n'
- b'data: {"type":"content_block_delta","index":0,'
- b'"delta":{"type":"text_delta","text":"lo"}}\n\n'
- b'event: content_block_stop\n'
- b'data: {"type":"content_block_stop","index":0}\n\n'
- b'event: content_block_start\n'
- b'data: {"type":"content_block_start","index":1,'
- b'"content_block":{"type":"tool_use","id":"toolu_9","name":"lookup"}}\n\n'
- b'event: content_block_delta\n'
- b'data: {"type":"content_block_delta","index":1,'
- b'"delta":{"type":"input_json_delta","partial_json":"{\\"q\\":"}}\n\n'
- b'event: content_block_delta\n'
- b'data: {"type":"content_block_delta","index":1,'
- b'"delta":{"type":"input_json_delta","partial_json":"\\"ks\\"}"}}\n\n'
- b'event: content_block_stop\n'
- b'data: {"type":"content_block_stop","index":1}\n\n'
- b'event: message_delta\n'
- b'data: {"type":"message_delta",'
- b'"delta":{"stop_reason":"tool_use"},"usage":{"output_tokens":9}}\n\n'
- b'event: message_stop\n'
- b'data: {"type":"message_stop"}\n\n'
- )
- return httpx.Response(200, headers={"content-type": "text/event-stream"}, content=body)
-
- client = OpenAICompatibleModelClient(
- network_guard=AllowNetwork(),
- transport=httpx.MockTransport(handler),
- )
- chunks = [
- chunk
- async for chunk in client.stream(
- _anthropic_model(),
- messages=[{"role": "user", "content": "test"}],
- network_policy=NetworkPolicy(allowed_hosts=["model.example.com"]),
- timeout_seconds=10,
- tools=[
- {
- "type": "function",
- "function": {"name": "lookup", "parameters": {"type": "object"}},
- }
- ],
- )
- ]
-
- assert captured["json"]["stream"] is True
- assert captured["json"]["max_tokens"] == 8192
- assert "".join(chunk.text for chunk in chunks if chunk.text) == "Hello"
- done = chunks[-1]
- assert done.done is True
- assert [call.name for call in done.tool_calls] == ["lookup"]
- assert __import__("json").loads(done.tool_calls[0].arguments) == {"q": "ks"}
- assert done.usage is not None
- assert done.usage.input_tokens == 7
- assert done.usage.output_tokens == 9
diff --git a/tests/studio/test_model_empty_output_limit.py b/tests/studio/test_model_empty_output_limit.py
deleted file mode 100644
index b8ded661e..000000000
--- a/tests/studio/test_model_empty_output_limit.py
+++ /dev/null
@@ -1,55 +0,0 @@
-"""Explicit empty-output compatibility repair must never bypass a terminal reason."""
-
-import json
-
-import httpx
-import pytest
-
-from ksadk.model_gateway.client import ModelGatewayClient
-from tests.studio.test_model_client import AllowNetwork
-from tests.studio.test_model_wire_usage import sse
-from tests.studio.test_native_model_port import MODEL, NETWORK
-
-
-def chat_response(_streaming):
- return httpx.Response(200, json={"choices": [{
- "message": {"role": "assistant", "content": "42"}, "finish_reason": "length",
- }]})
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize("reason", [
- "length", "incomplete", "max_tokens", "max_output_tokens", "output_limit",
- "context_overflow", "context_length_exceeded", "policy_abort", "user_abort",
- "canceled", "cancelled",
-])
-@pytest.mark.parametrize("retry", [False, True])
-async def test_empty_non_success_stream_repairs_only_explicit_output_caps(monkeypatch, reason, retry):
- monkeypatch.setenv("FIXTURE_KEY", "fixture-key")
- captured = []
-
- def handler(incoming):
- captured.append(json.loads(incoming.content))
- if len(captured) == 1:
- return httpx.Response(200, headers={"content-type": "text/event-stream"}, content=sse([
- {"choices": [{"index": 0, "delta": {}, "finish_reason": reason}]}, "[DONE]",
- ]))
- return chat_response(False)
-
- gateway = ModelGatewayClient(network_guard=AllowNetwork(), transport=httpx.MockTransport(handler))
- try:
- chunks = [chunk async for chunk in gateway.stream(
- MODEL, messages=[{"role": "user", "content": "Fixture."}],
- network_policy=NETWORK, timeout_seconds=2.5, max_output_tokens=128,
- output_budget_mode="fixed", retry_empty_stream=retry,
- )]
- repair = retry and reason in {
- "length", "incomplete", "max_tokens", "max_output_tokens", "output_limit",
- }
- assert len(captured) == (2 if repair else 1)
- assert all(body["max_tokens"] == 128 for body in captured)
- assert chunks[-1].done and chunks[-1].finish_reason == ("length" if repair else reason)
- assert not chunks[-1].tool_calls
- assert "".join(chunk.text for chunk in chunks) == ("42" if repair else "")
- finally:
- await gateway.aclose()
diff --git a/tests/studio/test_model_incomplete_finish_reason.py b/tests/studio/test_model_incomplete_finish_reason.py
deleted file mode 100644
index 9ecfb4968..000000000
--- a/tests/studio/test_model_incomplete_finish_reason.py
+++ /dev/null
@@ -1,129 +0,0 @@
-"""Observed non-success termination survives an unfilled streamed tool call."""
-import json
-import socket
-
-import httpx
-import pytest
-
-from ksadk.harness.native.completion import TaskContract
-from ksadk.harness.native.machine import reduce_model
-from ksadk.harness.native.model import ModelProfile, normalize_response
-from ksadk.harness.native.ports import RunConfiguration, RunLimits
-from ksadk.harness.native.state import RunPhase, RunSnapshot
-from ksadk.model_gateway.client import ModelGatewayClient
-from tests.studio.test_model_client import AllowNetwork
-from tests.studio.test_native_model_port import SCOPE, TOOL, port, request
-
-
-@pytest.fixture(autouse=True)
-def no_network_or_credentials(monkeypatch):
- monkeypatch.setenv("FIXTURE_KEY", "local-synthetic-value")
- monkeypatch.delenv("KSADK_MODEL_COMPAT_RULE", raising=False)
-
- def denied(*_args, **_kwargs):
- raise AssertionError("No network is permitted by this fixture")
-
- monkeypatch.setattr(socket, "getaddrinfo", denied)
- monkeypatch.setattr(socket.socket, "connect", denied)
- monkeypatch.setattr(socket.socket, "connect_ex", denied)
-
-
-def body(*, finish, arguments="", done=True, usage=True):
- chunks = [{"choices": [{"delta": {"tool_calls": [{
- "index": 0, "id": "call-1", "type": "function",
- "function": {"name": TOOL.name, "arguments": arguments},
- }]}, "finish_reason": finish}]}]
- if usage:
- chunks.append({"choices": [], "usage": {
- "prompt_tokens": 20, "completion_tokens": 1024,
- }})
- return b"".join(
- ("data: " + json.dumps(chunk) + "\n\n").encode() for chunk in chunks
- ) + (b"data: [DONE]\n\n" if done else b"")
-
-
-async def result_from(raw):
- dispatched = []
-
- def provider(incoming):
- dispatched.append(incoming.url.host)
- return httpx.Response(200, headers={"content-type": "text/event-stream"}, content=raw)
-
- client = ModelGatewayClient(
- network_guard=AllowNetwork(), transport=httpx.MockTransport(provider)
- )
- req = request(streaming=True, tools=(TOOL,))
- try:
- events = [event async for event in port(client, req).stream(req)]
- finally:
- await client.aclose()
- assert dispatched == ["example.test"]
- assert len([event for event in events if event.kind == "final"]) == 1
- return events[-1].result
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize("done", [False, True])
-@pytest.mark.parametrize("finish,expected", [
- ("length", "output_limit"), ("max_tokens", "output_limit"),
- ("max_output_tokens", "output_limit"), ("output_limit", "output_limit"),
- ("incomplete", "output_limit"), ("content_filter", "policy_abort"),
- ("policy_abort", "policy_abort"), ("context_length_exceeded", "context_overflow"),
- ("context_overflow", "context_overflow"), ("canceled", "user_abort"),
- ("cancelled", "user_abort"), ("user_abort", "user_abort"),
-])
-async def test_explicit_non_success_finish_does_not_become_transport_retry(finish, expected, done):
- result = await result_from(body(finish=finish, done=done))
- assert result.response_kind == expected
- assert result.finish_reason == finish
- assert result.tool_calls == ()
- assert result.usage.output_tokens == 1024
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize("finish", [None, "stop", "tool_calls"])
-@pytest.mark.parametrize("done", [False, True])
-async def test_missing_or_success_finish_never_promotes_unfilled_arguments(finish, done):
- result = await result_from(body(finish=finish, done=done))
- assert result.response_kind == "provider_retryable_error"
- assert result.failure_kind == "incomplete_response"
- assert result.tool_calls == ()
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize("arguments", ["{", '{"value":', "{}"])
-async def test_nonempty_argument_fragments_keep_existing_length_precedence(arguments):
- result = await result_from(body(finish="length", arguments=arguments))
- assert result.response_kind == "output_limit"
- assert result.tool_calls == ()
-
-
-@pytest.mark.asyncio
-async def test_observed_finish_does_not_fabricate_missing_usage():
- result = await result_from(body(finish="length", usage=False))
- assert result.response_kind == "output_limit"
- assert result.usage is None
- assert result.tool_calls == ()
-
-
-@pytest.mark.asyncio
-async def test_length_uses_existing_continuation_pool_without_tool_execution():
- result = await result_from(body(finish="length"))
- config = RunConfiguration(
- profile=ModelProfile(profile_id="local", profile_version="1", provider_family="test",
- max_continuations=1, max_provider_retries=1),
- limits=RunLimits(max_output_restarts=0), contract=TaskContract(revision="1", items=()),
- )
- before = RunSnapshot(scope=SCOPE, run_id="run", session_id="s", turn_id="t", goal="goal",
- phase=RunPhase.REQUESTING_MODEL)
- after = reduce_model(before, result, config)
- assert (after.model_calls, after.tool_calls) == (1, 0)
- assert (after.provider_errors, after.continuations) == (0, 1)
- final = reduce_model(after, result, config)
- assert final.reason == "continuation_budget_exhausted"
- assert final.model_calls == 2 and final.tool_calls == 0
- retry = normalize_response(request_id="r", attempt_id="a", stream_complete=False)
- retried = reduce_model(before, retry, config)
- assert (retried.provider_errors, retried.continuations, retried.model_calls) == (1, 0, 1)
- exhausted = reduce_model(retried, retry, config)
- assert exhausted.reason == "provider_retryable_error_retry_exhausted"
diff --git a/tests/studio/test_model_wire_identity.py b/tests/studio/test_model_wire_identity.py
deleted file mode 100644
index 82e65fed5..000000000
--- a/tests/studio/test_model_wire_identity.py
+++ /dev/null
@@ -1,414 +0,0 @@
-"""Raw provider alternatives and identities must not become mixed Native facts."""
-
-import copy
-import json
-
-import httpx
-import pytest
-
-from ksadk.harness.native.model_runtime import exchange
-from ksadk.model_gateway.client import ModelGatewayClient
-from tests.studio.test_model_client import AllowNetwork
-from tests.studio.test_model_wire_usage import sse
-from tests.studio.test_native_model_port import MODEL, TOOL, port, request
-
-WIRES = ("chat", "responses", "anthropic")
-
-
-def frames(wire):
- if wire == "chat":
- return [
- {"id": "response-one", "model": "provider-alias", "choices": [
- {"index": 0, "delta": {"content": "42"}, "finish_reason": None},
- ], "usage": {"prompt_tokens": 12, "completion_tokens": 4}},
- {"id": "response-one", "model": "provider-alias", "choices": [
- {"index": 0, "delta": {}, "finish_reason": "stop"},
- ]},
- "[DONE]",
- ]
- if wire == "responses":
- return [
- {"type": "response.created", "response": {
- "id": "response-one", "model": "provider-alias",
- }},
- {"type": "response.output_text.delta", "response_id": "response-one", "delta": "42"},
- {"type": "response.completed", "response": {
- "id": "response-one", "model": "provider-alias",
- "usage": {"input_tokens": 12, "output_tokens": 4},
- }},
- ]
- return [
- {"type": "message_start", "message": {
- "id": "response-one", "model": "provider-alias",
- "usage": {"input_tokens": 12, "output_tokens": 0},
- }},
- {"type": "content_block_delta", "index": 0,
- "delta": {"type": "text_delta", "text": "42"}},
- {"type": "message_delta", "delta": {"stop_reason": "end_turn"},
- "usage": {"output_tokens": 4}},
- {"type": "message_stop"},
- ]
-
-
-async def collect(monkeypatch, wire, events, *, streaming=True, emit=None, public_summary=False):
- monkeypatch.setenv("FIXTURE_KEY", "fixture-key")
- calls = []
-
- def handler(incoming):
- calls.append(incoming)
- if streaming:
- if isinstance(events, httpx.AsyncByteStream):
- return httpx.Response(200, stream=events)
- return httpx.Response(
- 200, headers={"content-type": "text/event-stream"}, content=sse(events),
- )
- return httpx.Response(200, json=events)
-
- gateway = ModelGatewayClient(
- network_guard=AllowNetwork(), transport=httpx.MockTransport(handler),
- )
- current = request(streaming=streaming, tools=(TOOL,))
- model = MODEL.model_copy(update={"wire_api": wire, "parameters": MODEL.parameters.model_copy(
- update={"public_thinking_summary": public_summary},
- )})
- adapter = port(gateway, current, model=model)
- try:
- result = await exchange(adapter, current, emit=emit)
- assert len(calls) == 1
- return result
- finally:
- await gateway.aclose()
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize("wire", WIRES)
-async def test_stable_provider_alias_and_optional_identity_remain_compatible(monkeypatch, wire):
- result = await collect(monkeypatch, wire, frames(wire))
- assert result.response_kind == "final_candidate" and result.text == "42", result
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize("wire", WIRES)
-@pytest.mark.parametrize("field", ["id", "model"])
-async def test_one_attempt_does_not_mix_provider_response_identity(monkeypatch, wire, field):
- events = frames(wire)
- if wire == "chat":
- events[1][field] = "PRIVATE_FOREIGN"
- elif wire == "responses":
- events[-1]["response"][field] = "PRIVATE_FOREIGN"
- else:
- foreign = copy.deepcopy(events[0])
- foreign["message"][field] = "PRIVATE_FOREIGN"
- events.insert(1, foreign)
- result = await collect(monkeypatch, wire, events)
- assert result.failure_kind == "invalid_response", result
- assert result.gateway_error_code == "MODEL_RESPONSE_INVALID"
- assert not result.tool_calls
- assert "PRIVATE_FOREIGN" not in result.model_dump_json()
- if wire == "chat":
- assert (result.usage.input_tokens, result.usage.output_tokens) == (12, 4)
- elif wire == "anthropic":
- assert (result.usage.input_tokens, result.usage.output_tokens) == (12, 0)
- else:
- assert result.usage is None, "A foreign response's counters are not this attempt's evidence"
-
-
-@pytest.mark.asyncio
-async def test_responses_explicit_response_id_is_checked_before_text_projection(monkeypatch):
- events = frames("responses")
- events[1]["response_id"] = "PRIVATE_FOREIGN"
- result = await collect(monkeypatch, "responses", events)
- assert result.failure_kind == "invalid_response", result
- assert "PRIVATE_FOREIGN" not in result.model_dump_json()
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize("wire", WIRES)
-@pytest.mark.parametrize("bad", ["", " ", True, 7])
-async def test_supplied_response_identity_is_genuine_nonblank_text(monkeypatch, wire, bad):
- events = frames(wire)
- if wire == "chat":
- events[0]["id"] = bad
- elif wire == "responses":
- events[0]["response"]["id"] = bad
- else:
- events[0]["message"]["id"] = bad
- result = await collect(monkeypatch, wire, events)
- assert result.failure_kind == "invalid_response", result
- assert result.usage is None
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize("wire", WIRES)
-@pytest.mark.parametrize("raw", ["{PRIVATE_BROKEN", "[]", "null", "7"])
-async def test_invalid_data_frame_cannot_be_skipped_as_if_it_never_happened(monkeypatch, wire, raw):
- events = frames(wire)
- events.insert(1, raw)
- result = await collect(monkeypatch, wire, events)
- assert result.failure_kind == "invalid_response", result
- assert "PRIVATE_BROKEN" not in result.model_dump_json()
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize("streaming", [False, True])
-async def test_chat_projects_choice_zero_without_merging_alternative_text_or_tools(
- monkeypatch, streaming,
-):
- zero = {"index": 0, "delta": {"content": "42"},
- "message": {"content": "42"}, "finish_reason": "stop"}
- other = {"index": 1, "delta": {"content": "PRIVATE_ALTERNATIVE", "tool_calls": [
- {"index": 0, "id": "other-call", "function": {"name": "read_value", "arguments": "{}"}},
- ]}, "message": {"content": "PRIVATE_ALTERNATIVE"}, "finish_reason": "tool_calls"}
- packet = {"id": "response-one", "choices": [other, zero]}
- events = [packet, "[DONE]"] if streaming else packet
- result = await collect(monkeypatch, "chat", events, streaming=streaming)
- assert result.response_kind == "final_candidate" and result.text == "42", result
- assert not result.tool_calls
-
-
-@pytest.mark.asyncio
-async def test_chat_does_not_promote_an_alternative_only_frame_to_the_selected_choice(monkeypatch):
- events = frames("chat")
- events[0]["choices"][0]["delta"]["content"] = "4"
- events.insert(1, {"id": "response-one", "choices": [
- {"index": 1, "delta": {"content": "PRIVATE_ALTERNATIVE"}, "finish_reason": "stop"},
- ]})
- events[2]["choices"][0]["delta"]["content"] = "2"
- result = await collect(monkeypatch, "chat", events)
- assert result.response_kind == "final_candidate" and result.text == "42", result
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize("bad", [True, "0", -1])
-async def test_chat_choice_index_is_not_coerced(monkeypatch, bad):
- events = frames("chat")
- events[0]["choices"][0]["index"] = bad
- result = await collect(monkeypatch, "chat", events)
- assert result.failure_kind == "invalid_response", result
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize("changed", [False, True])
-async def test_chat_tool_id_is_stable_identity_not_argument_text(monkeypatch, changed):
- events = frames("chat")
- events[0]["choices"][0]["delta"] = {"tool_calls": [{
- "index": 0, "id": "call-one", "function": {"name": "read_value", "arguments": "{"},
- }]}
- events[1]["choices"][0]["delta"] = {"tool_calls": [{
- "index": 0, "id": "PRIVATE_FOREIGN" if changed else "call-one",
- "function": {"arguments": "}"},
- }]}
- events[1]["choices"][0]["finish_reason"] = "tool_calls"
- result = await collect(monkeypatch, "chat", events)
- if changed:
- assert result.failure_kind == "invalid_response", result
- assert not result.tool_calls
- assert "PRIVATE_FOREIGN" not in result.model_dump_json()
- else:
- assert result.response_kind == "tool_calls", result
- assert result.tool_calls[0].call_id == "call-one"
- assert result.tool_calls[0].name == "read_value" and result.tool_calls[0].arguments == {}
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize("wire", WIRES)
-async def test_invalid_visible_content_is_not_stringified_into_an_answer(monkeypatch, wire):
- events = frames(wire)
- if wire == "chat":
- events[0]["choices"][0]["delta"]["content"] = {"PRIVATE_OBJECT": 7}
- elif wire == "responses":
- events[1]["delta"] = {"PRIVATE_OBJECT": 7}
- else:
- events[1]["delta"]["text"] = {"PRIVATE_OBJECT": 7}
- result = await collect(monkeypatch, wire, events)
- assert result.failure_kind == "invalid_response", result
- assert "PRIVATE_OBJECT" not in result.model_dump_json()
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize("bad_tail", ["foreign", "malformed", "conflicting_finish"])
-async def test_chat_finish_with_usage_does_not_seal_before_the_response_boundary(
- monkeypatch, bad_tail,
-):
- events = frames("chat")
- events[0]["choices"][0]["delta"] = {"tool_calls": [{
- "index": 0, "id": "call-one",
- "function": {"name": "read_value", "arguments": "{}"},
- }]}
- events[1]["choices"][0]["finish_reason"] = "tool_calls"
- events[1]["usage"] = {"prompt_tokens": 12, "completion_tokens": 4}
- tail = copy.deepcopy(events[1])
- if bad_tail == "foreign":
- tail["id"] = "PRIVATE_FOREIGN"
- elif bad_tail == "malformed":
- tail = "{PRIVATE_BROKEN"
- else:
- tail["choices"][0]["finish_reason"] = "stop"
- events.insert(-1, tail)
- result = await collect(monkeypatch, "chat", events)
- assert result.failure_kind == "invalid_response", result
- assert not result.tool_calls, "An unsealed response cannot authorize a tool batch"
- assert (result.usage.input_tokens, result.usage.output_tokens) == (12, 4)
- assert "PRIVATE_" not in result.model_dump_json()
-
-
-@pytest.mark.asyncio
-async def test_chat_post_finish_usage_updates_are_consumed_before_sealing(monkeypatch):
- events = frames("chat")
- events[1]["usage"] = {"prompt_tokens": 12, "completion_tokens": 4}
- events.insert(-1, {"id": "response-one", "choices": [],
- "usage": {"prompt_tokens": 12, "completion_tokens": 7}})
- result = await collect(monkeypatch, "chat", events)
- assert result.response_kind == "final_candidate" and result.text == "42", result
- assert (result.usage.input_tokens, result.usage.output_tokens) == (12, 7)
-
-
-@pytest.mark.asyncio
-async def test_chat_finish_before_authoritative_tool_snapshot_keeps_its_finish_reason(monkeypatch):
- events = frames("chat")
- events[0]["choices"][0]["delta"] = {"tool_calls": [{
- "index": 0, "id": "call-one", "function": {"name": "read_value"},
- }]}
- events[1]["choices"][0]["finish_reason"] = "tool_calls"
- events.insert(-1, {"id": "response-one", "choices": [{
- "index": 0, "message": {"tool_calls": [{
- "index": 0, "id": "call-one",
- "function": {"name": "read_value", "arguments": {}},
- }]},
- }]})
- result = await collect(monkeypatch, "chat", events)
- assert result.response_kind == "tool_calls", result
- assert result.tool_calls[0].call_id == "call-one" and result.tool_calls[0].arguments == {}
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize("boundary", ["done", "eof"])
-async def test_chat_known_finish_with_optional_usage_can_seal_at_done_or_eof(monkeypatch, boundary):
- events = frames("chat")
- if boundary == "eof":
- events.pop()
- result = await collect(monkeypatch, "chat", events)
- assert result.response_kind == "final_candidate" and result.text == "42", result
- assert (result.usage.input_tokens, result.usage.output_tokens) == (12, 4)
-
-
-@pytest.mark.asyncio
-async def test_chat_read_failure_after_finish_keeps_usage_without_a_tool_batch(monkeypatch):
- class Interrupted(httpx.AsyncByteStream):
- closed = 0
-
- async def __aiter__(self):
- events = frames("chat")[:-1]
- events[0]["choices"][0]["delta"] = {"tool_calls": [{
- "index": 0, "id": "call-one",
- "function": {"name": "read_value", "arguments": "{}"},
- }]}
- events[1]["choices"][0]["finish_reason"] = "tool_calls"
- events[1]["usage"] = {"prompt_tokens": 12, "completion_tokens": 4}
- yield sse(events)
- raise httpx.ReadError("PRIVATE_TRANSPORT_BODY")
-
- async def aclose(self):
- self.closed += 1
-
- stream = Interrupted()
- result = await collect(monkeypatch, "chat", stream)
- assert result.response_kind in {"provider_terminal_error", "provider_retryable_error"}, result
- assert not result.tool_calls
- assert (result.usage.input_tokens, result.usage.output_tokens) == (12, 4)
- assert stream.closed == 1 and "PRIVATE_TRANSPORT_BODY" not in result.model_dump_json()
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize("case", ["chat", "responses", "anthropic", "chat_after_finish"])
-async def test_ordinary_studio_rejects_foreign_wire_identity_without_retry_or_tools(
- tmp_path, monkeypatch, case,
-):
- from ksadk.harness.native.state import RunScope
- from ksadk.studio.contracts import (
- AgentSpec,
- Instructions,
- ModelSpec,
- NetworkPolicy,
- RunStatus,
- RuntimeRef,
- SecuritySpec,
- )
- from ksadk.studio.service import StudioService
- from tests.studio.test_dsh_provider_registration import _managed_profile
-
- wire = "chat" if case == "chat_after_finish" else case
- events = frames(wire)
- if case == "chat_after_finish":
- events[1]["usage"] = {"prompt_tokens": 12, "completion_tokens": 4}
- foreign = copy.deepcopy(events[1])
- foreign["id"] = "PRIVATE_FOREIGN"
- events.insert(-1, foreign)
- elif wire == "chat":
- events[1]["id"] = "PRIVATE_FOREIGN"
- elif wire == "responses":
- events[-1]["response"]["id"] = "PRIVATE_FOREIGN"
- else:
- foreign = copy.deepcopy(events[0])
- foreign["message"]["id"] = "PRIVATE_FOREIGN"
- events.insert(1, foreign)
- calls = []
-
- def handler(incoming):
- calls.append(incoming)
- return httpx.Response(
- 200, headers={"content-type": "text/event-stream"}, content=sse(events),
- )
-
- class Gateway(ModelGatewayClient):
- def supports_streaming(self, model, *, requested=True):
- return requested
-
- _managed_profile(tmp_path, monkeypatch)
- monkeypatch.setenv("FIXTURE_KEY", "fixture-key")
- gateway = Gateway(network_guard=AllowNetwork(), transport=httpx.MockTransport(handler))
- studio = StudioService(
- tmp_path / "studio", model_client=gateway, native_harness_agent_ids=("wire-agent",),
- )
- try:
- studio.create_agent(
- agent_id="wire-agent", name="Native wire identity",
- spec=AgentSpec(
- runtime=RuntimeRef(type="harness"),
- instructions=Instructions(system="Answer the request."),
- model=ModelSpec(
- model="fixture-model", endpoint_url="https://example.test/v1/model",
- wire_api=wire, credential_ref="env://FIXTURE_KEY",
- ),
- security=SecuritySpec(
- allowed_permissions=["process:host-user"],
- network=NetworkPolicy(allowed_hosts=["example.test"]),
- ),
- ),
- )
- build = await studio.ensure_current_build("wire-agent")
- result = await studio.run_build(build.id, "Return 42.", "wire-session")
- assert result.status == RunStatus.FAILED, result.error
- assert len(calls) == 1 and json.loads(calls[0].content)["stream"] is True
- assert "PRIVATE_FOREIGN" not in result.model_dump_json()
- session = await studio.session_service.get_session_metadata("wire-session")
- scope = RunScope(
- tenant_id="local-studio", workspace_id=studio.workspace_record.workspace_id,
- user_id=session.user_id, agent_id=session.agent_id,
- )
- composer = studio._native_product_composer
- head = composer.store.session_head(scope, "wire-session")
- events = composer.store.events(scope, head.run_id)
- assert head.model_calls == 1 and head.tool_calls == 0
- assert sum(event.kind == "run.failed" for event in events) == 1
- assert not any(event.kind == "run.completed" for event in events)
- receipts = [event for event in events if event.kind == "usage.reported"]
- if wire == "responses":
- assert not receipts and result.usage.reported is False
- else:
- assert len(receipts) == 1 and result.usage.reported is True
- assert (result.usage.input_tokens, result.usage.output_tokens) == (
- 12, 0 if wire == "anthropic" else 4,
- )
- finally:
- await studio.aclose()
diff --git a/tests/studio/test_model_wire_usage.py b/tests/studio/test_model_wire_usage.py
deleted file mode 100644
index 40c680eb1..000000000
--- a/tests/studio/test_model_wire_usage.py
+++ /dev/null
@@ -1,336 +0,0 @@
-"""Provider bytes must not manufacture a complete, coerced usage report."""
-
-import json
-
-import httpx
-import pytest
-
-from ksadk.harness.native.model_runtime import exchange
-from ksadk.model_gateway.client import ModelGatewayClient
-from tests.studio.test_model_client import AllowNetwork
-from tests.studio.test_native_model_port import MODEL, port, request
-
-WIRES = ("chat", "responses", "anthropic")
-
-
-def payload(wire, usage):
- if wire == "chat":
- value = {"choices": [{"message": {"content": "42"}, "finish_reason": "stop"}]}
- elif wire == "responses":
- value = {"output_text": "42", "status": "completed", "output": [{
- "type": "message", "role": "assistant",
- "content": [{"type": "output_text", "text": "42"}],
- }]}
- else:
- value = {"content": [{"type": "text", "text": "42"}], "stop_reason": "end_turn"}
- if usage is not None:
- value["usage"] = usage
- return value
-
-
-def usage_for(wire, value):
- if wire != "chat" or not isinstance(value, dict):
- return value
- names = {"input_tokens": "prompt_tokens", "output_tokens": "completion_tokens"}
- return {names.get(key, key): item for key, item in value.items()}
-
-
-def stream_events(wire, usage):
- if wire == "chat":
- return [
- {"choices": [{"delta": {"content": "42"}, "finish_reason": None}]},
- {"choices": [{"delta": {}, "finish_reason": "stop"}], "usage": usage},
- "[DONE]",
- ]
- if wire == "responses":
- return [
- {"type": "response.output_text.delta", "delta": "42"},
- {"type": "response.completed", "response": {"usage": usage}},
- ]
- if isinstance(usage, dict):
- initial = {key: value for key, value in usage.items() if key != "output_tokens"}
- final = {key: value for key, value in usage.items() if key == "output_tokens"}
- else:
- initial, final = usage, None
- return [
- {"type": "message_start", "message": {"usage": initial}},
- {"type": "content_block_delta", "index": 0,
- "delta": {"type": "text_delta", "text": "42"}},
- {"type": "message_delta", "delta": {"stop_reason": "end_turn"}, "usage": final},
- {"type": "message_stop"},
- ]
-
-
-def sse(events):
- return "".join(
- "data: " + (event if isinstance(event, str) else json.dumps(event)) + "\n\n"
- for event in events
- ).encode()
-
-
-async def model_result(monkeypatch, wire, *, streaming, usage=None, events=None):
- monkeypatch.setenv("FIXTURE_KEY", "fixture-key")
- calls = []
-
- def handler(incoming):
- calls.append(incoming)
- if streaming:
- body = sse(events if events is not None else stream_events(wire, usage))
- return httpx.Response(200, headers={"content-type": "text/event-stream"}, content=body)
- return httpx.Response(200, json=payload(wire, usage))
-
- gateway = ModelGatewayClient(
- network_guard=AllowNetwork(), transport=httpx.MockTransport(handler),
- )
- current = request(streaming=streaming)
- model = MODEL.model_copy(update={"wire_api": wire})
- try:
- result = await exchange(port(gateway, current, model=model), current)
- assert len(calls) == 1
- assert json.loads(calls[0].content).get("stream", False) is streaming
- return result
- finally:
- await gateway.aclose()
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize("wire", WIRES)
-@pytest.mark.parametrize("streaming", [False, True])
-@pytest.mark.parametrize("value", [None, {}, {"input_tokens": 12}, {"total_tokens": 16}])
-async def test_absent_or_partial_wire_usage_stays_unknown(monkeypatch, wire, streaming, value):
- result = await model_result(
- monkeypatch, wire, streaming=streaming, usage=usage_for(wire, value),
- )
- assert result.response_kind == "final_candidate", result
- assert result.text == "42"
- assert result.usage is None, "Missing counters are not an explicit provider report of zero"
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize("wire", WIRES)
-@pytest.mark.parametrize("streaming", [False, True])
-@pytest.mark.parametrize("counts", [(0, 0), (12, 4)])
-async def test_complete_wire_usage_including_zero_is_reported(monkeypatch, wire, streaming, counts):
- result = await model_result(
- monkeypatch, wire, streaming=streaming,
- usage=usage_for(wire, {"input_tokens": counts[0], "output_tokens": counts[1]}),
- )
- assert result.response_kind == "final_candidate", result
- assert result.usage is not None
- assert (result.usage.input_tokens, result.usage.output_tokens) == counts
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize("wire", WIRES)
-@pytest.mark.parametrize("streaming", [False, True])
-@pytest.mark.parametrize("bad", [True, "12", 12.5, -1, None])
-async def test_malformed_counter_is_not_coerced_or_retried(monkeypatch, wire, streaming, bad):
- result = await model_result(
- monkeypatch, wire, streaming=streaming,
- usage=usage_for(wire, {"input_tokens": bad, "output_tokens": 4}),
- )
- assert result.response_kind == "provider_terminal_error", result
- assert result.failure_kind == "invalid_response"
- assert result.gateway_error_code == "MODEL_RESPONSE_INVALID"
- assert result.usage is None
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize("wire", WIRES)
-@pytest.mark.parametrize("streaming", [False, True])
-@pytest.mark.parametrize("bad", [["PRIVATE_USAGE"], [], 0, False])
-async def test_invalid_usage_container_is_a_sanitized_protocol_error(
- monkeypatch, wire, streaming, bad,
-):
- result = await model_result(monkeypatch, wire, streaming=streaming, usage=bad)
- assert result.failure_kind == "invalid_response", result
- assert result.gateway_error_code == "MODEL_RESPONSE_INVALID"
- assert "PRIVATE_USAGE" not in result.model_dump_json()
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize("streaming", [False, True])
-async def test_anthropic_inclusive_input_counts_cache_reads_and_writes(monkeypatch, streaming):
- result = await model_result(
- monkeypatch, "anthropic", streaming=streaming,
- usage={"input_tokens": 12, "output_tokens": 4,
- "cache_read_input_tokens": 7, "cache_creation_input_tokens": 3},
- )
- assert result.response_kind == "final_candidate", result
- assert result.usage.input_tokens == 22
- assert result.usage.output_tokens == 4 and result.usage.cached_input_tokens == 7
-
-
-@pytest.mark.asyncio
-async def test_anthropic_partial_updates_do_not_erase_known_fields(monkeypatch):
- events = stream_events("anthropic", {"input_tokens": 12, "output_tokens": 4})
- events.insert(-1, {"type": "message_delta", "delta": {}, "usage": {}})
- result = await model_result(monkeypatch, "anthropic", streaming=True, events=events)
- assert result.response_kind == "final_candidate", result
- assert result.usage.input_tokens == 12 and result.usage.output_tokens == 4
-
-
-@pytest.mark.parametrize("wire", WIRES)
-def test_buffered_dto_marks_known_counters_and_derives_missing_total(wire):
- from ksadk.studio.model_client import OpenAICompatibleModelClient
-
- raw_usage = usage_for(wire, {"input_tokens": 12, "output_tokens": 4})
- parser = {
- "chat": OpenAICompatibleModelClient._parse_response,
- "responses": OpenAICompatibleModelClient._parse_responses_response,
- "anthropic": OpenAICompatibleModelClient._parse_anthropic_response,
- }[wire]
- result = parser(httpx.Response(200, json=payload(wire, raw_usage)))
- assert result.usage.reported is True and result.usage.source == "model-provider"
- assert result.usage.total_tokens == 16
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize("bad_last", [False, True])
-async def test_chat_usage_only_frame_before_finish_is_preserved(monkeypatch, bad_last):
- events = stream_events("chat", None)
- events.insert(1, {"choices": [], "usage": {"prompt_tokens": 12, "completion_tokens": 4}})
- if bad_last:
- events[2]["usage"] = {"prompt_tokens": "PRIVATE_BAD_COUNTER", "completion_tokens": 4}
- result = await model_result(monkeypatch, "chat", streaming=True, events=events)
- assert result.response_kind == ("provider_terminal_error" if bad_last else "final_candidate")
- if bad_last:
- assert result.failure_kind == "invalid_response"
- assert "PRIVATE_BAD_COUNTER" not in result.model_dump_json()
- assert result.usage.input_tokens == 12 and result.usage.output_tokens == 4
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize("wire", ["chat", "responses"])
-@pytest.mark.parametrize("streaming", [False, True])
-@pytest.mark.parametrize("bad", [True, "7", None, -1])
-async def test_optional_subdivision_does_not_coerce_reported_counter(
- monkeypatch, wire, streaming, bad,
-):
- details = "prompt_tokens_details" if wire == "chat" else "input_tokens_details"
- result = await model_result(
- monkeypatch, wire, streaming=streaming,
- usage=usage_for(wire, {
- "input_tokens": 12, "output_tokens": 4, details: {"cached_tokens": bad},
- }),
- )
- assert result.failure_kind == "invalid_response", result
- assert result.usage is None
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize("streaming", [False, True])
-async def test_anthropic_optional_null_cache_is_absent(monkeypatch, streaming):
- result = await model_result(
- monkeypatch, "anthropic", streaming=streaming,
- usage={"input_tokens": 12, "output_tokens": 4,
- "cache_read_input_tokens": None, "cache_creation_input_tokens": None},
- )
- assert result.response_kind == "final_candidate", result
- assert result.usage.input_tokens == 12 and result.usage.cached_input_tokens == 0
-
-
-@pytest.mark.asyncio
-async def test_anthropic_zero_update_and_cache_breakdown_merge_are_right_biased(monkeypatch):
- events = stream_events("anthropic", {
- "input_tokens": 12, "output_tokens": 4,
- "cache_read_input_tokens": 7, "cache_creation_input_tokens": 3,
- })
- events.insert(-1, {"type": "message_delta", "delta": {}, "usage": {
- "input_tokens": 0, "output_tokens": 0, "cache_read_input_tokens": None,
- }})
- result = await model_result(monkeypatch, "anthropic", streaming=True, events=events)
- assert result.response_kind == "final_candidate", result
- assert result.usage.input_tokens == 10 and result.usage.output_tokens == 0
- assert result.usage.cached_input_tokens == 7
-
-
-@pytest.mark.asyncio
-async def test_anthropic_rejected_delta_keeps_the_last_known_report(monkeypatch):
- events = stream_events("anthropic", {"input_tokens": 12, "output_tokens": 4})
- events[0]["message"]["usage"]["output_tokens"] = 0
- events[2]["usage"]["output_tokens"] = "PRIVATE_BAD_COUNTER"
- result = await model_result(monkeypatch, "anthropic", streaming=True, events=events)
- assert result.failure_kind == "invalid_response", result
- assert result.usage.input_tokens == 12 and result.usage.output_tokens == 0
- assert "PRIVATE_BAD_COUNTER" not in result.model_dump_json()
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize("wire", WIRES)
-@pytest.mark.parametrize("streaming", [False, True])
-async def test_ordinary_studio_commits_true_zero_report_once(
- tmp_path, monkeypatch, wire, streaming,
-):
- from ksadk.harness.native.state import RunScope
- from ksadk.studio.contracts import (
- AgentSpec,
- Instructions,
- ModelSpec,
- NetworkPolicy,
- RunStatus,
- RuntimeRef,
- SecuritySpec,
- )
- from ksadk.studio.service import StudioService
- from tests.studio.test_dsh_provider_registration import _managed_profile
-
- calls = []
- usage = usage_for(wire, {"input_tokens": 0, "output_tokens": 0})
-
- def handler(incoming):
- calls.append(incoming)
- if streaming:
- return httpx.Response(
- 200, headers={"content-type": "text/event-stream"},
- content=sse(stream_events(wire, usage)),
- )
- return httpx.Response(200, json=payload(wire, usage))
-
- class Gateway(ModelGatewayClient):
- def supports_streaming(self, model, *, requested=True):
- return streaming and requested
-
- _managed_profile(tmp_path, monkeypatch)
- monkeypatch.setenv("FIXTURE_KEY", "fixture-key")
- gateway = Gateway(network_guard=AllowNetwork(), transport=httpx.MockTransport(handler))
- studio = StudioService(
- tmp_path / "studio", model_client=gateway, native_harness_agent_ids=("wire-agent",),
- )
- try:
- studio.create_agent(
- agent_id="wire-agent", name="Native wire accounting",
- spec=AgentSpec(
- runtime=RuntimeRef(type="harness"),
- instructions=Instructions(system="Answer the request."),
- model=ModelSpec(
- model="fixture-model", endpoint_url="https://example.test/v1/model",
- wire_api=wire, credential_ref="env://FIXTURE_KEY",
- ),
- security=SecuritySpec(
- allowed_permissions=["process:host-user"],
- network=NetworkPolicy(allowed_hosts=["example.test"]),
- ),
- ),
- )
- build = await studio.ensure_current_build("wire-agent")
- result = await studio.run_build(build.id, "Return 42.", "wire-session")
- assert result.status == RunStatus.COMPLETED and result.output == "42", result.error
- assert result.usage.reported is True
- assert result.usage.input_tokens == result.usage.output_tokens == 0
- assert len(calls) == 1
- assert json.loads(calls[0].content).get("stream", False) is streaming
- session = await studio.session_service.get_session_metadata("wire-session")
- scope = RunScope(
- tenant_id="local-studio", workspace_id=studio.workspace_record.workspace_id,
- user_id=session.user_id, agent_id=session.agent_id,
- )
- composer = studio._native_product_composer
- head = composer.store.session_head(scope, "wire-session")
- events = composer.store.events(scope, head.run_id)
- assert head.model_calls == 1 and head.tool_calls == 0
- assert sum(event.kind == "usage.reported" for event in events) == 1
- assert not any(event.kind == "usage.unavailable" for event in events)
- assert sum(event.kind == "run.completed" for event in events) == 1
- finally:
- await studio.aclose()
diff --git a/tests/studio/test_native_artifact_context_capacity.py b/tests/studio/test_native_artifact_context_capacity.py
deleted file mode 100644
index 77e4e2422..000000000
--- a/tests/studio/test_native_artifact_context_capacity.py
+++ /dev/null
@@ -1,305 +0,0 @@
-"""Source capacity must fit the real planner after sealing an entire read batch."""
-
-import copy
-import hashlib
-import json
-from dataclasses import replace
-from types import SimpleNamespace
-
-import pytest
-
-from ksadk.harness.artifact_adapters.native_page_budget import ArtifactPagePolicy
-from ksadk.harness.artifact_adapters.native_tool import (
- install_artifact_tool,
-)
-from ksadk.harness.native.artifact_read_capacity import artifact_group_capacity
-from ksadk.harness.native.context_driver import ContextDriver
-from ksadk.harness.native.context_runtime import CompactionHistory, CompactionPolicy, ContextPlanner
-from ksadk.harness.native.context_runtime_contracts import _resume, _summary
-from ksadk.harness.native.effective_configuration import effective_run_configuration
-from ksadk.harness.native.engine import NativeKernel
-from ksadk.harness.native.machine import next_transition, reduce_tool
-from ksadk.harness.native.model import ModelProfile, ModelToolCall
-from ksadk.harness.native.ports import ArtifactRef, RunLimits, ToolResult, digest
-from ksadk.harness.native.state import RunPhase
-from ksadk.harness.native.tool_budget import (
- model_instructions,
- model_tool_surface,
- model_turn_control,
-)
-from ksadk.harness.native.transitions import commit_transition
-from ksadk.harness.stores.native_memory import MemoryRunStore
-from ksadk.studio.contracts import ContextSpec
-from ksadk.studio.native_product import _estimated_token_counter, _studio_context_planner
-from ksadk.studio.native_read_budget import StudioSourceReadPolicy
-from tests.harness.native.test_kernel import SCOPE, ScriptedModel, config
-
-
-class Ports:
- async def execute(self, _request):
- pytest.fail("A capacity quote cannot execute a tool.")
-
- async def read(self, _request):
- pytest.fail("A capacity quote cannot read an artifact.")
-
-
-def setup(*, revision=98, old_refs=8, progress=9, summary_max=1024, message_extra=0,
- instructions="Report only observed sources.", max_tool_calls=1000,
- legacy_projection=False):
- profile = ModelProfile(profile_id="capacity", profile_version="1", provider_family="test",
- context_window=8000, max_output_tokens=1024)
- planner = _studio_context_planner(profile, context=ContextSpec() if legacy_projection else None)
- planner.policy = planner.policy.model_copy(update={"summary_max_tokens": summary_max})
- if message_extra:
- ordinary = planner.count_message_tokens
- planner.count_message_tokens = lambda message: ordinary(message) + message_extra
- planner.tokenizer_id += f"-frame-{message_extra}"
- policy = StudioSourceReadPolicy(
- profile, _estimated_token_counter, "test-units/v1", planner.count_message_tokens,
- retain_requested_source=True, artifact_only_fallback=True,
- archive_model_policy="archived-model-view/v5", artifact_pages=True,
- artifact_result_max_bytes=65536, context_planner=planner,
- )
- state = None
- store = SimpleNamespace(load=lambda scope, run_id: state)
- source = policy.artifact_policy(
- store, workspace_revision="unavailable", workspace_tracking=False,
- )
- base = config().model_copy(update={"profile": profile, "tools": (),
- "limits": RunLimits(max_tool_calls=max_tool_calls),
- "instructions": instructions})
- configuration, port = install_artifact_tool(base, Ports(), Ports(), enable_search=True,
- page_policy=source)
- kernel = NativeKernel(store=MemoryRunStore(), scope=SCOPE, configuration=configuration,
- model=ScriptedModel(), context_planner=planner)
- initial = kernel.start(goal="Inspect the requested sources.", session_id="capacity", run_id="r")
- messages = list(initial.messages)
- for i in range(old_refs):
- messages.extend((
- {"role": "assistant", "content": "", "tool_calls": [{
- "id": f"old-{i}", "type": "function", "function": {
- "name": "ArtifactRead", "arguments": json.dumps({"uri": f"artifact://old/{i}"}),
- }}]},
- {"role": "tool", "tool_call_id": f"old-{i}",
- "content": '{"status":"ok","content":"old"}',
- "receipt_ref": f"r:effect:{i+1}", "receipt_goal_revision": initial.goal_revision,
- "receipt_tool_call": i+1},
- ))
- messages.extend({"role": "assistant", "content": "Earlier observations. " * 60}
- for _ in range(30))
- calls = tuple(ModelToolCall(call_id=f"page-{i}", name="ArtifactRead",
- arguments={"uri": f"artifact://source/{i}", "limit_chars": 32000})
- for i in range(8))
- messages.append({"role": "assistant", "content": "", "tool_calls": [{
- "id": c.call_id, "type": "function", "function": {
- "name": c.name, "arguments": json.dumps(c.arguments),
- }} for c in calls]})
- text = "Observation 汉字.\n" * 2000
- refs = tuple(ArtifactRef(uri=c.arguments["uri"], size_bytes=len(text.encode()),
- content_hash="sha256:" + hashlib.sha256(text.encode()).hexdigest(),
- mime_type="text/plain") for c in calls)
- state = initial.model_copy(update={
- "phase": RunPhase.EXECUTING_TOOLS, "revision": revision, "model_calls": 2,
- "tool_calls": old_refs, "messages": tuple(messages),
- "pending_tools": tuple(c.model_dump(mode="json") for c in calls),
- "observed_progress_revision": progress,
- "artifact_refs": tuple(ref.model_dump(mode="json") for ref in refs),
- })
- state = next_transition(state, configuration).snapshot
-
- def set_state(value):
- nonlocal state
- state = value
-
- return configuration, planner, policy, source, port, kernel, state, refs, text, set_state
-
-
-@pytest.mark.parametrize("revision,old_refs,progress,summary_max,message_extra", [
- (8, 8, 9, 1024, 0), (98, 8, 99, 1024, 0), (998, 9, 999, 512, 31),
- (9998, 7, 9, 2048, 17),
-])
-@pytest.mark.parametrize("legacy_projection", [False, True])
-def test_sealed_full_batch_retained_with_real_planner(
- revision, old_refs, progress, summary_max, message_extra, legacy_projection,
-):
- cfg, planner, policy, source, port, kernel, state, refs, text, save = setup(
- revision=revision, old_refs=old_refs, progress=progress,
- summary_max=summary_max, message_extra=message_extra,
- legacy_projection=legacy_projection,
- )
- original = copy.deepcopy(state)
- before_store = kernel.store.load(SCOPE, "r").model_dump_json()
- first = artifact_group_capacity(state, cfg, kernel.context)
- assert state == original and kernel.store.load(SCOPE, "r").model_dump_json() == before_store
- assert first.summary_tokens == (
- min(summary_max, cfg.profile.max_output_tokens)
- + planner._count_message(_summary(""))
- + (planner._count_message(_resume()) if legacy_projection else 0)
- )
- quoted = []
- while state.pending_tools:
- # This is execution by the real pure transition reducers, with a new
- # page selected for every call. The quote itself cannot commit anything.
- prepared = next_transition(state.model_copy(update={
- "pending_intent": None, "revision": state.revision - 1,
- }), cfg)
- calls = prepared.intents[0].payload.get("calls") or [prepared.intents[0].payload["call"]]
- updated = state
- for raw in calls:
- call = ModelToolCall.model_validate(raw)
- budget = port._page_policy.resolve(SimpleNamespace(
- scope=SCOPE, run_id="r", call=call), cfg.tools)
- assert budget.source_group_size == 8
- ref = next(r for r in refs if r.uri == call.arguments["uri"])
- page = budget.select({"uri": ref.uri, "content": text, "offset_chars": 0,
- "next_offset_chars": len(text), "complete": True,
- "content_hash": ref.content_hash, "size_bytes": ref.size_bytes,
- "mime_type": ref.mime_type})
- assert page["content"] and budget.fits(page)
- updated = reduce_tool(
- updated.model_copy(update={"pending_intent": state.pending_intent}),
- ToolResult(status="ok", content=page),
- definition=next(t for t in cfg.tools if t.name == "ArtifactRead"))
- quoted.append(page)
- state = commit_transition(state, updated, "effect.received").snapshot
- if state.pending_tools:
- state = next_transition(state, cfg).snapshot
- save(state)
- state = next_transition(state, cfg).snapshot
- plan = planner.plan(
- source_revision=state.revision, model_turn=state.model_calls, profile=cfg.profile,
- instructions=model_instructions(state, cfg), tools=model_tool_surface(state, cfg),
- context_tools=cfg.tools, messages=state.messages,
- continuity=kernel.context.continuity(state, cfg), contract=cfg.contract,
- history=CompactionHistory(), turn_control=model_turn_control(state, cfg),
- )
- assert plan.action == "compact", plan.reason
- retained = plan.request.retained_messages
- observed = [json.loads(m["content"])["content"] for m in retained
- if m.get("tool_call_id", "").startswith("page-")]
- assert observed == quoted and len(observed) == 8
- assert (sum(planner.count_model_message(m, cfg.profile) for m in retained)
- + first.summary_tokens <= plan.request.budget.input_capacity)
-
-
-@pytest.mark.parametrize("changed", ["configuration", "context", "command", "mixed", "duplicate"])
-def test_unknown_or_intervening_state_has_no_strong_quote(changed):
- cfg, planner, policy, source, port, kernel, state, *_ = setup()
- if changed == "configuration":
- state = state.model_copy(update={"configuration_digest": "foreign"})
- elif changed == "context":
- state = state.model_copy(update={"context_binding": "foreign"})
- elif changed == "command":
- state = state.model_copy(update={"revision": state.revision+1})
- else:
- messages = copy.deepcopy(state.messages)
- calls = messages[-1]["tool_calls"]
- if changed == "mixed":
- calls[0]["function"]["name"] = "unknown"
- else:
- calls[1]["function"]["arguments"] = calls[0]["function"]["arguments"]
- state = state.model_copy(update={"messages": messages})
- if changed in {"configuration", "context"}:
- with pytest.raises(ValueError, match="configuration_mismatch"):
- artifact_group_capacity(state, cfg, kernel.context)
- else:
- assert artifact_group_capacity(state, cfg, kernel.context) is None
-
-
-def test_summary_policy_and_message_framing_change_capacity_identity():
- cfg, planner, policy, *_ = setup()
- smaller = ContextPlanner(count_tokens=len, tokenizer_id="characters/v1",
- policy=CompactionPolicy(summary_max_tokens=64))
- assert smaller.summary_reservation(cfg.profile) == 64 + len(json.dumps(
- _summary(""), ensure_ascii=False, sort_keys=True, separators=(",", ":"))) + len(json.dumps(
- _resume(), ensure_ascii=False, sort_keys=True, separators=(",", ":")))
- assert replace(policy, context_planner=smaller).digest != policy.digest
-
-
-def test_configuration_binding_waits_for_all_reserved_tools_and_rejects_wrong_digest():
- cfg, planner, policy, source, port, kernel, state, *_ = setup()
- assert {t.name for t in cfg.tools} == {"ArtifactRead", "ArtifactSearch"}
- with pytest.raises(ValueError, match="unbound"):
- source.resolve(None, ())
- # A reconstructed installation binds to exactly the same immutable config.
- cfg2, port2 = install_artifact_tool(
- cfg, Ports(), Ports(), enable_search=True, page_policy=source,
- )
- assert cfg2 == cfg and port2._page_policy.digest == port._page_policy.digest
- request = SimpleNamespace(scope=SCOPE, run_id="r",
- call=ModelToolCall.model_validate(state.pending_tools[0]))
- budget1 = port._page_policy.resolve(request, cfg.tools)
- budget2 = port2._page_policy.resolve(request, cfg2.tools)
- assert (budget1.max_units, budget1.max_result_units) == (
- budget2.max_units, budget2.max_result_units)
- assert budget1.count_result_message({"content": "known"}) == (
- budget2.count_result_message({"content": "known"}))
- foreign = cfg.model_copy(update={"instructions": "Different child instructions and contract."})
- foreign_port = source.bind_configuration(foreign)
- with pytest.raises(ValueError, match="configuration_mismatch"):
- foreign_port.resolve(request, foreign.tools)
- bad = ArtifactPagePolicy(source.digest, source.resolve, bind_configuration=lambda c:
- ArtifactPagePolicy("sha256:"+"0"*64, source.resolve))
- with pytest.raises(ValueError, match="configuration_binding_invalid"):
- install_artifact_tool(cfg, Ports(), Ports(), enable_search=True, page_policy=bad)
-
-
-def test_effective_configuration_matches_kernel_contract_and_output_schema():
- cfg, planner, policy, source, port, kernel, state, *_ = setup()
- assert effective_run_configuration(cfg, state) == kernel.effective_configuration(state)
- contract = cfg.contract.model_copy(update={
- "revision": "child", "allowed_tool_names": ("ArtifactRead",),
- "final_submission_schema": {"type": "object", "properties": {"answer": {"type": "string"}},
- "required": ["answer"], "additionalProperties": False},
- "final_submission_payload_key": "answer",
- })
- state = state.model_copy(update={"task_contract": contract.model_dump(mode="json"),
- "contract_digest": digest(contract)})
- effective = effective_run_configuration(cfg, state)
- assert effective == kernel.effective_configuration(state)
- assert effective.contract == contract and cfg.contract != contract
- assert effective.final_submission_schema == contract.final_submission_schema
- assert effective.final_submission_payload_key == "answer"
- with pytest.raises(ValueError, match="contract identity"):
- effective_run_configuration(cfg, state.model_copy(update={"contract_digest": "wrong"}))
-
-
-def test_parent_and_child_bind_separate_actual_configurations():
- parent = setup(instructions="Parent orchestration. " * 20, max_tool_calls=1000)
- child = setup(instructions="Child source reporting.", max_tool_calls=16)
- quotes = []
- for current, other in ((parent, child), (child, parent)):
- cfg, planner, policy, source, port, kernel, state, *_ = current
- quote = artifact_group_capacity(state, cfg, kernel.context)
- assert quote is not None
- quotes.append(quote)
- request = SimpleNamespace(scope=SCOPE, run_id="r",
- call=ModelToolCall.model_validate(state.pending_tools[0]))
- page_budget = port._page_policy.resolve(request, cfg.tools)
- assert page_budget.max_result_units == quote.result_message_units
- # A legitimate configuration for another Run still cannot price this
- # Run's contract, finalization control, or complete model tool surface.
- with pytest.raises(ValueError, match="configuration_mismatch"):
- source.bind_configuration(other[0]).resolve(request, other[0].tools)
- assert quotes[0].fixed_tokens != quotes[1].fixed_tokens
-
-
-def test_mandatory_system_messages_remain_in_full_request_capacity():
- cfg, planner, policy, source, port, kernel, state, *_ = setup()
- before = artifact_group_capacity(state, cfg, kernel.context)
- state = state.model_copy(update={"messages": (
- {"role": "system", "content": "Pinned system requirement. " * 100}, *state.messages,
- )})
- after = artifact_group_capacity(state, cfg, kernel.context)
- assert after.fixed_tokens == before.fixed_tokens
- assert after.result_message_units < before.result_message_units
- assert after.source_units < before.source_units
-
-
-@pytest.mark.parametrize("working_set_count", [0, 7])
-def test_insufficient_read_working_set_cannot_claim_retained_group_capacity(working_set_count):
- cfg, planner, policy, source, port, kernel, state, *_ = setup()
- planner.policy = planner.policy.model_copy(update={"read_working_set_count": working_set_count})
- driver = ContextDriver(planner, "unavailable")
- state = state.model_copy(update={"context_binding": driver.binding})
- assert artifact_group_capacity(state, cfg, driver) is None
diff --git a/tests/studio/test_native_browser_port.py b/tests/studio/test_native_browser_port.py
deleted file mode 100644
index 41ee3b6da..000000000
--- a/tests/studio/test_native_browser_port.py
+++ /dev/null
@@ -1,1341 +0,0 @@
-"""Real Chromium checks for Studio's Run-scoped Native browser owner."""
-
-import json
-import sqlite3
-from functools import partial
-from http.server import ThreadingHTTPServer
-from pathlib import Path
-from threading import Thread
-from urllib.error import HTTPError
-from urllib.request import urlopen
-
-import pytest
-
-from ksadk.harness.native.model import ModelToolCall
-from ksadk.harness.native.ports import ToolDefinition, ToolRequest
-from ksadk.harness.native.state import RunScope
-from ksadk.studio.contracts import (
- AgentBindings,
- AgentSpec,
- CapabilityBinding,
- ExecutionSpec,
- Instructions,
- ModelSpec,
- NetworkPolicy,
- RunStatus,
- RuntimeRef,
- SecuritySpec,
- Usage,
-)
-from ksadk.studio.model_client import ModelResponse, ToolCall
-from ksadk.studio.native_browser_port import (
- StudioNativeBrowserPort,
- _is_launch_label,
- _QuietScopedHandler,
- browser_environment_warning,
-)
-from ksadk.studio.service import StudioService
-from tests.studio.test_dsh_provider_registration import _managed_profile
-
-pytestmark = pytest.mark.local_process_heavy
-
-_SCOPE = RunScope(tenant_id="tenant", workspace_id="workspace", user_id="user", agent_id="agent")
-_DEFINITION = ToolDefinition(name="browser_inspect_workspace", description="browser", parameters={})
-
-
-def test_pointer_lock_environment_classification_requires_exact_observed_error() -> None:
- message = "The root document of this element is not valid for pointer lock."
- assert browser_environment_warning(message)
- assert not browser_environment_warning("app bug: " + message)
-
-
-def test_settings_entry_is_not_a_launch_control() -> None:
- assert not _is_launch_label("进入设置")
-
-
-def test_browser_file_server_rejects_workspace_symlink_to_outside(tmp_path: Path) -> None:
- workspace = tmp_path / "workspace"
- workspace.mkdir()
- outside = tmp_path / "outside.txt"
- outside.write_text("fixture-private", encoding="utf-8")
- (workspace / "outside.txt").symlink_to(outside)
- server = ThreadingHTTPServer(
- ("127.0.0.1", 0), partial(_QuietScopedHandler, directory=str(workspace))
- )
- thread = Thread(target=server.serve_forever, daemon=True)
- thread.start()
- try:
- with pytest.raises(HTTPError) as error:
- urlopen(f"http://127.0.0.1:{server.server_port}/outside.txt", timeout=2)
- assert error.value.code == 403
- finally:
- server.shutdown()
- server.server_close()
- thread.join(timeout=2)
-
-
-def _request(run: str, operation: str, **arguments: object) -> ToolRequest:
- return ToolRequest(
- scope=_SCOPE,
- run_id=run,
- operation_key=operation,
- call=ModelToolCall(
- call_id=f"call-{operation}",
- name="browser_inspect_workspace",
- arguments={"path": "app/index.html", "wait_ms": 0, **arguments},
- ),
- definition=_DEFINITION,
- )
-
-
-@pytest.mark.asyncio
-async def test_visible_control_without_id_has_an_actionable_unique_selector(tmp_path: Path) -> None:
- app = tmp_path / "app"
- app.mkdir()
- (app / "index.html").write_text(
- ""
- '0
'
- '",
- encoding="utf-8",
- )
- browser = StudioNativeBrowserPort(scope=_SCOPE, root=tmp_path, runtime_id="no-id-control")
- try:
- first = await browser.execute(_request("run", "observe"))
- assert first.status == "ok"
- controls = [
- control for control in first.content["controls"] if control["label"] == "Craft plank"
- ]
- assert len(controls) == 1
- selector = controls[0]["selector"]
- assert isinstance(selector, str) and selector.endswith("div:nth-of-type(1)")
- clicked = await browser.execute(
- _request("run", "click", actions=[{"type": "click", "selector": selector}])
- )
- assert clicked.status == "ok"
- assert "1" in clicked.content["body_text_preview"]
- finally:
- await browser.aclose()
-
-
-@pytest.mark.asyncio
-async def test_studio_browser_uses_available_chrome_for_webgl_pointer_lock(
- tmp_path: Path,
-) -> None:
- app = tmp_path / "app"
- app.mkdir()
- (app / "index.html").write_text(
- 'pending
'
- '",
- encoding="utf-8",
- )
- port = StudioNativeBrowserPort(scope=_SCOPE, root=tmp_path, runtime_id="webgl-lock")
- try:
- result = await port.execute(
- _request("run", "pointer-lock", actions=[{"type": "click", "selector": "#play"}])
- )
- assert "browser_channel" in result.content
- if result.content.get("browser_channel") != "chrome":
- pytest.skip("system Chrome is unavailable; bundled Chromium cannot test pointer lock")
- assert result.status == "ok"
- assert result.content["browser_version"]
- assert "locked" in result.content["body_text_preview"]
- finally:
- await port.aclose()
-
-
-@pytest.mark.asyncio
-async def test_bounded_hold_actions_move_real_page_and_invalid_batch_has_no_effect(
- tmp_path: Path,
-) -> None:
- app = tmp_path / "app"
- app.mkdir()
- (app / "index.html").write_text(
- ""
- "0
0
"
- "",
- encoding="utf-8",
- )
- port = StudioNativeBrowserPort(scope=_SCOPE, root=tmp_path, runtime_id="test-browser")
- try:
- for index, broken in enumerate(
- (
- {"type": "press", "selector": "body", "key": "w", "duration_ms": 5001},
- {"type": "press", "selector": "body"},
- {"type": "click"},
- {"type": "fill", "selector": "#mine"},
- {"type": "click", "selector": "#mine", "button": "other"},
- {"type": "move", "x": 1280, "y": 0},
- )
- ):
- invalid = await port.execute(
- _request(
- "run",
- f"invalid-{index}",
- actions=[{"type": "click", "selector": "#mine", "duration_ms": 300}, broken],
- )
- )
- assert invalid.status == "error"
- assert invalid.content["code"] == "browser_action_invalid"
- over_budget = await port.execute(
- _request(
- "run",
- "over-budget",
- actions=[
- {"type": "click", "selector": "#mine"},
- *({"type": "wait", "ms": 10000} for _ in range(4)),
- ],
- )
- )
- assert over_budget.status == "error"
- assert over_budget.content["code"] == "browser_action_time_budget_exceeded"
- held = await port.execute(
- _request(
- "run",
- "held",
- actions=[
- {"type": "press", "selector": "body", "key": "w", "duration_ms": 300},
- {"type": "click", "selector": "#mine", "duration_ms": 300},
- ],
- )
- )
- assert held.status == "ok", held.content
- text = held.content["body_text_preview"]
- assert "Mine" in text
- assert int(text.split("Mine", 1)[1].split()[0]) >= 5
- assert int(text.split("Mine", 1)[1].split()[1]) >= 5
- finally:
- await port.aclose()
-
-
-@pytest.mark.asyncio
-async def test_right_click_and_mouse_move_reach_real_page(tmp_path: Path) -> None:
- app = tmp_path / "app"
- app.mkdir()
- (app / "index.html").write_text(
- "Move0
"
- "Right0
",
- encoding="utf-8",
- )
- port = StudioNativeBrowserPort(scope=_SCOPE, root=tmp_path, runtime_id="test-browser")
- try:
- result = await port.execute(
- _request(
- "run",
- "pointer-actions",
- actions=[
- {"type": "move", "x": 20, "y": 40, "steps": 3},
- {"type": "click", "selector": "#block", "button": "right"},
- ],
- )
- )
- assert result.status == "ok", result.content
- assert "Right1" in result.content["body_text_preview"]
- assert "Move" in result.content["body_text_preview"]
- assert "Move0" not in result.content["body_text_preview"]
- assert [action["ok"] for action in result.content["actions"]] == [True, True]
- finally:
- await port.aclose()
-
-
-@pytest.mark.asyncio
-async def test_browser_page_survives_tool_turns_but_isolated_by_run(tmp_path: Path) -> None:
- app = tmp_path / "app"
- app.mkdir()
- (app / "index.html").write_text(
- "0",
- encoding="utf-8",
- )
- port = StudioNativeBrowserPort(scope=_SCOPE, root=tmp_path, runtime_id="test-browser")
- try:
- first = await port.execute(
- _request("run-one", "first", actions=[{"type": "click", "selector": "#increment"}])
- )
- second = await port.execute(
- _request("run-one", "second", actions=[{"type": "click", "selector": "#increment"}])
- )
- other = await port.execute(_request("run-two", "other"))
- assert first.status == second.status == other.status == "ok"
- assert "increment1" in first.content["body_text_preview"]
- assert "increment2" in second.content["body_text_preview"]
- assert "increment0" in other.content["body_text_preview"]
- assert first.content["browser_session_id"] == second.content["browser_session_id"]
- assert first.content["browser_session_id"] != other.content["browser_session_id"]
- assert first.content["page_navigation_reason"] == "initial_open"
- assert second.content["page_navigation_reason"] == "none"
- assert second.content_blocks and (tmp_path / ".artifacts/browser-check.png").is_file()
- finally:
- await port.aclose()
-
-
-@pytest.mark.asyncio
-async def test_workspace_root_screenshot_does_not_reload_active_page(tmp_path: Path) -> None:
- (tmp_path / "index.html").write_text(
- "0",
- encoding="utf-8",
- )
- port = StudioNativeBrowserPort(scope=_SCOPE, root=tmp_path, runtime_id="root-screenshot")
- try:
- first = await port.execute(
- _request(
- "run",
- "first",
- path=".",
- screenshot_path="screenshot_initial.png",
- actions=[{"type": "click", "selector": "#increment"}],
- )
- )
- second = await port.execute(
- _request(
- "run",
- "second",
- path=".",
- screenshot_path="screenshot_after_click.png",
- actions=[{"type": "click", "selector": "#increment"}],
- )
- )
- assert first.status == second.status == "ok"
- assert "increment1" in first.content["body_text_preview"]
- assert "increment2" in second.content["body_text_preview"]
- assert second.content["page_navigation_reason"] == "none"
- finally:
- await port.aclose()
-
-
-@pytest.mark.asyncio
-async def test_editing_a_captured_image_invalidates_the_served_page(tmp_path: Path) -> None:
- (tmp_path / "index.html").write_text('ready', encoding="utf-8")
- port = StudioNativeBrowserPort(scope=_SCOPE, root=tmp_path, runtime_id="edited-capture")
- try:
- first = await port.execute(
- _request("run", "first", path=".", screenshot_path="capture.png")
- )
- assert first.status == "ok"
- capture = tmp_path / "capture.png"
- capture.write_bytes(capture.read_bytes() + b"edited")
- second = await port.execute(_request("run", "second", path=".", screenshot_path="next.png"))
- assert second.status == "ok"
- assert second.content["page_navigation_reason"] == "source_changed"
- finally:
- await port.aclose()
-
-
-@pytest.mark.asyncio
-async def test_browser_reloads_same_page_after_served_asset_changes(tmp_path: Path) -> None:
- app = tmp_path / "app"
- app.mkdir()
- (app / "index.html").write_text(
- 'loading',
- encoding="utf-8",
- )
- script = app / "game.js"
- script.write_text(
- "document.querySelector('#version').textContent='version-one'", encoding="utf-8"
- )
- port = StudioNativeBrowserPort(scope=_SCOPE, root=tmp_path, runtime_id="test-browser")
- try:
- first = await port.execute(_request("run", "before"))
- assert first.status == "ok"
- assert "version-one" in first.content["body_text_preview"]
- script.write_text(
- "document.querySelector('#version').textContent='version-two'", encoding="utf-8"
- )
- second = await port.execute(_request("run", "after"))
- assert second.status == "ok"
- assert "version-two" in second.content["body_text_preview"]
- assert first.content["browser_session_id"] == second.content["browser_session_id"]
- assert second.content["page_navigation_reason"] == "source_changed"
- finally:
- await port.aclose()
-
-
-@pytest.mark.asyncio
-async def test_source_edit_explains_in_game_selector_disappearing_after_reload(
- tmp_path: Path,
-) -> None:
- app = tmp_path / "app"
- app.mkdir()
- (app / "index.html").write_text(
- '',
- encoding="utf-8",
- )
- script = app / "game.js"
- script.write_text("window.version = 1", encoding="utf-8")
- port = StudioNativeBrowserPort(scope=_SCOPE, root=tmp_path, runtime_id="test-browser")
- try:
- started = await port.execute(
- _request("run", "start", actions=[{"type": "click", "selector": "#start"}])
- )
- assert started.status == "ok"
- script.write_text("window.version = 2", encoding="utf-8")
- after_edit = await port.execute(
- _request("run", "after-edit", actions=[{"type": "click", "selector": "#mine"}])
- )
- assert after_edit.status == "error"
- assert after_edit.content["page_navigation_reason"] == "source_changed"
- assert after_edit.content["browser_session_id"] == started.content["browser_session_id"]
- assert after_edit.content["error_code"] == "selector_not_visible"
- finally:
- await port.aclose()
-
-
-@pytest.mark.asyncio
-async def test_browser_blocks_external_requests_and_preserves_error_evidence(
- tmp_path: Path,
-) -> None:
- app = tmp_path / "app"
- app.mkdir()
- (app / "index.html").write_text(
- "local
", encoding="utf-8"
- )
- port = StudioNativeBrowserPort(scope=_SCOPE, root=tmp_path, runtime_id="test-browser")
- try:
- result = await port.execute(_request("run", "first"))
- assert result.status == "error"
- assert result.content["request_failures"]
- assert result.content["screenshot_path"] == ".artifacts/browser-check.png"
- assert result.content_blocks
- outside = await port.execute(_request("run", "outside", screenshot_path="../outside.png"))
- assert outside.status == "error"
- assert outside.content["code"] == "screenshot_path_invalid"
- assert not (tmp_path.parent / "outside.png").exists()
- finally:
- await port.aclose()
-
-
-@pytest.mark.asyncio
-async def test_browser_console_log_is_observation_not_execution_failure(tmp_path: Path) -> None:
- app = tmp_path / "app"
- app.mkdir()
- (app / "index.html").write_text(
- "",
- encoding="utf-8",
- )
- port = StudioNativeBrowserPort(scope=_SCOPE, root=tmp_path, runtime_id="test-browser")
- try:
- result = await port.execute(_request("run", "first"))
- assert result.status == "ok"
- assert result.content["console_errors"] == []
- finally:
- await port.aclose()
-
-
-@pytest.mark.asyncio
-async def test_missing_script_reports_exact_asset_http_failure(tmp_path: Path) -> None:
- app = tmp_path / "app"
- app.mkdir()
- (app / "index.html").write_text(
- 'Loading
',
- encoding="utf-8",
- )
- port = StudioNativeBrowserPort(scope=_SCOPE, root=tmp_path, runtime_id="test-browser")
- try:
- result = await port.execute(_request("run", "first"))
- assert result.status == "error"
- assert any(
- "asset_http_error:404: /missing/game.js" in failure
- for failure in result.content["request_failures"]
- )
- assert result.content["screenshot_path"] == ".artifacts/browser-check.png"
- finally:
- await port.aclose()
-
-
-@pytest.mark.asyncio
-async def test_browser_script_error_reports_bounded_source_location(tmp_path: Path) -> None:
- app = tmp_path / "app"
- app.mkdir()
- (app / "index.html").write_text(
- '', encoding="utf-8"
- )
- (app / "broken.js").write_text("export const value = ;", encoding="utf-8")
- port = StudioNativeBrowserPort(scope=_SCOPE, root=tmp_path, runtime_id="test-browser")
- try:
- result = await port.execute(_request("run", "script-location"))
- assert result.status == "error"
- assert result.content["page_errors"]
- assert any(
- location.startswith("/broken.js:1:")
- for location in result.content["page_error_locations"]
- )
- finally:
- await port.aclose()
-
-
-@pytest.mark.asyncio
-async def test_host_verification_reload_keeps_evidence_outside_agent_workspace(
- tmp_path: Path,
-) -> None:
- workspace = tmp_path / "workspace"
- app = workspace / "app"
- app.mkdir(parents=True)
- (app / "index.html").write_text(
- "built
", encoding="utf-8"
- )
- evidence = tmp_path / "evidence"
- port = StudioNativeBrowserPort(
- scope=_SCOPE, root=workspace, runtime_id="test-browser", evidence_root=evidence
- )
- try:
- observation = await port.verify_page(
- run_id="run", entry_path="app/index.html", candidate_id="candidate"
- )
- assert observation.status == "ok"
- assert observation.page_errors
- assert list(evidence.glob("*.png"))
- assert not (workspace / ".artifacts").exists()
- finally:
- await port.aclose()
-
-
-@pytest.mark.asyncio
-async def test_host_verification_observes_controls_after_page_settles(tmp_path: Path) -> None:
- workspace = tmp_path / "workspace"
- workspace.mkdir()
- (workspace / "index.html").write_text(
- "Loading
",
- encoding="utf-8",
- )
- port = StudioNativeBrowserPort(
- scope=_SCOPE,
- root=workspace,
- runtime_id="test-browser",
- evidence_root=tmp_path / "evidence",
- )
- try:
- observation = await port.verify_page(
- run_id="run", entry_path="index.html", candidate_id="candidate"
- )
- assert observation.status == "ok"
- assert any(control.label == "Start" for control in observation.controls)
- assert "Start" in observation.text
- finally:
- await port.aclose()
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize(
- "launch_label", ["新游戏", "▶ 新游戏", "新的世界", "开始新世界", "进入星界 ▶", "New Game"]
-)
-async def test_host_verification_launches_one_visible_start_control_and_catches_late_error(
- tmp_path: Path,
- launch_label: str,
-) -> None:
- workspace = tmp_path / "workspace"
- workspace.mkdir()
- (workspace / "index.html").write_text(
- '',
- encoding="utf-8",
- )
- evidence = tmp_path / "evidence"
- port = StudioNativeBrowserPort(
- scope=_SCOPE, root=workspace, runtime_id="test-browser", evidence_root=evidence
- )
- try:
- observation = await port.verify_page(
- run_id="run", entry_path="index.html", candidate_id="candidate"
- )
- assert any("game-start-broken" in error for error in observation.page_errors)
- assert observation.action_id.endswith(":3")
- assert list(evidence.glob("*.png"))
- assert not (workspace / ".artifacts").exists()
- finally:
- await port.aclose()
-
-
-@pytest.mark.asyncio
-async def test_pointer_lock_result_is_classified_by_observed_browser_channel(
- tmp_path: Path,
-) -> None:
- app = tmp_path / "app"
- app.mkdir()
- (app / "index.html").write_text(
- '',
- encoding="utf-8",
- )
- port = StudioNativeBrowserPort(scope=_SCOPE, root=tmp_path, runtime_id="test-browser")
- try:
- result = await port.execute(
- _request(
- "run",
- "click",
- wait_ms=300,
- actions=[{"type": "click", "selector": "#new"}],
- )
- )
- assert result.status == "ok"
- assert result.content["page_errors"] == []
- if result.content["browser_channel"] == "chrome":
- assert result.content["environment_warnings"] == []
- else:
- assert result.content["browser_channel"] == "bundled-chromium"
- assert any(
- "not valid for pointer lock" in item
- for item in result.content["environment_warnings"]
- )
- finally:
- await port.aclose()
-
-
-@pytest.mark.asyncio
-async def test_obscured_click_returns_safe_feedback_then_succeeds_after_repair(
- tmp_path: Path,
-) -> None:
- app = tmp_path / "app"
- app.mkdir()
- entry = app / "index.html"
- button = (
- '0'
- )
- entry.write_text(
- button + ''
- "Loading
",
- encoding="utf-8",
- )
- port = StudioNativeBrowserPort(scope=_SCOPE, root=tmp_path, runtime_id="test-browser")
- try:
- blocked = await port.execute(
- _request("run", "blocked", actions=[{"type": "click", "selector": "#new"}])
- )
- assert blocked.status == "error"
- assert blocked.content["error_code"] == "selector_not_actionable"
- assert blocked.content["pointer_lock_active"] is False
- assert "New Game0" in blocked.content["body_text_preview"]
- covered = next(
- control for control in blocked.content["controls"] if control["selector"] == "#new"
- )
- assert covered["clickable"] is True
- assert covered["hit_test_reachable"] is False
- entry.write_text(button, encoding="utf-8")
- repaired = await port.execute(
- _request("run", "repaired", actions=[{"type": "click", "selector": "#new"}])
- )
- assert repaired.status == "ok"
- assert "New Game1" in repaired.content["body_text_preview"]
- uncovered = next(
- control for control in repaired.content["controls"] if control["selector"] == "#new"
- )
- assert uncovered["hit_test_reachable"] is True
- finally:
- await port.aclose()
-
-
-@pytest.mark.asyncio
-async def test_pointer_locked_click_exposes_actionable_browser_state(tmp_path: Path) -> None:
- app = tmp_path / "app"
- app.mkdir()
- (app / "index.html").write_text(
- ''
- ''
- 'pending",
- encoding="utf-8",
- )
- port = StudioNativeBrowserPort(scope=_SCOPE, root=tmp_path, runtime_id="locked-click")
- try:
- opened = await port.execute(
- _request("run", "lock", actions=[{"type": "click", "selector": "#start"}])
- )
- if opened.content.get("browser_channel") != "chrome":
- pytest.skip("system Chrome is unavailable; bundled Chromium cannot test pointer lock")
- assert opened.status == "ok"
- assert "locked" in opened.content["body_text_preview"]
- blocked = await port.execute(
- _request("run", "craft", actions=[{"type": "click", "selector": "#craft"}])
- )
- assert blocked.status == "error"
- assert blocked.content["error_code"] == "selector_not_actionable"
- assert blocked.content["pointer_lock_active"] is True
- assert "Craft" in blocked.content["body_text_preview"]
- finally:
- await port.aclose()
-
-
-@pytest.mark.asyncio
-async def test_menu_load_is_reachable_while_hud_load_is_occluded(tmp_path: Path) -> None:
- app = tmp_path / "app"
- app.mkdir()
- (app / "index.html").write_text(
- ''
- '",
- encoding="utf-8",
- )
- port = StudioNativeBrowserPort(scope=_SCOPE, root=tmp_path, runtime_id="dual-load")
- try:
- observed = await port.execute(_request("run", "observe"))
- assert observed.status == "ok"
- controls = {row["selector"]: row for row in observed.content["controls"]}
- assert controls["#hud-load"]["clickable"] is True
- assert controls["#hud-load"]["hit_test_reachable"] is False
- assert controls["#menu-load"]["hit_test_reachable"] is True
- opened = await port.execute(
- _request("run", "open", actions=[{"type": "click", "selector": "#menu-load"}])
- )
- assert opened.status == "ok"
- controls = {row["selector"]: row for row in opened.content["controls"]}
- assert controls["#hud-load"]["hit_test_reachable"] is True
- finally:
- await port.aclose()
-
-
-@pytest.mark.asyncio
-async def test_host_verification_launches_unique_pointer_control_with_id(tmp_path: Path) -> None:
- workspace = tmp_path / "workspace"
- workspace.mkdir()
- (workspace / "index.html").write_text(
- ' { throw new Error('div-start-broken') }, 30)\">"
- "开始新世界
",
- encoding="utf-8",
- )
- port = StudioNativeBrowserPort(
- scope=_SCOPE, root=workspace, runtime_id="test-browser", evidence_root=tmp_path / "evidence"
- )
- try:
- observation = await port.verify_page(
- run_id="run", entry_path="index.html", candidate_id="candidate"
- )
- assert any("div-start-broken" in error for error in observation.page_errors)
- assert observation.action_id.endswith(":3")
- finally:
- await port.aclose()
-
-
-@pytest.mark.asyncio
-async def test_duplicate_visible_launch_ids_are_observable_and_fail_cold_check(
- tmp_path: Path,
-) -> None:
- workspace = tmp_path / "workspace"
- app = workspace / "app"
- app.mkdir(parents=True)
- (app / "index.html").write_text(
- ''
- '',
- encoding="utf-8",
- )
- port = StudioNativeBrowserPort(
- scope=_SCOPE, root=workspace, runtime_id="test-browser", evidence_root=tmp_path / "evidence"
- )
- try:
- tool_result = await port.execute(_request("run", "inspect"))
- controls = tool_result.content["controls"]
- duplicate_buttons = [control for control in controls if control["label"] == "开始新世界"]
- assert len(duplicate_buttons) == 2
- assert all(control["selector"] is None for control in duplicate_buttons)
- assert all(control["duplicate_id"] is True for control in duplicate_buttons)
- observation = await port.verify_page(
- run_id="run", entry_path="app/index.html", candidate_id="candidate"
- )
- assert observation.status == "error"
- assert observation.error_code == "browser_launch_control_ambiguous"
- finally:
- await port.aclose()
-
-
-@pytest.mark.asyncio
-async def test_host_verification_uses_fresh_browser_storage_without_resetting_agent_page(
- tmp_path: Path,
-) -> None:
- workspace = tmp_path / "workspace"
- app = workspace / "app"
- app.mkdir(parents=True)
- (app / "index.html").write_text(
- '",
- encoding="utf-8",
- )
- port = StudioNativeBrowserPort(
- scope=_SCOPE,
- root=workspace,
- runtime_id="test-browser",
- evidence_root=tmp_path / "evidence",
- )
- try:
- first = await port.execute(_request("run", "opened"))
- assert first.status == "ok"
- warmed = await port.execute(_request("run", "warmed", actions=[{"type": "reload"}]))
- assert warmed.status == "ok"
- observed = await port.verify_page(
- run_id="run", entry_path="app/index.html", candidate_id="candidate"
- )
- assert any("cold-start-broken" in error for error in observed.page_errors)
- assert observed.session_ref.session_id != first.content["browser_session_id"]
- resumed = await port.execute(
- _request("run", "continued", actions=[{"type": "click", "selector": "#new"}])
- )
- assert resumed.status == "ok"
- assert resumed.content["browser_session_id"] == first.content["browser_session_id"]
- finally:
- await port.aclose()
-
-
-@pytest.mark.asyncio
-async def test_host_verification_does_not_click_ambiguous_launch_controls(tmp_path: Path) -> None:
- workspace = tmp_path / "workspace"
- workspace.mkdir()
- (workspace / "index.html").write_text(
- ''
- '',
- encoding="utf-8",
- )
- port = StudioNativeBrowserPort(
- scope=_SCOPE,
- root=workspace,
- runtime_id="test-browser",
- evidence_root=tmp_path / "evidence",
- )
- try:
- observation = await port.verify_page(
- run_id="run", entry_path="index.html", candidate_id="candidate"
- )
- assert observation.action_id.endswith(":1")
- assert observation.status == "ok"
- assert not observation.page_errors
- finally:
- await port.aclose()
-
-
-class _TwoTurnBrowserClient:
- def __init__(self) -> None:
- self.requests: list[dict] = []
-
- async def complete(self, _model, **kwargs):
- self.requests.append(kwargs)
- turn = len(self.requests)
- calls = (
- [
- ToolCall(
- id=f"browser-{turn}",
- name="browser_inspect_workspace",
- arguments=(
- '{"path":"app/index.html","wait_ms":0,'
- '"actions":[{"type":"click","selector":"#increment"}]}'
- ),
- )
- ]
- if turn <= 2
- else []
- )
- return ModelResponse(
- content="2" if turn == 3 else "",
- finish_reason="stop" if turn == 3 else "tool_calls",
- usage=Usage(input_tokens=20, output_tokens=8, total_tokens=28, reported=True),
- tool_calls=calls,
- raw_message={},
- )
-
-
-@pytest.mark.asyncio
-async def test_ordinary_studio_native_keeps_browser_page_across_model_turns(
- tmp_path: Path, monkeypatch: pytest.MonkeyPatch
-) -> None:
- _managed_profile(tmp_path, monkeypatch)
- monkeypatch.setenv("KSADK_SANDBOX_BACKEND", "local")
- monkeypatch.setenv("NATIVE_PRODUCT_TEST_KEY", "fixture-key")
- root = tmp_path / "studio"
- app = root / ".harness-tools" / "workspace" / "app"
- app.mkdir(parents=True)
- (app / "index.html").write_text(
- "0",
- encoding="utf-8",
- )
- client = _TwoTurnBrowserClient()
- studio = StudioService(
- root, model_client=client, native_harness_agent_ids=("browser-native-agent",)
- )
- try:
- browser = next(
- item
- for item in studio.catalog.list(kind="tool", limit=200)
- if item.name == "browser_inspect_workspace"
- )
- studio.create_agent(
- agent_id="browser-native-agent",
- name="Browser continuity",
- spec=AgentSpec(
- runtime=RuntimeRef(type="harness"),
- instructions=Instructions(system="Use the bound browser."),
- model=ModelSpec(
- model="fixture-model",
- endpoint_url="https://example.invalid/v1/chat/completions",
- credential_ref="env://NATIVE_PRODUCT_TEST_KEY",
- ),
- bindings=AgentBindings(
- policy_template="loose",
- tools=[CapabilityBinding(resource_id=browser.resource_id)],
- ),
- execution=ExecutionSpec(max_steps=8, timeout_seconds=180),
- security=SecuritySpec(
- allowed_permissions=["process:host-user"],
- network=NetworkPolicy(allowed_hosts=["example.invalid"]),
- ),
- ),
- )
- build = await studio.ensure_current_build("browser-native-agent")
- result = await studio.run_build(
- build.id,
- "Click increment twice in the same browser page, then report the count.",
- "browser-continuity-session",
- approval_mode="full",
- )
- assert result.status == RunStatus.COMPLETED, result.error
- assert len(client.requests) == 3
- assert "increment1" in str(client.requests[1]["messages"])
- assert "increment2" in str(client.requests[2]["messages"]), client.requests[2]["messages"][
- -1
- ]
- finally:
- await studio.aclose()
-
-
-class _DeliveryCheckpointClient:
- def __init__(self) -> None:
- self.requests: list[dict] = []
-
- async def complete(self, _model, **kwargs):
- self.requests.append(kwargs)
- turn = len(self.requests)
- if turn in {1, 2}:
- path = "app/index.html" if turn == 1 else "app/autotest.html"
- content = "" if turn == 1 else "test fixture
"
- calls = [
- ToolCall(
- id=f"write-{turn}",
- name="write_workspace_file",
- arguments=json.dumps({"path": path, "content": content}),
- )
- ]
- elif turn in {3, 4}:
- path = "app/autotest.html" if turn == 3 else "app/index.html"
- calls = [
- ToolCall(
- id=f"browser-{turn}",
- name="browser_inspect_workspace",
- arguments=json.dumps({"path": path, "wait_ms": 0}),
- )
- ]
- else:
- calls = []
- return ModelResponse(
- content="Created and inspected the page." if not calls else "",
- finish_reason="stop" if not calls else "tool_calls",
- usage=Usage(input_tokens=20, output_tokens=8, total_tokens=28, reported=True),
- tool_calls=calls,
- raw_message={},
- )
-
-
-def _verification_observation(messages):
- for message in reversed(messages):
- content = message.get("content")
- if not isinstance(content, str):
- continue
- try:
- value = json.loads(content)
- except ValueError:
- continue
- if isinstance(value, dict) and {"failed", "blocked", "not_run"} <= value.keys():
- return value
- raise AssertionError("Expected structured verification feedback")
-
-
-async def _native_snapshot(studio, record):
- metadata = await studio.session_service.get_session_metadata(record.session_id)
- scope = RunScope(
- tenant_id="local-studio", workspace_id=studio.workspace_record.workspace_id,
- user_id=metadata.user_id, agent_id=metadata.agent_id,
- )
- return studio._native_product_composer.store.load(scope, record.runtime_handle["run_id"])
-
-
-@pytest.mark.asyncio
-async def test_browser_on_auxiliary_page_triggers_delivery_checkpoint_before_final(
- tmp_path: Path, monkeypatch: pytest.MonkeyPatch
-) -> None:
- _managed_profile(tmp_path, monkeypatch)
- monkeypatch.setenv("KSADK_SANDBOX_BACKEND", "local")
- monkeypatch.setenv("NATIVE_PRODUCT_TEST_KEY", "fixture-key")
- client = _DeliveryCheckpointClient()
- studio = StudioService(
- tmp_path / "studio",
- model_client=client,
- native_harness_agent_ids=("delivery-checkpoint-agent",),
- )
- try:
- resources = {item.name: item for item in studio.catalog.list(kind="tool", limit=200)}
- studio.create_agent(
- agent_id="delivery-checkpoint-agent",
- name="Delivery checkpoint",
- spec=AgentSpec(
- runtime=RuntimeRef(type="harness"),
- instructions=Instructions(system="Complete the user's web task."),
- model=ModelSpec(
- model="fixture-model",
- endpoint_url="https://example.invalid/v1/chat/completions",
- credential_ref="env://NATIVE_PRODUCT_TEST_KEY",
- ),
- bindings=AgentBindings(
- policy_template="loose",
- tools=[
- CapabilityBinding(resource_id=resources[name].resource_id)
- for name in ("write_workspace_file", "browser_inspect_workspace")
- ],
- ),
- execution=ExecutionSpec(max_steps=12, timeout_seconds=180),
- security=SecuritySpec(
- allowed_permissions=["process:host-user", "workspace:file:write"],
- network=NetworkPolicy(allowed_hosts=["example.invalid"]),
- ),
- ),
- )
- build = await studio.ensure_current_build("delivery-checkpoint-agent")
- result = await studio.run_build(
- build.id,
- "Create a working web page in app/index.html and inspect it.",
- "delivery-checkpoint-session",
- approval_mode="full",
- )
- assert result.status == RunStatus.COMPLETED, result.error
- assert len(client.requests) == 5
- feedback = _verification_observation(client.requests[3]["messages"])
- assert feedback["failed"] == feedback["not_run"] == []
- (blocked,) = feedback["blocked"]
- assert blocked["status"] == "blocked"
- assert "changed files belong to multiple pages" in blocked["safe_summary"]
- snapshot = await _native_snapshot(studio, result)
- assert result.verification_outcome == snapshot.outcome == "blocked"
- assert snapshot.repair_attempts == 0 and not snapshot.verification["repairable"]
- with sqlite3.connect(
- tmp_path / "studio" / ".agentengine" / "ui" / "sessions.sqlite"
- ) as connection:
- checkpoint_rows = connection.execute(
- "SELECT content_json FROM ksadk_events "
- "WHERE content_json LIKE '%verification.checkpoint_started%'"
- ).fetchall()
- checkpoint_ids = {
- json.loads(row[0])["runtime_event"]["source"]["native_event_id"]
- for row in checkpoint_rows
- }
- assert len(checkpoint_ids) == 1
- finally:
- await studio.aclose()
-
-
-class _BrokenThenRepairedPageClient:
- def __init__(
- self,
- *,
- interactive: bool = False,
- duplicate_launch: bool = False,
- obscured_launch: bool = False,
- ) -> None:
- self.requests: list[dict] = []
- self.interactive = interactive
- self.duplicate_launch = duplicate_launch
- self.obscured_launch = obscured_launch
-
- async def complete(self, _model, **kwargs):
- self.requests.append(kwargs)
- turn = len(self.requests)
- if turn in {1, 3}:
- if self.duplicate_launch:
- content = (
- ''
- if turn == 1
- else 'repaired
'
- )
- elif self.obscured_launch:
- content = (
- ''
- 'Loading
'
- if turn == 1
- else 'repaired
'
- )
- elif self.interactive:
- behavior = (
- "setTimeout(() => {throw new Error('start-broken')}, 30)"
- if turn == 1
- else "window.ready = true"
- )
- content = (
- f"{'built' if turn == 1 else 'repaired'}
"
- f''
- )
- else:
- content = (
- "built
"
- if turn == 1
- else "repaired
"
- )
- calls = [
- ToolCall(
- id=f"write-{turn}",
- name="write_workspace_file",
- arguments='{"path":"app/index.html","content":' + json.dumps(content) + "}",
- )
- ]
- elif turn == 4:
- calls = [
- ToolCall(
- id="observe-repaired-page",
- name="browser_inspect_workspace",
- arguments=json.dumps(
- {
- "path": "app/index.html",
- "actions": (
- [{"type": "click", "selector": "#start"}]
- if self.interactive
- else []
- ),
- "wait_ms": 100,
- }
- ),
- )
- ]
- else:
- calls = []
- return ModelResponse(
- content="The page is ready." if not calls else "",
- finish_reason="tool_calls" if calls else "stop",
- usage=Usage(input_tokens=20, output_tokens=8, total_tokens=28, reported=True),
- tool_calls=calls,
- raw_message={},
- )
-
-
-class _LateRepairPageClient:
- def __init__(self) -> None:
- self.requests: list[dict] = []
-
- async def complete(self, _model, **kwargs):
- self.requests.append(kwargs)
- turn = len(self.requests)
- if turn in {1, 9}:
- content = (
- "built
"
- if turn == 1
- else "repaired
"
- )
- name = "write_workspace_file"
- arguments = json.dumps({"path": "app/index.html", "content": content})
- elif turn <= 8:
- name = "read_workspace_file"
- arguments = json.dumps({"path": "app/index.html"})
- elif turn == 10:
- name = "browser_inspect_workspace"
- arguments = json.dumps({"path": "app/index.html", "wait_ms": 100})
- else:
- name = None
- arguments = ""
- calls = (
- [ToolCall(id=f"call-{turn}", name=name, arguments=arguments)]
- if name is not None
- else []
- )
- return ModelResponse(
- content="The page is ready." if not calls else "",
- finish_reason="tool_calls" if calls else "stop",
- usage=Usage(input_tokens=20, output_tokens=8, total_tokens=28, reported=True),
- tool_calls=calls,
- raw_message={},
- )
-
-
-@pytest.mark.asyncio
-async def test_studio_native_checks_dirty_workspace_before_model_budget_exhaustion(
- tmp_path: Path, monkeypatch: pytest.MonkeyPatch
-) -> None:
- _managed_profile(tmp_path, monkeypatch)
- monkeypatch.setenv("KSADK_SANDBOX_BACKEND", "local")
- monkeypatch.setenv("NATIVE_PRODUCT_TEST_KEY", "fixture-key")
- root = tmp_path / "studio"
- client = _LateRepairPageClient()
- studio = StudioService(
- root, model_client=client, native_harness_agent_ids=("browser-native-agent",)
- )
- try:
- catalog = {item.name: item for item in studio.catalog.list(kind="tool", limit=200)}
- studio.create_agent(
- agent_id="browser-native-agent",
- name="Late browser repair",
- spec=AgentSpec(
- runtime=RuntimeRef(type="harness"),
- instructions=Instructions(system="Build and check the page."),
- model=ModelSpec(
- model="fixture-model",
- endpoint_url="https://example.invalid/v1/chat/completions",
- credential_ref="env://NATIVE_PRODUCT_TEST_KEY",
- ),
- bindings=AgentBindings(
- policy_template="loose",
- tools=[
- CapabilityBinding(resource_id=catalog[name].resource_id)
- for name in (
- "write_workspace_file",
- "read_workspace_file",
- "browser_inspect_workspace",
- )
- ],
- ),
- execution=ExecutionSpec(max_steps=12, timeout_seconds=180),
- security=SecuritySpec(
- allowed_permissions=["process:host-user"],
- network=NetworkPolicy(allowed_hosts=["example.invalid"]),
- ),
- ),
- )
- build = await studio.ensure_current_build("browser-native-agent")
- result = await studio.run_build(
- build.id,
- "Build a working page in app/index.html.",
- "late-browser-repair-session",
- approval_mode="full",
- )
- assert result.status == RunStatus.COMPLETED, result.error
- assert len(client.requests) == 11
- assert "Browser reported an error" in str(client.requests[5]["messages"])
- assert "Browser reported an error" in str(client.requests[8]["messages"])
- assert "repaired" in (root / ".harness-tools/workspace/app/index.html").read_text()
- assert len(list((root / ".harness-tools/state/browser-verification").glob("*.png"))) >= 2
- finally:
- await studio.aclose()
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize(
- "mode", ["script_error", "late_click_error", "duplicate_launch", "obscured_launch"]
-)
-async def test_ordinary_studio_native_browser_failure_reenters_repair(
- tmp_path: Path, monkeypatch: pytest.MonkeyPatch, mode: str
-) -> None:
- _managed_profile(tmp_path, monkeypatch)
- monkeypatch.setenv("KSADK_SANDBOX_BACKEND", "local")
- monkeypatch.setenv("NATIVE_PRODUCT_TEST_KEY", "fixture-key")
- root = tmp_path / "studio"
- client = _BrokenThenRepairedPageClient(
- interactive=mode == "late_click_error",
- duplicate_launch=mode == "duplicate_launch",
- obscured_launch=mode == "obscured_launch",
- )
- observations = []
- verify_page = StudioNativeBrowserPort.verify_page
-
- async def observe_verification(port, **kwargs):
- observation = await verify_page(port, **kwargs)
- observations.append(observation)
- return observation
-
- monkeypatch.setattr(StudioNativeBrowserPort, "verify_page", observe_verification)
- studio = StudioService(
- root, model_client=client, native_harness_agent_ids=("browser-native-agent",)
- )
- try:
- catalog = {item.name: item for item in studio.catalog.list(kind="tool", limit=200)}
- studio.create_agent(
- agent_id="browser-native-agent",
- name="Browser repair",
- spec=AgentSpec(
- runtime=RuntimeRef(type="harness"),
- instructions=Instructions(system="Build and check the page."),
- model=ModelSpec(
- model="fixture-model",
- endpoint_url="https://example.invalid/v1/chat/completions",
- credential_ref="env://NATIVE_PRODUCT_TEST_KEY",
- ),
- bindings=AgentBindings(
- policy_template="loose",
- tools=[
- CapabilityBinding(resource_id=catalog[name].resource_id)
- for name in ("write_workspace_file", "browser_inspect_workspace")
- ],
- ),
- execution=ExecutionSpec(max_steps=12, timeout_seconds=180),
- security=SecuritySpec(
- allowed_permissions=["process:host-user"],
- network=NetworkPolicy(allowed_hosts=["example.invalid"]),
- ),
- ),
- )
- build = await studio.ensure_current_build("browser-native-agent")
- result = await studio.run_build(
- build.id,
- "Build a working page in app/index.html.",
- "browser-repair-session",
- approval_mode="full",
- )
- assert result.status == RunStatus.COMPLETED, result.error
- if mode == "obscured_launch":
- assert len(client.requests) == 2
- (observation,) = observations
- assert observation.status == "error"
- assert observation.error_code == "selector_not_actionable"
- assert observation.complete and observation.retryability == "safe"
- (start,) = [control for control in observation.controls if control.label == "Start"]
- assert start.clickable and start.hit_test_reachable is False
- snapshot = await _native_snapshot(studio, result)
- assert result.verification_outcome == snapshot.outcome == "blocked"
- assert snapshot.repair_attempts == 0 and not snapshot.verification["repairable"]
- (item,) = snapshot.verification["items"]
- assert item["status"] == "blocked" and item["evidence_refs"]
- assert "incomplete host observation" in item["safe_summary"]
- assert "Loading" in (root / ".harness-tools/workspace/app/index.html").read_text()
- assert observation.screenshot is not None
- return
- assert len(client.requests) == 5
- expected = (
- "multiple visible start controls"
- if mode == "duplicate_launch"
- else "Browser reported an error"
- )
- assert expected in str(client.requests[2]["messages"])
- assert "repaired" in (root / ".harness-tools/workspace/app/index.html").read_text()
- evidence = root / ".harness-tools/state/browser-verification"
- assert len(list(evidence.glob("*.png"))) >= 2
- finally:
- await studio.aclose()
diff --git a/tests/studio/test_native_default_install.py b/tests/studio/test_native_default_install.py
deleted file mode 100644
index 3bd52385e..000000000
--- a/tests/studio/test_native_default_install.py
+++ /dev/null
@@ -1,100 +0,0 @@
-"""Default release assembly must execute Native without optional frameworks."""
-
-import importlib
-import os
-import subprocess
-import sys
-from pathlib import Path
-
-import pytest
-from packaging.requirements import Requirement
-
-tomllib = importlib.import_module("tomllib" if sys.version_info >= (3, 11) else "tomli")
-
-ROOT = Path(__file__).resolve().parents[2]
-
-
-@pytest.mark.parametrize("streaming", [False, True])
-@pytest.mark.parametrize("durable", [None, False, True])
-def test_cold_default_studio_build_and_tools_without_framework_imports(streaming, durable):
- command = [sys.executable, str(ROOT / "scripts/verify_native_studio_install.py")]
- if streaming:
- command.append("--streaming")
- if durable is True:
- command.append("--durable")
- elif durable is False:
- command.append("--memory")
- environment = dict(os.environ, PYTHONPATH=str(ROOT))
- completed = subprocess.run(command, cwd=ROOT, env=environment, text=True,
- capture_output=True, timeout=60, check=False)
- assert completed.returncode == 0, completed.stdout + completed.stderr
- assert '"engine": "native"' in completed.stdout
-
-
-def test_base_dependency_contract_keeps_managed_factory_dependency():
- project = tomllib.loads((ROOT / "pyproject.toml").read_text())["project"]
- names = {Requirement(raw).name for raw in project["dependencies"]}
- assert "langgraph" in names
- assert "langgraph-checkpoint-sqlite" in names
- assert not names & {"langchain", "langchain-core"}
- for name in ("langgraph", "langchain", "deepagents"):
- assert project["optional-dependencies"][name]
-
-
-@pytest.mark.parametrize("configuration,default,enabled", [
- ({}, True, True),
- ({"native_harness_default": False}, False, False),
- ({"native_harness_agent_ids": ()}, False, False),
- ({"native_harness_agent_ids": ("one",)}, False, True),
- ({"native_harness_default": True, "native_harness_agent_ids": ("one",)}, True, True),
- ({"harness_reasoner": object()}, False, False),
-])
-@pytest.mark.asyncio
-async def test_default_and_explicit_compatibility_selection(
- tmp_path, monkeypatch, configuration, default, enabled,
-):
- from ksadk.studio.service import StudioService
- from tests.studio.test_dsh_provider_registration import _managed_profile
-
- _managed_profile(tmp_path, monkeypatch)
- monkeypatch.delenv("KSADK_STUDIO_NATIVE_DEFAULT", raising=False)
- monkeypatch.delenv("KSADK_STUDIO_NATIVE_AGENT_IDS", raising=False)
- monkeypatch.delenv("KSADK_STUDIO_NATIVE_DURABLE", raising=False)
- studio = StudioService(tmp_path / "workspace", **configuration)
- try:
- assert studio._native_harness_default is default
- assert studio._native_harness_durable is default
- assert (studio._native_product_composer is not None) is enabled
- finally:
- await studio.aclose()
-
-
-@pytest.mark.asyncio
-async def test_native_default_environment_and_explicit_override(tmp_path, monkeypatch):
- from ksadk.studio.service import StudioService
- from tests.studio.test_dsh_provider_registration import _managed_profile
-
- _managed_profile(tmp_path, monkeypatch)
- monkeypatch.setenv("KSADK_STUDIO_NATIVE_DEFAULT", "1")
- monkeypatch.setenv("KSADK_STUDIO_NATIVE_AGENT_IDS", "selected")
- studio = StudioService(tmp_path / "default")
- try:
- assert studio._native_harness_default is True
- compatibility = StudioService(tmp_path / "compatibility", native_harness_default=False,
- native_harness_agent_ids=())
- try:
- assert compatibility._native_product_composer is None
- finally:
- await compatibility.aclose()
- finally:
- await studio.aclose()
-
-
-@pytest.mark.parametrize("value", ["maybe", "", "true"])
-def test_invalid_native_default_fails_before_opening_workspace(tmp_path, monkeypatch, value):
- from ksadk.studio.service import StudioService
-
- monkeypatch.setenv("KSADK_STUDIO_NATIVE_DEFAULT", value)
- with pytest.raises(ValueError, match="KSADK_STUDIO_NATIVE_DEFAULT"):
- StudioService(tmp_path / "workspace")
- assert not (tmp_path / "workspace").exists()
diff --git a/tests/studio/test_native_delivery_evidence_routing.py b/tests/studio/test_native_delivery_evidence_routing.py
deleted file mode 100644
index c46b1445d..000000000
--- a/tests/studio/test_native_delivery_evidence_routing.py
+++ /dev/null
@@ -1,346 +0,0 @@
-"""Installed tools are capabilities, not per-goal acceptance evidence."""
-
-import hashlib
-from types import SimpleNamespace
-
-import pytest
-
-from ksadk.harness.native.completion import AcceptanceItem, TaskContract, reduce_completion
-from ksadk.harness.native_runtime import TaskContractInput
-from ksadk.studio.contracts import RunStatus
-from ksadk.studio.native_final_shape import StudioFinalShapeVerifier
-from ksadk.studio.native_product import _activation_contract, _goal_contract
-from ksadk.studio.service import StudioService
-from tests.studio.test_native_final_shape import SCOPE, request
-from tests.studio.test_native_product_durability import (
- RecordingClient,
- _suspend_product,
- _wait_for,
-)
-
-EVIDENCE_REF = "studio.delivery-evidence-rejection"
-EVIDENCE_VERSION = "1"
-
-
-def contract(goal, *, parent=None):
- return _goal_contract(TaskContractInput(
- goal=goal, session_id="session", parent_run_id="parent" if parent else None,
- parent_goal="Previous web task" if parent else None, parent_contract=parent,
- ))
-
-
-def verifier(tmp_path, *, changed=(), errors=(), observed=True, visual=False):
- # An existing page must not turn a Python edit into a web delivery.
- (tmp_path / "index.html").write_text("existing page
")
- state = SimpleNamespace(
- messages=(), workspace_modified_paths=changed,
- unresolved_interaction_observation=None, last_web_mutation_tool_call=1,
- last_browser_observation={"entry_path": "index.html", "tool_call": 2}
- if observed else None,
- )
- calls = []
-
- class Browser:
- async def verify_page(self, **kwargs):
- calls.append(kwargs)
- return SimpleNamespace(
- status="ok", status_code=200, error_code=None, controls=(), page_errors=errors,
- console=(), network_failures=(), screenshot=None,
- )
-
- return StudioFinalShapeVerifier(
- SCOPE, build_id="build", workspace_root=tmp_path,
- store=SimpleNamespace(load=lambda *_: state), browser=Browser(),
- require_visual_feedback=visual,
- ), calls
-
-
-def test_new_goals_pin_general_evidence_without_inheriting_parent_output_protocol():
- parent = contract("Build the page. Return only a JSON object.")
- current = contract("Fix the Python session manager.", parent=parent)
- item = current.items[0]
- assert (item.verifier_ref, item.verifier_version) == (EVIDENCE_REF, EVIDENCE_VERSION)
- assert item.required and item.verification_method == "deterministic"
- assert current.final_submission_schema is None
- assert current.final_submission_payload_key is None
-
-
-@pytest.mark.parametrize("browser_available", [False, True])
-def test_activation_anchor_preserves_legacy_configuration_for_cold_attach(browser_available):
- anchor = _activation_contract("activation", browser_available=browser_available)
- revision = hashlib.sha256(b"activation\0\0Initial activation contract").hexdigest()[:24]
- assert anchor.model_dump(mode="json") == {
- "revision": f"studio-goal-{revision}",
- "items": [{
- "acceptance_id": "current_user_goal", "required": True,
- "verifier_ref": "studio.browser-smoke-rejection" if browser_available
- else "studio.independent-evidence-unavailable",
- "verifier_version": "9" if browser_available else "1",
- "verification_method": "deterministic" if browser_available else "human",
- "description": "Initial activation contract",
- }],
- "allowed_tool_names": None, "final_submission_schema": None,
- "final_submission_payload_key": None, "host_resolved_answer": None,
- }
- assert contract("New real goal.").items[0].verifier_ref == EVIDENCE_REF
-
-
-@pytest.mark.asyncio
-async def test_python_changes_do_not_consume_browser_or_claim_semantic_success(tmp_path):
- port, calls = verifier(tmp_path, changed=("app/events.py",))
- task = contract("Fix the Python session manager.")
- result = await port.verify(request("unused", "Done.").model_copy(update={"contract": task}))
- assert calls == []
- assert result.report is not None
- item = result.report.items[0]
- assert item.status == "not_run" and not result.report.repairable
- assert "browser" not in item.safe_summary.lower()
- assert "semantics" in item.safe_summary.lower()
- assert reduce_completion(task, result.candidate, result.report).outcome == "unverified"
-
-
-@pytest.mark.parametrize("checkpoint", [False, True])
-@pytest.mark.asyncio
-async def test_real_web_change_rejects_page_errors_at_final_and_checkpoint(tmp_path, checkpoint):
- port, calls = verifier(tmp_path, changed=("index.html",), errors=("ReferenceError: broken",))
- task = contract("Implement the requested feature.")
- req = request("unused", "Done.").model_copy(update={
- "contract": task, "purpose": "checkpoint" if checkpoint else "final",
- })
- result = await port.verify(req)
- assert len(calls) == 1 and calls[0]["entry_path"] == "index.html"
- assert result.report.items[0].status == "failed"
- assert result.report.repairable
- assert reduce_completion(task, result.candidate, result.report).action == "repair"
-
-
-@pytest.mark.parametrize("observed,visual", [(True, False), (False, False), (True, True)])
-@pytest.mark.asyncio
-async def test_new_binding_keeps_browser_observation_and_visual_gates(tmp_path, observed, visual):
- port, calls = verifier(tmp_path, changed=("index.html",), observed=observed, visual=visual)
- task = contract("Build the requested page.")
- result = await port.verify(request("unused", "Done.").model_copy(update={"contract": task}))
- assert len(calls) == 1
- expected = "not_run" if observed and not visual else "failed"
- assert result.report.items[0].status == expected
- assert result.report.repairable is (expected == "failed")
- if expected == "not_run":
- assert reduce_completion(task, result.candidate, result.report).outcome == "unverified"
-
-
-@pytest.mark.asyncio
-async def test_explicit_output_shape_does_not_hide_web_failure(tmp_path):
- port, calls = verifier(tmp_path, changed=("index.html",), errors=("script error",))
- task = contract("Build the requested page. Return only a JSON object.")
- result = await port.verify(request("unused", '{"done":true}').model_copy(
- update={"contract": task}
- ))
- assert len(calls) == 1 and result.report.items[0].status == "failed"
- assert "Browser reported an error" in result.report.items[0].safe_summary
-
-
-@pytest.mark.asyncio
-async def test_legacy_shape_contract_is_not_silently_upgraded_to_browser_checks(tmp_path):
- port, calls = verifier(tmp_path, changed=("index.html",), errors=("script error",))
- legacy = request("Return only the total.", "42")
- result = await port.verify(legacy)
- assert calls == [] and result.report.items[0].status == "not_run"
- fresh = await port.verify(legacy.model_copy(
- update={"contract": contract("Return only the total.")}
- ))
- assert fresh.candidate.environment_digest != result.candidate.environment_digest
- assert fresh.report.items[0].status == "failed"
-
-
-@pytest.mark.asyncio
-async def test_non_web_checkpoint_does_not_start_a_repair_loop(tmp_path):
- port, calls = verifier(tmp_path, changed=("app/events.py",))
- result = await port.verify(request("unused", "").model_copy(update={
- "contract": contract("Fix Python code."), "purpose": "checkpoint",
- }))
- assert calls == [] and result.report is None
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize("observed", [True, False])
-async def test_continued_nested_game_does_not_verify_old_root_page(tmp_path, observed):
- port, calls = verifier(tmp_path, changed=("mario/game.js",), observed=observed)
- (tmp_path / "mario").mkdir()
- (tmp_path / "mario/index.html").write_text('')
- (tmp_path / "mario/game.js").write_text("// updated game")
- state = port._store.load(SCOPE, "run")
- state.last_browser_observation = (
- {"entry_path": "mario/index.html", "tool_call": 2} if observed else None
- )
- task = contract("Continue the existing Mario game in mario/.")
- result = await port.verify(request("unused", "Done.").model_copy(update={"contract": task}))
- assert [call["entry_path"] for call in calls] == ["mario/index.html"]
- assert result.report.items[0].status == ("not_run" if observed else "failed")
- if observed:
- assert not result.report.repairable
- assert reduce_completion(task, result.candidate, result.report).outcome == "unverified"
-
-
-@pytest.mark.asyncio
-async def test_unbound_web_project_blocks_without_spending_game_repair_budget(tmp_path):
- port, calls = verifier(tmp_path, changed=("one/index.html", "two/index.html"))
- for name in ("one", "two"):
- (tmp_path / name).mkdir()
- (tmp_path / name / "index.html").write_text("different project
")
- task = contract("Update the requested web project.")
- for purpose in ("checkpoint", "final"):
- result = await port.verify(request("unused", "Done.").model_copy(
- update={"contract": task, "purpose": purpose}
- ))
- assert calls == []
- assert result.report.items[0].status == "blocked"
- assert "entry" in result.report.items[0].safe_summary
- assert not result.report.repairable
- decision = reduce_completion(task, result.candidate, result.report)
- assert decision.reason == "required_acceptance_blocked"
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize("changed", ["mario/game.js", "mario/missing.html", "../outside.js"])
-async def test_missing_or_unsafe_binding_never_falls_back_to_old_root_page(tmp_path, changed):
- port, calls = verifier(tmp_path, changed=(changed,))
- task = contract("Continue the nested project.")
- result = await port.verify(request("unused", "Done.").model_copy(update={"contract": task}))
- assert calls == []
- assert result.report.items[0].status == "blocked"
- assert not result.report.repairable
-
-
-@pytest.mark.asyncio
-async def test_continued_custom_entry_preserves_host_observed_page(tmp_path):
- port, calls = verifier(tmp_path, changed=("mario/src/game.js",))
- (tmp_path / "mario/src").mkdir(parents=True)
- (tmp_path / "mario/play.html").write_text('')
- state = port._store.load(SCOPE, "run")
- state.last_browser_observation = {"entry_path": "mario/play.html", "tool_call": 2}
- task = contract("Continue the nested game.")
- result = await port.verify(request("unused", "Done.").model_copy(update={"contract": task}))
- assert [call["entry_path"] for call in calls] == ["mario/play.html"]
- assert result.report.items[0].status == "not_run"
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize("reference,expected", [
- ('', "not_run"),
- ('', "blocked"),
-])
-async def test_root_project_requires_local_reference_to_nested_asset(tmp_path, reference, expected):
- port, calls = verifier(tmp_path, changed=("src/main.js",))
- (tmp_path / "index.html").write_text(reference)
- (tmp_path / "src").mkdir()
- (tmp_path / "src/main.js").write_text("// current asset")
- task = contract("Continue this web project.")
- result = await port.verify(request("unused", "Done.").model_copy(update={"contract": task}))
- assert result.report.items[0].status == expected
- assert bool(calls) == (expected == "not_run")
-
-
-@pytest.mark.asyncio
-async def test_entry_symlink_cannot_select_an_outside_page(tmp_path):
- port, calls = verifier(tmp_path, changed=("mario/index.html",))
- (tmp_path / "mario").mkdir()
- outside = tmp_path.parent / (tmp_path.name + "-outside.html")
- outside.write_text("outside
")
- (tmp_path / "mario/index.html").symlink_to(outside)
- task = contract("Continue the nested game.")
- result = await port.verify(request("unused", "Done.").model_copy(update={"contract": task}))
- assert calls == [] and result.report.items[0].status == "blocked"
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize("failure", ["exception", "incomplete", "http", "duplicate"])
-async def test_host_browser_blockers_do_not_request_game_repairs(tmp_path, failure):
- port, calls = verifier(tmp_path, changed=("index.html",), observed=False)
-
- class Browser:
- async def verify_page(self, **kwargs):
- calls.append(kwargs)
- if failure == "exception":
- raise RuntimeError("private host error must not be disclosed")
- return SimpleNamespace(
- status="incomplete" if failure == "incomplete" else "error",
- status_code=404 if failure == "http" else None,
- error_code="browser_launch_control_ambiguous" if failure == "duplicate"
- else "observation_capture_failed_after_action",
- controls=(), page_errors=(), console=(), network_failures=(), screenshot=None,
- )
-
- port._browser = Browser()
- task = contract("Complete the game and verify it in the browser.")
- for purpose in ("final", "checkpoint"):
- result = await port.verify(request("unused", "Everything completed.").model_copy(
- update={"contract": task, "purpose": purpose}
- ))
- item = result.report.items[0]
- blocked = failure in {"exception", "incomplete"}
- assert item.status == ("blocked" if blocked else "failed")
- assert result.report.repairable is not blocked
- assert "private host error" not in item.safe_summary
- decision = reduce_completion(task, result.candidate, result.report)
- assert decision.reason == (
- "required_acceptance_blocked" if blocked else "required_acceptance_failed"
- )
- assert decision.action == ("finalize" if blocked else "repair")
-
-
-@pytest.mark.asyncio
-async def test_legacy_pending_run_restores_unchanged_then_new_turn_uses_new_binding(
- tmp_path, monkeypatch,
-):
- from ksadk.studio import native_product
-
- def legacy_plain_contract(facts):
- revision = hashlib.sha256(
- f"{facts.session_id}\0{facts.parent_run_id or ''}\0{facts.goal}".encode()
- ).hexdigest()[:24]
- return TaskContract(revision=f"studio-goal-{revision}", items=(AcceptanceItem(
- acceptance_id="current_user_goal",
- verifier_ref="studio.independent-evidence-unavailable",
- verifier_version="1", verification_method="human", description=facts.goal[:1024],
- ),))
-
- # Freeze the prior plain-goal contract before shutdown, not rewrite its
- # SQLite row after the new reader starts. Model transport is a fixture;
- # Build, DSH activation, SQLite, approval and file execution are real.
- with monkeypatch.context() as prior:
- prior.setattr(native_product, "_goal_contract", legacy_plain_contract)
- root, original, scope, approval = await _suspend_product(tmp_path, monkeypatch)
- native_id = original.runtime_handle["run_id"]
- client = RecordingClient("The approved write is complete.")
- second = StudioService(root, model_client=client)
- try:
- before = second._native_product_composer.store.load(scope, native_id).task_contract
- await second.start()
- await second.run_service.recover_interrupted(second.resolve_run_spec)
- await _wait_for(lambda: (
- second.run_service._waiting_modes.get(original.id) == "resume"
- and second.event_store.get(original.id).status == RunStatus.WAITING_INPUT
- ) or second.event_store.get(original.id).status == RunStatus.INTERRUPTED)
- assert second.event_store.get(original.id).status == RunStatus.WAITING_INPUT
- assert second.event_store.get(original.id).runtime_handle == original.runtime_handle
- assert client.requests == [] and not list(root.rglob("approved.txt"))
- await second.run_service.submit_interaction(
- original.id, approval.data["approvalId"], name="approve", data={"decision": "approve"},
- expected_revision=1, idempotency_key="legacy-routing-approval",
- )
- await _wait_for(lambda: second.event_store.get(original.id).status == RunStatus.COMPLETED)
- await _wait_for(lambda: not second.run_service._recovery_tasks)
- restored = second._native_product_composer.store.load(scope, native_id)
- assert restored.task_contract == before
- assert len(list(root.rglob("approved.txt"))) == 1
- assert list(root.rglob("approved.txt"))[0].read_text() == "written once"
- following = await second.run_build(
- original.build_id, "Explain the result.", original.session_id
- )
- assert following.status == RunStatus.COMPLETED, following.error
- head = second._native_product_composer.store.session_head(scope, original.session_id)
- assert head.parent_run_id == native_id
- assert head.task_contract["items"][0]["verifier_ref"] == EVIDENCE_REF
- assert head.outcome == "unverified"
- finally:
- await second.aclose()
diff --git a/tests/studio/test_native_final_shape.py b/tests/studio/test_native_final_shape.py
deleted file mode 100644
index c55227fd0..000000000
--- a/tests/studio/test_native_final_shape.py
+++ /dev/null
@@ -1,625 +0,0 @@
-"""A final-answer shape failure may request repair, never semantic success."""
-
-from __future__ import annotations
-
-import json
-from types import SimpleNamespace
-
-import pytest
-
-from ksadk.harness.native.completion import AcceptanceItem, TaskContract, reduce_completion
-from ksadk.harness.native.ports import VerificationRequest
-from ksadk.harness.native.state import RunScope
-from ksadk.harness.native_runtime import TaskContractInput
-from ksadk.studio.native_final_shape import (
- BROWSER_VERIFIER_REF,
- BROWSER_VERIFIER_VERSION,
- EVIDENCE_VERIFIER_REF,
- VERIFIER_REF,
- VERIFIER_VERSION,
- StudioFinalShapeVerifier,
- _written_web_entry,
- requested_exact_workspace_file,
- requested_final_shape,
-)
-from ksadk.studio.native_product import _goal_contract
-
-SCOPE = RunScope(tenant_id="tenant", workspace_id="workspace", user_id="user", agent_id="agent")
-
-
-def test_explicit_json_goal_pins_submission_protocol_only_for_current_goal():
- structured = _goal_contract(
- TaskContractInput(
- goal="分析文件。最后只返回 JSON 对象,键为 incidents 和 total_cents。不能修改文件。",
- session_id="session",
- parent_run_id=None,
- parent_goal=None,
- parent_contract=None,
- )
- )
- assert structured.final_submission_schema["required"] == ["output"]
- assert structured.final_submission_payload_key == "output"
- following = _goal_contract(
- TaskContractInput(
- goal="解释结果。",
- session_id="session",
- parent_run_id="parent",
- parent_goal="分析文件。",
- parent_contract=structured,
- )
- )
- assert following.final_submission_schema is None
- assert following.items[0].verifier_ref == EVIDENCE_VERIFIER_REF
-
-
-def test_browser_entry_requires_observed_change_or_successful_write_receipt(tmp_path):
- entry = tmp_path / "app" / "index.html"
- entry.parent.mkdir()
- entry.write_text("page
")
- proposed = {
- "role": "assistant",
- "tool_calls": [
- {
- "id": "write-1",
- "function": {
- "name": "write_workspace_file",
- "arguments": json.dumps({"path": "app/index.html", "content": "page
"}),
- },
- }
- ],
- }
-
- def store(messages, changed=()):
- return SimpleNamespace(
- load=lambda *_: SimpleNamespace(messages=messages, workspace_modified_paths=changed)
- )
-
- failed = {"role": "tool", "tool_call_id": "write-1", "content": '{"status":"error"}'}
- assert _written_web_entry(store((proposed, failed)), SCOPE, "run", tmp_path) is None
- succeeded = {"role": "tool", "tool_call_id": "write-1", "content": '{"status":"ok"}'}
- assert (
- _written_web_entry(store((proposed, succeeded)), SCOPE, "run", tmp_path) == "app/index.html"
- )
- assert (
- _written_web_entry(store((), ("app/index.html",)), SCOPE, "run", tmp_path)
- == "app/index.html"
- )
-
-
-@pytest.mark.parametrize(
- ("page_errors", "network_failures", "expected_summary"),
- [
- (("script error",), (), "Browser reported an error"),
- (
- ("ReferenceError: Three is not defined",),
- ("network_denied: https://example.invalid/runtime.js",),
- "Browser blocked a page request under the locked network policy",
- ),
- (
- ("error: Failed to load resource: the server responded with a status of 404",),
- ("asset_http_error:404: /missing/game.js",),
- "/missing/game.js",
- ),
- ],
-)
-@pytest.mark.asyncio
-async def test_browser_failure_binds_evidence_to_observed_screenshot(
- tmp_path, page_errors, network_failures, expected_summary
-):
- (tmp_path / "index.html").write_text("broken
")
-
- class Browser:
- async def verify_page(self, **_kwargs):
- return SimpleNamespace(
- status="ok",
- status_code=200,
- controls=(),
- page_errors=page_errors,
- console=(),
- network_failures=network_failures,
- screenshot=SimpleNamespace(content_ref="sha256:" + "b" * 64),
- )
-
- store = SimpleNamespace(
- load=lambda *_: SimpleNamespace(messages=(), workspace_modified_paths=("index.html",))
- )
- browser_request = request("Build a working page.", "Done.").model_copy(
- update={
- "contract": TaskContract(
- revision="goal-v1",
- items=(
- AcceptanceItem(
- acceptance_id="current_user_goal",
- verifier_ref=BROWSER_VERIFIER_REF,
- verifier_version=BROWSER_VERIFIER_VERSION,
- verification_method="deterministic",
- description="Build a working page.",
- ),
- ),
- ),
- }
- )
- verifier = StudioFinalShapeVerifier(
- SCOPE, build_id="build-1", workspace_root=tmp_path, store=store, browser=Browser()
- )
- result = await verifier.verify(browser_request)
- assert result.report is not None
- assert result.report.items[0].status == "failed"
- assert result.report.items[0].evidence_refs == ("sha256:" + "b" * 64,)
- assert expected_summary in result.report.items[0].safe_summary
- assert "example.invalid" not in result.report.items[0].safe_summary
-
-
-@pytest.mark.asyncio
-async def test_headless_pointer_lock_denial_does_not_claim_game_failure(tmp_path):
- (tmp_path / "index.html").write_text("")
-
- class Browser:
- async def verify_page(self, **_kwargs):
- return SimpleNamespace(
- status="ok",
- status_code=200,
- controls=(),
- page_errors=("The root document of this element is not valid for pointer lock.",),
- console=(),
- network_failures=(),
- screenshot=None,
- )
-
- state = SimpleNamespace(
- messages=(),
- workspace_modified_paths=("index.html",),
- unresolved_interaction_observation=None,
- last_web_mutation_tool_call=1,
- last_browser_observation={"entry_path": "index.html", "tool_call": 2},
- )
- contract = TaskContract(
- revision="goal-v1",
- items=(
- AcceptanceItem(
- acceptance_id="current_user_goal",
- verifier_ref=BROWSER_VERIFIER_REF,
- verifier_version=BROWSER_VERIFIER_VERSION,
- verification_method="deterministic",
- description="Build a working page.",
- ),
- ),
- )
- result = await StudioFinalShapeVerifier(
- SCOPE,
- build_id="build-1",
- workspace_root=tmp_path,
- store=SimpleNamespace(load=lambda *_: state),
- browser=Browser(),
- ).verify(request("Build a working page.", "Done.").model_copy(update={"contract": contract}))
- assert result.report is not None
- assert result.report.items[0].status == "not_run"
-
-
-@pytest.mark.asyncio
-async def test_final_browser_check_rejects_unrechecked_interaction_failure(tmp_path):
- (tmp_path / "index.html").write_text("")
-
- class Browser:
- async def verify_page(self, **_kwargs):
- return SimpleNamespace(
- status="ok",
- status_code=200,
- controls=(),
- page_errors=(),
- console=(),
- network_failures=(),
- screenshot=None,
- )
-
- issue = {
- "tool_name": "browser_inspect_workspace",
- "entry_path": "index.html",
- "tool_call": 7,
- "error": "uncaught TypeError after Start",
- "evidence_ref": "sha256:" + "c" * 64,
- }
- store = SimpleNamespace(
- load=lambda *_: SimpleNamespace(
- messages=(),
- workspace_modified_paths=("index.html",),
- unresolved_interaction_observation=issue,
- )
- )
- browser_request = request("Build a working page.", "Done.").model_copy(
- update={
- "contract": TaskContract(
- revision="goal-v1",
- items=(
- AcceptanceItem(
- acceptance_id="current_user_goal",
- verifier_ref=BROWSER_VERIFIER_REF,
- verifier_version=BROWSER_VERIFIER_VERSION,
- verification_method="deterministic",
- description="Build a working page.",
- ),
- ),
- ),
- }
- )
- result = await StudioFinalShapeVerifier(
- SCOPE, build_id="build-1", workspace_root=tmp_path, store=store, browser=Browser()
- ).verify(browser_request)
- assert result.report is not None
- assert result.report.items[0].status == "failed"
- assert result.report.items[0].evidence_refs == (issue["evidence_ref"],)
- assert "successfully rechecked" in result.report.items[0].safe_summary
-
-
-@pytest.mark.asyncio
-async def test_final_web_delivery_requires_current_run_browser_observation(tmp_path):
- (tmp_path / "index.html").write_text("ready
")
-
- class Browser:
- async def verify_page(self, **_kwargs):
- return SimpleNamespace(
- status="ok",
- status_code=200,
- controls=(),
- page_errors=(),
- console=(),
- network_failures=(),
- screenshot=None,
- )
-
- state = SimpleNamespace(
- messages=(),
- workspace_modified_paths=("index.html",),
- unresolved_interaction_observation=None,
- last_web_mutation_tool_call=4,
- last_browser_observation=None,
- )
- store = SimpleNamespace(load=lambda *_: state)
- browser_request = request("Build a working page.", "Done.").model_copy(
- update={
- "contract": TaskContract(
- revision="goal-v1",
- items=(
- AcceptanceItem(
- acceptance_id="current_user_goal",
- verifier_ref=BROWSER_VERIFIER_REF,
- verifier_version=BROWSER_VERIFIER_VERSION,
- verification_method="deterministic",
- description="Build a working page.",
- ),
- ),
- ),
- }
- )
- verifier = StudioFinalShapeVerifier(
- SCOPE, build_id="build-1", workspace_root=tmp_path, store=store, browser=Browser()
- )
- missing = await verifier.verify(browser_request)
- assert missing.report is not None
- assert missing.report.items[0].status == "failed"
- assert "browser tool" in missing.report.items[0].safe_summary
- state.last_browser_observation = {"entry_path": "index.html", "tool_call": 3}
- stale = await verifier.verify(browser_request)
- assert stale.report is not None and stale.report.items[0].status == "failed"
- state.last_browser_observation = {"entry_path": "index.html", "tool_call": 5}
- current = await verifier.verify(browser_request)
- assert current.report is not None and current.report.items[0].status == "not_run"
- state.last_browser_observation = {"entry_path": "autotest.html", "tool_call": 5}
- checkpoint = await verifier.verify(
- browser_request.model_copy(update={"purpose": "checkpoint", "final_text": ""})
- )
- assert checkpoint.report is not None
- assert checkpoint.report.items[0].status == "failed"
- assert "delivered web page" in checkpoint.report.items[0].safe_summary
- state.last_browser_observation = {"entry_path": "index.html", "tool_call": 5}
- visual_verifier = StudioFinalShapeVerifier(
- SCOPE,
- build_id="build-1",
- workspace_root=tmp_path,
- store=store,
- browser=Browser(),
- require_visual_feedback=True,
- )
- missing_visual = await visual_verifier.verify(browser_request)
- assert missing_visual.report is not None
- assert missing_visual.report.items[0].status == "failed"
- assert "visual-model description" in missing_visual.report.items[0].safe_summary
- state.last_browser_observation["vision_description_status"] = "available"
- visual_observed = await visual_verifier.verify(browser_request)
- assert visual_observed.report is not None
- assert visual_observed.report.items[0].status == "not_run"
-
-
-def request(goal: str, answer: str) -> VerificationRequest:
- return VerificationRequest(
- scope=SCOPE,
- run_id="run",
- candidate_id="candidate",
- final_text=answer,
- contract=TaskContract(
- revision="goal-v1",
- items=(
- AcceptanceItem(
- acceptance_id="current_user_goal",
- verifier_ref=VERIFIER_REF,
- verifier_version=VERIFIER_VERSION,
- verification_method="deterministic",
- description=goal,
- ),
- ),
- ),
- subject_context_digest="sha256:" + "a" * 64,
- )
-
-
-def test_shape_recognition_is_narrow_and_does_not_infer_answer_values():
- assert requested_final_shape("Read the file. Return only the total.") == "number"
- assert (
- requested_final_shape(
- "Read the bound Skill instructions, then return only the instruction sentence "
- "from SKILL.md."
- )
- == "sentence"
- )
- assert requested_final_shape("Return the result with a short explanation.") is None
- assert requested_final_shape("Return only the total and explain it.") is None
- assert requested_final_shape("Return only the sentence and explain it.") is None
- assert requested_final_shape("Read the canvas. Reply with only those digits.") == "digits"
- assert requested_final_shape("计算 37 × 24,只回复数字。") == "number"
- assert (
- requested_final_shape('从 JSON {"ok":true} 提取 ok,只回复 JSON 布尔值。') == "json_boolean"
- )
- assert requested_final_shape("解释 JSON 布尔值的用法。") is None
- assert requested_final_shape("2024 年是闰年吗?只回复 是 或 否。") == ("是", "否")
- assert requested_final_shape("选择方案,只输出 左 或 右。") == ("左", "右")
- assert requested_final_shape("只回复 是 或 否,并解释原因。") is None
-
-
-@pytest.mark.parametrize(
- "goal,shape",
- [
- ("Read the sources. Return only a JSON object.", "json_object"),
- ("Read the sources. Reply with only a JSON array.", "json_array"),
- ("最后只返回 JSON 对象,键为 incidents 和 total_cents。不能修改文件。", "json_object"),
- ("仅输出 JSON 数组。", "json_array"),
- ('最后只返回 JSON 对象,格式为 {"records":数组,"count":整数}。', "json_object"),
- ('仅输出 JSON 数组,格式是 [{"label":字符串}]。', "json_array"),
- ],
-)
-def test_structured_json_shape_is_an_explicit_output_clause(goal, shape):
- assert requested_final_shape(goal) == shape
- assert requested_final_shape("解释‘只返回 JSON 对象’这句话。") is None
- assert requested_final_shape("不要只返回 JSON 对象。") is None
- assert requested_final_shape("最后只返回 JSON 对象并解释原因。") is None
- assert requested_final_shape('解释“只返回 JSON 对象,格式为 {"x":1}”这句话。') is None
- assert requested_final_shape('不要只返回 JSON 对象,格式为 {"x":1}。') is None
- assert requested_final_shape('只返回 JSON 对象,格式为 {"x":1},再解释原因。') is None
- assert requested_final_shape('只返回 JSON 对象,格式为 [{"x":1}]。') is None
- assert requested_final_shape('只返回 JSON 数组,格式为 {"x":1}。') is None
-
-
-@pytest.mark.asyncio
-async def test_json_shape_rejects_prose_and_fences_but_does_not_verify_semantics():
- verifier = StudioFinalShapeVerifier(SCOPE, build_id="build")
- goal = "最后只返回 JSON 对象,键为 incidents 和 total_cents。不能修改文件。"
- for bad in (
- 'Here is the result: {"total_cents": 73}',
- '```json\n{"total_cents":73}\n```',
- '[{"total_cents":73}]',
- '{"total_cents":NaN}',
- ):
- result = await verifier.verify(request(goal, bad))
- assert result.report.items[0].status == "failed"
- result = await verifier.verify(request(goal, '{"total_cents":999}'))
- assert result.report.items[0].status == "not_run"
- # JSON shape alone proves no sum, citation, key completeness or user goal.
- assert "semantic" in result.report.items[0].safe_summary.lower()
-
-
-@pytest.mark.asyncio
-async def test_long_goal_keeps_an_explicit_json_clause_before_source_instructions():
- goal = (
- "最后只返回 JSON 对象,键为 incidents 和 total_cents。" + "必须保留准确的来源引用。" * 150
- )
- contract = _goal_contract(
- TaskContractInput(
- goal=goal,
- session_id="session",
- parent_run_id=None,
- parent_goal=None,
- parent_contract=None,
- )
- )
- assert len(contract.items[0].description) <= 1024
- assert requested_final_shape(contract.items[0].description) == "json_object"
- result = await StudioFinalShapeVerifier(SCOPE, build_id="build").verify(
- request(goal, '```json\n{"total_cents":73}\n```').model_copy(update={"contract": contract})
- )
- assert result.report.items[0].status == "failed"
-
-
-@pytest.mark.asyncio
-async def test_long_goal_keeps_its_final_shape_clause_in_the_pinned_contract():
- goal = "Inspect the files. " + ("Context details. " * 100) + "Return only the total."
- contract = _goal_contract(
- TaskContractInput(
- goal=goal,
- session_id="session",
- parent_run_id=None,
- parent_goal=None,
- parent_contract=None,
- )
- )
- assert len(contract.items[0].description) == 1024
- assert contract.items[0].description.endswith("Return only the total.")
- verifier = StudioFinalShapeVerifier(SCOPE, build_id="build-1")
- bad = await verifier.verify(
- request(goal, "The total is 42").model_copy(update={"contract": contract})
- )
- assert bad.report is not None
- assert bad.report.items[0].status == "failed"
-
-
-@pytest.mark.asyncio
-async def test_numeric_shape_failure_repairs_but_shape_success_is_unverified():
- verifier = StudioFinalShapeVerifier(SCOPE, build_id="build-1")
- bad = await verifier.verify(request("Return only the total.", "19 + 23 = 42"))
- assert bad.report.items[0].status == "failed"
- assert "42" not in bad.report.items[0].safe_summary
- assert (
- reduce_completion(
- request("Return only the total.", "19 + 23 = 42").contract, bad.candidate, bad.report
- ).action
- == "repair"
- )
-
- good_request = request("Return only the total.", "42")
- good = await verifier.verify(good_request)
- assert good.report.items[0].status == "not_run"
- decision = reduce_completion(good_request.contract, good.candidate, good.report)
- assert decision.action == "finalize" and decision.outcome == "unverified"
-
-
-@pytest.mark.asyncio
-async def test_exact_digits_shape_rejects_preamble_without_claiming_visual_truth():
- verifier = StudioFinalShapeVerifier(SCOPE, build_id="build-1")
- goal = "Read the canvas. Reply with only those digits."
- bad = await verifier.verify(request(goal, "The four digits are: 6428"))
- assert bad.report is not None
- assert bad.report.items[0].status == "failed"
- good = await verifier.verify(request(goal, "6428"))
- assert good.report.items[0].status == "not_run"
-
-
-@pytest.mark.asyncio
-async def test_explicit_chinese_json_boolean_rejects_markdown_without_claiming_truth():
- verifier = StudioFinalShapeVerifier(SCOPE, build_id="build-1")
- goal = '从 JSON {"ok":true} 提取 ok,只回复 JSON 布尔值。'
- for bad_text in ("`true`", "```json\ntrue\n```", "The answer is true"):
- bad = await verifier.verify(request(goal, bad_text))
- assert bad.report is not None
- assert bad.report.items[0].status == "failed"
- assert (
- reduce_completion(request(goal, bad_text).contract, bad.candidate, bad.report).action
- == "repair"
- )
- good = await verifier.verify(request(goal, "true"))
- assert good.report is not None
- assert good.report.items[0].status == "not_run"
- decision = reduce_completion(request(goal, "true").contract, good.candidate, good.report)
- assert decision.action == "finalize" and decision.outcome == "unverified"
-
-
-@pytest.mark.asyncio
-async def test_explicit_two_choice_final_rejects_punctuation_without_claiming_truth():
- verifier = StudioFinalShapeVerifier(SCOPE, build_id="build-1")
- goal = "2024 年是闰年吗?只回复 是 或 否。"
- bad_request = request(goal, "是。")
- bad = await verifier.verify(bad_request)
- assert bad.report is not None
- assert bad.report.items[0].status == "failed"
- assert reduce_completion(bad_request.contract, bad.candidate, bad.report).action == "repair"
- good_request = request(goal, "是")
- good = await verifier.verify(good_request)
- assert good.report is not None
- assert good.report.items[0].status == "not_run"
- assert (
- reduce_completion(good_request.contract, good.candidate, good.report).outcome
- == "unverified"
- )
-
-
-@pytest.mark.asyncio
-async def test_sentence_shape_rejects_preamble_and_unknown_goal_remains_unverified():
- verifier = StudioFinalShapeVerifier(SCOPE, build_id="build-1")
- goal = "Return only the instruction sentence from SKILL.md."
- bad = await verifier.verify(request(goal, "The sentence is:\n\n> Be concise."))
- assert bad.report.items[0].status == "failed"
- good = await verifier.verify(request(goal, "Be concise."))
- assert good.report.items[0].status == "not_run"
- unknown = await verifier.verify(request("Explain the Skill.", "Explanation"))
- assert unknown.report is None
- with pytest.raises(ValueError, match="scope_mismatch"):
- await verifier.verify(
- request(goal, "Be concise.").model_copy(
- update={"scope": SCOPE.model_copy(update={"tenant_id": "other"})}
- )
- )
-
-
-@pytest.mark.asyncio
-async def test_exact_workspace_file_is_observed_by_host_and_repairs_mismatch(tmp_path):
- goal = '在工作区创建 baseline/config.json,内容恰好是 {"enabled":true}。完成后回复路径。'
- requirement = requested_exact_workspace_file(goal)
- assert requirement is not None
- assert requirement.relative_path == "baseline/config.json"
- assert requirement.content == '{"enabled":true}'
- assert (
- requested_exact_workspace_file("在工作区创建 ../outside.json,内容恰好是 secret。") is None
- )
- assert requested_exact_workspace_file("请写一个 JSON 文件。") is None
- assert (
- requested_exact_workspace_file(
- '不要在工作区创建 baseline/config.json,内容恰好是 {"enabled":true}。'
- )
- is None
- )
-
- contract = _goal_contract(
- TaskContractInput(
- goal=goal,
- session_id="session",
- parent_run_id=None,
- parent_goal=None,
- parent_contract=None,
- )
- )
- assert [item.acceptance_id for item in contract.items] == [
- "current_user_goal",
- "exact_workspace_file",
- ]
- verifier = StudioFinalShapeVerifier(SCOPE, build_id="build-1", workspace_root=tmp_path)
- candidate_request = request(goal, "baseline/config.json").model_copy(
- update={"contract": contract}
- )
- path = tmp_path / "baseline" / "config.json"
- path.parent.mkdir()
- path.write_text('{"enabled": true}')
- mismatch = await verifier.verify(candidate_request)
- assert mismatch.report is not None
- assert [item.status for item in mismatch.report.items] == ["failed", "failed"]
- assert "UTF-8 hex" in mismatch.report.items[1].safe_summary
- assert reduce_completion(contract, mismatch.candidate, mismatch.report).action == "repair"
-
- path.write_text('{"enabled":true}')
- match = await verifier.verify(candidate_request)
- assert match.report is not None
- assert [item.status for item in match.report.items] == ["not_run", "passed"]
- decision = reduce_completion(contract, match.candidate, match.report)
- assert (decision.action, decision.outcome) == ("finalize", "partial")
-
-
-@pytest.mark.asyncio
-async def test_exact_workspace_file_cannot_follow_symlink_outside_workspace(tmp_path):
- root = tmp_path / "workspace"
- root.mkdir()
- outside = tmp_path / "outside"
- outside.mkdir()
- (outside / "config.json").write_text('{"enabled":true}')
- (root / "baseline").symlink_to(outside, target_is_directory=True)
- goal = '在工作区创建 baseline/config.json,内容恰好是 {"enabled":true}。'
- contract = _goal_contract(
- TaskContractInput(
- goal=goal,
- session_id="session",
- parent_run_id=None,
- parent_goal=None,
- parent_contract=None,
- )
- )
- verifier = StudioFinalShapeVerifier(SCOPE, build_id="build-1", workspace_root=root)
- observed = await verifier.verify(
- request(goal, "done").model_copy(update={"contract": contract})
- )
- assert observed.report is not None
- assert [item.status for item in observed.report.items] == ["failed", "failed"]
diff --git a/tests/studio/test_native_model_port.py b/tests/studio/test_native_model_port.py
deleted file mode 100644
index b8f50e1f2..000000000
--- a/tests/studio/test_native_model_port.py
+++ /dev/null
@@ -1,774 +0,0 @@
-"""Studio ModelGateway -> Native sealed model-result projection."""
-
-from __future__ import annotations
-
-import pytest
-
-from ksadk.harness.native.model import ModelProfile
-from ksadk.harness.native.ports import ModelRequest, ToolDefinition
-from ksadk.harness.native.state import RunScope
-from ksadk.model_gateway.events import ModelStreamEvent, ModelStreamEventType
-from ksadk.studio.contracts import (
- ModelParameters,
- NetworkPolicy,
- ResolvedModel,
- SecuritySpec,
- Usage,
-)
-from ksadk.studio.errors import StudioError
-from ksadk.studio.model_client import ModelResponse, ToolCall
-from ksadk.studio.native_model_port import (
- StudioNativeModelPort,
- native_model_profile_from_build,
- native_studio_streaming_support,
-)
-
-SCOPE = RunScope(tenant_id="tenant", workspace_id="workspace", user_id="user", agent_id="agent")
-MODEL = ResolvedModel(
- provider="openai-compatible",
- model="fixture",
- endpoint_url="https://example.test/v1/chat/completions",
- credential_ref="env://FIXTURE_KEY",
- parameters=ModelParameters(max_tokens=512),
-)
-NETWORK = NetworkPolicy(allowed_hosts=["example.test"])
-TOOL = ToolDefinition(
- name="read_value",
- description="Read a value",
- parameters={"type": "object", "properties": {}, "additionalProperties": False},
-)
-
-
-def request(*, streaming=False, tools=()):
- profile = ModelProfile(
- profile_id="fixture",
- profile_version="1",
- provider_family="openai-compatible",
- context_window=4096,
- max_output_tokens=512,
- streaming=streaming,
- )
- return ModelRequest(
- scope=SCOPE,
- run_id="run",
- request_id="request",
- attempt_id="attempt",
- profile=profile,
- instructions="Do the fixture.",
- messages=({"role": "user", "content": "Read the value."},),
- tools=tools,
- )
-
-
-class Client:
- def __init__(self, *, response=None, error=None, events=()):
- self.response, self.error, self.events = response, error, events
- self.calls = []
-
- async def complete(self, model, **kwargs):
- self.calls.append((model, kwargs))
- if self.error is not None:
- raise self.error
- return self.response
-
- async def stream_events(self, model, **kwargs):
- self.calls.append((model, kwargs))
- for event in self.events:
- yield event
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize("terminal", ["completed", "failed", "consumer_close"])
-async def test_native_stream_joins_gateway_iterator_before_returning(terminal):
- class OwnedStreamClient(Client):
- closed = False
-
- async def stream_events(self, model, **kwargs):
- try:
- yield ModelStreamEvent(
- ModelStreamEventType.TEXT_DELTA, model.model, 1, text="partial"
- )
- if terminal == "failed":
- yield ModelStreamEvent(
- ModelStreamEventType.TURN_FAILED, model.model, 2,
- failure_category="malformed_tool_call",
- gateway_error_code="MODEL_TOOL_PROTOCOL_INVALID",
- )
- else:
- yield ModelStreamEvent(
- ModelStreamEventType.TURN_COMPLETED, model.model, 2,
- metadata={"finish_reason": "stop"},
- )
- finally:
- self.closed = True
-
- client = OwnedStreamClient()
- input_request = request(streaming=True)
- iterator = port(client, input_request).stream(input_request)
- if terminal == "consumer_close":
- assert (await anext(iterator)).kind == "text_delta"
- await iterator.aclose()
- else:
- events = [event async for event in iterator]
- assert events[-1].kind == "final"
- assert client.closed, "The model effect still owns an unclosed Gateway iterator"
-
-
-def port(client, input_request, *, model=MODEL):
- return StudioNativeModelPort(
- client,
- scope=SCOPE,
- model=model,
- network_policy=NETWORK,
- profile_digest=input_request.profile.digest,
- )
-
-
-def resolved_build(*, agent_id="agent", models=(MODEL,)):
- return {
- "agentId": agent_id,
- "model": models[0].model_dump(by_alias=True),
- "fallbackModels": [model.model_dump(by_alias=True) for model in models[1:]],
- "security": SecuritySpec(network=NETWORK).model_dump(by_alias=True),
- }
-
-
-@pytest.mark.parametrize("policy", [None, "idle/v1"])
-def test_stream_timeout_policy_is_locked_by_build_and_omitted_on_legacy_profiles(policy):
- build = resolved_build()
- build["context"] = {"maxInputTokens": 8192, "reserveOutputTokens": 1024}
- build["execution"] = {"nativeStreamTimeoutPolicy": policy} if policy else {}
- profile = native_model_profile_from_build(
- build, selected_model="fixture", build_id="build", streaming_support=lambda _: True,
- )
- assert profile.stream_timeout_policy == policy
- assert ("stream_timeout_policy" in profile.model_dump(mode="json")) is (policy is not None)
- buffered = native_model_profile_from_build(
- build, selected_model="fixture", build_id="build", streaming_support=lambda _: False,
- )
- assert buffered.stream_timeout_policy is None
-
-
-@pytest.mark.asyncio
-async def test_gateway_activity_is_content_free_and_does_not_replace_visible_deltas():
- input_request = request(streaming=True)
- input_request = input_request.model_copy(update={
- "profile": input_request.profile.model_copy(update={"stream_timeout_policy": "idle/v1"}),
- })
- client = Client(events=(
- ModelStreamEvent(ModelStreamEventType.TEXT_DELTA, MODEL.model, 1, text="answer"),
- ModelStreamEvent(
- ModelStreamEventType.TURN_COMPLETED, MODEL.model, 2,
- metadata={"finish_reason": "stop"},
- ),
- ))
- events = [event async for event in port(client, input_request).stream(input_request)]
- assert [event.kind for event in events] == ["activity", "text_delta", "activity", "final"]
- assert [event.seq for event in events] == [1, 2, 3, 4]
- assert all(not event.text and event.result is None for event in events if event.kind == "activity")
- assert events[-1].result.text == "answer"
-
-
-def test_native_profile_uses_only_locked_build_budgets():
- build = resolved_build()
- build["context"] = {"maxInputTokens": 8192, "reserveOutputTokens": 1024}
- build["execution"] = {
- "retry": {"maxAttempts": 3, "providerMaxAttempts": 5, "backoffSeconds": 1.5}
- }
- profile = native_model_profile_from_build(build, selected_model="fixture", build_id="build-123")
- assert len(profile.profile_version) == 24
- assert profile.profile_id.startswith("studio-")
- assert profile.context_window == 8192
- assert profile.max_output_tokens == 512
- assert profile.max_retries == 2
- assert profile.max_provider_retries == 4
- assert profile.retry_initial_delay_seconds == 1.5
- assert profile.image_input_mode == "text_only"
-
- narrowed = dict(build)
- narrowed["model"] = MODEL.model_copy(
- update={"metadata": {"context_window_tokens": 4096}}
- ).model_dump(by_alias=True)
- assert (
- native_model_profile_from_build(
- narrowed, selected_model="fixture", build_id="build-123"
- ).context_window
- == 4096
- )
-
- vision = dict(build)
- vision["model"] = MODEL.model_copy(
- update={"metadata": {"supports_image_input": True}}
- ).model_dump(by_alias=True)
- assert (
- native_model_profile_from_build(
- vision, selected_model="fixture", build_id="build-123"
- ).image_input_mode
- == "native"
- )
-
- slow = dict(build)
- slow["model"] = MODEL.model_copy(
- update={"metadata": {"request_timeout_seconds": 240}}
- ).model_dump(by_alias=True)
- assert (
- native_model_profile_from_build(
- slow, selected_model="fixture", build_id="build-123"
- ).request_timeout_seconds
- == 240
- )
- slow["execution"] = {"timeoutSeconds": 250}
- with pytest.raises(ValueError, match="request_timeout_invalid"):
- native_model_profile_from_build(slow, selected_model="fixture", build_id="build-123")
-
-
-@pytest.mark.parametrize("timeout,valid", [(0, True), (250, False), (300, True)])
-def test_unbounded_run_keeps_the_independent_model_request_deadline(timeout, valid):
- build = resolved_build(models=(MODEL.model_copy(update={
- "metadata": {"request_timeout_seconds": 240},
- }),))
- build["context"] = {"maxInputTokens": 8192, "reserveOutputTokens": 1024}
- build["execution"] = {"timeoutSeconds": timeout}
- if valid:
- profile = native_model_profile_from_build(
- build, selected_model="fixture", build_id="build-timeouts",
- )
- assert profile.request_timeout_seconds == 240
- else:
- with pytest.raises(ValueError, match="request_timeout_invalid"):
- native_model_profile_from_build(
- build, selected_model="fixture", build_id="build-timeouts",
- )
-
-
-def test_native_profile_pins_explicit_studio_reasoning_effort():
- build = resolved_build()
- build["context"] = {"maxInputTokens": 8192, "reserveOutputTokens": 1024}
- build["execution"] = {}
- automatic = native_model_profile_from_build(
- build, selected_model="fixture", build_id="build-123"
- )
- selected = native_model_profile_from_build(
- build, selected_model="fixture", build_id="build-123", reasoning_effort="low"
- )
- assert automatic.reasoning_effort is None
- assert selected.reasoning_effort == "low"
- assert selected.digest != automatic.digest
- with pytest.raises(ValueError, match="reasoning_effort_invalid"):
- native_model_profile_from_build(
- build, selected_model="fixture", build_id="build-123", reasoning_effort="unsupported"
- )
-
-
-def test_vision_role_selects_only_the_locked_vision_model_even_with_same_model_name():
- vision = MODEL.model_copy(update={"metadata": {"supports_image_input": True}})
- build = resolved_build()
- build["visionModel"] = vision.model_dump(by_alias=True)
- build["context"] = {"maxInputTokens": 8192, "reserveOutputTokens": 1024}
- build["execution"] = {}
- agent_profile = native_model_profile_from_build(
- build, selected_model="fixture", build_id="build-123"
- )
- vision_profile = native_model_profile_from_build(
- build, selected_model="fixture", build_id="build-123", model_role="vision"
- )
- assert agent_profile.image_input_mode == "text_only"
- assert vision_profile.image_input_mode == "native"
- assert agent_profile.digest != vision_profile.digest
- bound = StudioNativeModelPort.from_resolved_build(
- Client(),
- scope=SCOPE,
- resolved_agent_spec=build,
- selected_model="fixture",
- profile_digest=vision_profile.digest,
- model_role="vision",
- )
- assert bound._model.metadata["supports_image_input"] is True
-
-
-def test_native_profile_uses_studio_gateway_streaming_decision(monkeypatch):
- class Gateway(Client):
- def supports_streaming(self, model, *, requested):
- assert model.model == "fixture"
- self.requested = requested
- return requested
-
- gateway = Gateway()
- build = resolved_build()
- build["context"] = {"maxInputTokens": 8192, "reserveOutputTokens": 1024}
- build["execution"] = {}
- profile = native_model_profile_from_build(
- build,
- selected_model="fixture",
- build_id="build-123",
- streaming_support=lambda model: native_studio_streaming_support(gateway, model),
- )
- assert gateway.requested is True
- assert profile.streaming is True
- assert (
- profile.digest
- != native_model_profile_from_build(
- build, selected_model="fixture", build_id="build-123"
- ).digest
- )
-
- monkeypatch.setattr(
- "ksadk.studio.native_model_port.provider_compat.prefer_buffered_transport",
- lambda **_kwargs: True,
- )
- assert native_studio_streaming_support(gateway, MODEL) is False
- assert gateway.requested is False
- assert native_studio_streaming_support(Client(), MODEL) is False
-
-
-def test_native_profile_rejects_missing_or_conflicting_build_budgets():
- build = resolved_build()
- with pytest.raises(ValueError, match="budget_unavailable"):
- native_model_profile_from_build(build, selected_model="fixture", build_id="build-123")
- build["context"] = {"maxInputTokens": 1024, "reserveOutputTokens": 512}
- build["execution"] = {}
- build["model"] = MODEL.model_copy(
- update={"parameters": ModelParameters(max_tokens=2048)}
- ).model_dump(by_alias=True)
- with pytest.raises(ValueError, match="budget_conflict"):
- native_model_profile_from_build(build, selected_model="fixture", build_id="build-123")
-
-
-def response(*, text="answer", finish="stop", calls=(), reported=True):
- return ModelResponse(
- content=text,
- finish_reason=finish,
- usage=Usage(input_tokens=10, output_tokens=3, total_tokens=13, reported=reported),
- tool_calls=list(calls),
- raw_message={},
- )
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize("image_mode", ["native", "text_only"])
-async def test_studio_gateway_projects_host_image_after_complete_tool_batch(image_mode):
- base = request()
- image = {"type": "image_url", "image_url": {"url": "data:image/png;base64,ZmFrZQ=="}}
- observed = base.model_copy(
- update={
- "profile": base.profile.model_copy(update={"image_input_mode": image_mode}),
- "messages": (
- {"role": "user", "content": "Inspect the screenshot."},
- {
- "role": "assistant",
- "content": None,
- "tool_calls": [
- {
- "id": "capture-1",
- "type": "function",
- "function": {"name": "capture", "arguments": "{}"},
- }
- ],
- },
- {
- "role": "tool",
- "tool_call_id": "capture-1",
- "content": [
- {"type": "text", "text": '{"status":"ok"}'},
- image,
- ],
- },
- ),
- }
- )
- client = Client(response=response())
- await port(client, observed).complete(observed)
- messages = client.calls[0][1]["messages"]
- if image_mode == "native":
- assert messages[-2]["role"] == "tool"
- assert isinstance(messages[-2]["content"], str)
- assert messages[-1]["role"] == "user"
- assert messages[-1]["content"][1]["image_url"]["url"] == image["image_url"]["url"]
- else:
- assert len(messages) == 4
- assert messages[-1]["role"] == "tool"
- assert "image content is unavailable" in messages[-1]["content"]
-
-
-@pytest.mark.asyncio
-async def test_studio_native_model_port_applies_host_output_limit():
- base = request()
- capped = base.model_copy(update={"max_output_tokens": 64})
- client = Client(response=response())
- result = await port(client, base).complete(capped)
- assert result.response_kind == "final_candidate"
- assert client.calls[0][1]["max_output_tokens"] == 64
- with pytest.raises(ValueError, match="exceeds pinned profile"):
- ModelRequest.model_validate({**base.model_dump(mode="json"), "max_output_tokens": 513})
-
-
-@pytest.mark.asyncio
-async def test_studio_native_model_port_preserves_length_and_usage():
- input_request = request()
- client = Client(response=response(text="partial", finish="length"))
- result = await port(client, input_request).complete(input_request)
- assert result.response_kind == "output_limit"
- assert result.text == "partial"
- assert result.usage.input_tokens == 10
- assert client.calls[0][1]["max_attempts"] == 1
- assert client.calls[0][1]["retry_on_length"] is False
- assert client.calls[0][1]["retry_reasoning_only"] is False
- assert client.calls[0][1]["messages"][0] == {
- "role": "system",
- "content": "Do the fixture.",
- }
-
-
-@pytest.mark.asyncio
-async def test_studio_native_glm_buffered_content_cannot_expose_inline_reasoning():
- input_request = request()
- glm = MODEL.model_copy(update={"model": "glm-5.3-flash"})
- client = Client(response=response(text="The screenshot shows 6428.6428"))
- result = await port(client, input_request, model=glm).complete(input_request)
- assert result.response_kind == "final_candidate"
- assert result.text == "6428"
- other = await port(client, input_request).complete(input_request)
- assert other.text == "The screenshot shows 6428.6428"
-
-
-@pytest.mark.asyncio
-async def test_studio_native_glm_stream_never_exposes_inline_reasoning_delta():
- input_request = request(streaming=True)
- glm = MODEL.model_copy(update={"model": "glm-5.3-flash"})
- client = Client(
- events=(
- ModelStreamEvent(
- ModelStreamEventType.TEXT_DELTA,
- glm.model,
- 1,
- text="The screenshot shows 6428.64"),
- ModelStreamEvent(ModelStreamEventType.TEXT_DELTA, glm.model, 3, text="28"),
- ModelStreamEvent(
- ModelStreamEventType.TURN_COMPLETED,
- glm.model,
- 4,
- metadata={"finish_reason": "stop"},
- ),
- )
- )
- events = [event async for event in port(client, input_request, model=glm).stream(input_request)]
- assert [(event.kind, event.text) for event in events[:-1]] == [
- ("text_delta", "64"),
- ("text_delta", "28"),
- ]
- assert events[-1].result.response_kind == "final_candidate"
- assert events[-1].result.text == "6428"
-
-
-@pytest.mark.asyncio
-async def test_studio_native_model_port_does_not_complete_without_finish_reason():
- input_request = request()
- client = Client(response=response(text="partial", finish=""))
- result = await port(client, input_request).complete(input_request)
- assert result.response_kind == "provider_retryable_error"
- assert result.failure_kind == "incomplete_response"
- assert result.text == "partial"
-
-
-@pytest.mark.asyncio
-async def test_studio_native_model_port_seals_bad_arguments_for_safe_tool_receipt():
- input_request = request(tools=(TOOL,))
- good = Client(
- response=response(
- text="",
- finish="tool_calls",
- calls=(ToolCall(id="call-1", name="read_value", arguments='{"value": 7}'),),
- )
- )
- result = await port(good, input_request).complete(input_request)
- assert result.response_kind == "tool_calls"
- assert result.tool_calls[0].arguments == {"value": 7}
- assert good.calls[0][1]["tools"][0]["function"]["name"] == "read_value"
-
- bad = Client(
- response=response(
- text="",
- finish="tool_calls",
- calls=(ToolCall(id="call-1", name="read_value", arguments='{"x":1,"x":2}'),),
- )
- )
- malformed = await port(bad, input_request).complete(input_request)
- assert malformed.response_kind == "tool_calls"
- assert malformed.tool_calls[0].call_id == "call-1"
- assert malformed.tool_calls[0].arguments == {}
- assert malformed.tool_calls[0].wire_arguments_invalid is True
-
-
-@pytest.mark.asyncio
-async def test_studio_native_model_port_classifies_gateway_empty_length_and_rate_limit():
- input_request = request()
- length = Client(
- error=StudioError(
- "MODEL_EMPTY_RESPONSE",
- "empty",
- status_code=502,
- details={"finishReason": "length"},
- )
- )
- assert (await port(length, input_request).complete(input_request)).response_kind == (
- "output_limit"
- )
- rate_limit = Client(error=StudioError("MODEL_RATE_LIMITED", "limited", status_code=429))
- limited = await port(rate_limit, input_request).complete(input_request)
- assert limited.response_kind == "provider_retryable_error"
- assert limited.failure_kind == "rate_limit"
- assert limited.provider_failure_category == "rate_limit"
- assert limited.provider_status_code == 429
- invalid = Client(error=StudioError("MODEL_REQUEST_INVALID", "bad request", status_code=400))
- rejected = await port(invalid, input_request).complete(input_request)
- assert rejected.failure_kind == "client_error"
- assert rejected.provider_failure_category == "invalid_request"
- assert rejected.provider_status_code == 400
- assert rejected.gateway_error_code == "MODEL_REQUEST_INVALID"
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize(
- ("code", "metadata", "expected_kind"),
- [
- ("MODEL_TOOL_PROTOCOL_INVALID", {}, "malformed_tool_call"),
- ("MODEL_EMPTY_RESPONSE", {"finish_reason": "length"}, "output_limit"),
- ("MODEL_EMPTY_RESPONSE", {}, "empty_response"),
- ("MODEL_EMPTY_RESPONSE", {"finish_reason": []}, "empty_response"),
- ("MODEL_RESPONSE_INVALID", {}, "provider_terminal_error"),
- ("MODEL_REQUEST_INVALID", {}, "provider_terminal_error"),
- ],
-)
-async def test_streamed_host_error_matches_buffered_projection(code, metadata, expected_kind):
- input_request = request(streaming=True)
- client = Client(
- events=(
- ModelStreamEvent(
- ModelStreamEventType.TURN_FAILED,
- "fixture",
- 1,
- failure_category="invalid_request",
- gateway_error_code=code,
- status_code=422,
- metadata=metadata,
- ),
- )
- )
- events = [event async for event in port(client, input_request).stream(input_request)]
- result = events[-1].result
- assert result.response_kind == expected_kind
- assert result.gateway_error_code == code
- assert result.provider_status_code == 422
- assert result.tool_calls == ()
- assert result.failure_kind == {
- "MODEL_RESPONSE_INVALID": "invalid_response",
- "MODEL_REQUEST_INVALID": "client_error",
- }.get(code)
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize(
- ("category", "failure_kind"),
- [
- ("timeout", "request_timeout"),
- ("unavailable", "server_error"),
- ("transport", "network_error"),
- ("invalid_request", "client_error"),
- ("unknown", "unknown_error"),
- ("future_gateway_category", "unknown_error"),
- ],
-)
-async def test_studio_native_model_port_projects_safe_gateway_failure_kind(category, failure_kind):
- input_request = request(streaming=True)
- client = Client(
- events=(
- ModelStreamEvent(
- ModelStreamEventType.TURN_FAILED,
- "fixture",
- 1,
- failure_category=category,
- gateway_error_code="MODEL_REQUEST_FAILED" if category == "invalid_request" else "",
- status_code=400 if category == "invalid_request" else None,
- ),
- )
- )
- events = [event async for event in port(client, input_request).stream(input_request)]
- assert events[-1].result.failure_kind == failure_kind
- assert events[-1].result.provider_failure_category == category
- if category == "invalid_request":
- assert events[-1].result.provider_status_code == 400
- assert events[-1].result.gateway_error_code == "MODEL_REQUEST_FAILED"
- assert events[-1].result.response_kind == (
- "provider_retryable_error"
- if category in {"timeout", "unavailable", "transport"}
- else "provider_terminal_error"
- )
-
-
-@pytest.mark.asyncio
-async def test_studio_native_model_port_streams_text_then_seals_tool_and_usage():
- input_request = request(streaming=True, tools=(TOOL,))
- client = Client(
- events=(
- ModelStreamEvent(ModelStreamEventType.TURN_STARTED, "fixture", 1),
- ModelStreamEvent(ModelStreamEventType.TEXT_DELTA, "fixture", 2, text="Looking up"),
- ModelStreamEvent(
- ModelStreamEventType.TOOL_CALL_COMPLETED,
- "fixture",
- 3,
- call_id="call-1",
- tool_name="read_value",
- arguments="{}",
- ),
- ModelStreamEvent(
- ModelStreamEventType.USAGE_UPDATED,
- "fixture",
- 4,
- usage={"input_tokens": 12, "output_tokens": 4},
- ),
- ModelStreamEvent(
- ModelStreamEventType.TURN_COMPLETED,
- "fixture",
- 5,
- metadata={"finish_reason": "tool_calls"},
- ),
- )
- )
- events = [event async for event in port(client, input_request).stream(input_request)]
- assert [(event.kind, event.seq) for event in events] == [
- ("text_delta", 1),
- ("final", 2),
- ]
- assert events[-1].result.response_kind == "tool_calls"
- assert events[-1].result.tool_calls[0].name == "read_value"
- assert events[-1].result.usage.input_tokens == 12
- assert client.calls[0][1]["retry_empty_stream"] is False
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize("raw_arguments", ['{"x":1,"x":2}', "null", "{"])
-async def test_studio_native_stream_sealed_bad_arguments_keep_a_nonexecutable_call(
- raw_arguments: str,
-):
- input_request = request(streaming=True, tools=(TOOL,))
- client = Client(
- events=(
- ModelStreamEvent(
- ModelStreamEventType.TOOL_CALL_COMPLETED,
- "fixture",
- 1,
- call_id="call-1",
- tool_name="read_value",
- arguments=raw_arguments,
- ),
- ModelStreamEvent(
- ModelStreamEventType.TURN_COMPLETED,
- "fixture",
- 2,
- metadata={"finish_reason": "tool_calls"},
- ),
- )
- )
- events = [event async for event in port(client, input_request).stream(input_request)]
- result = events[-1].result
- assert result.response_kind == "tool_calls"
- assert result.tool_calls[0].arguments == {}
- assert result.tool_calls[0].wire_arguments_invalid is True
-
-
-@pytest.mark.asyncio
-async def test_studio_native_model_port_stream_without_finish_is_retryable():
- input_request = request(streaming=True)
- client = Client(
- events=(
- ModelStreamEvent(ModelStreamEventType.TEXT_DELTA, "fixture", 1, text="partial"),
- ModelStreamEvent(ModelStreamEventType.TURN_COMPLETED, "fixture", 2),
- )
- )
- events = [event async for event in port(client, input_request).stream(input_request)]
- assert events[-1].result.response_kind == "provider_retryable_error"
- assert events[-1].result.failure_kind == "incomplete_response"
- assert events[-1].result.text == "partial"
-
-
-@pytest.mark.asyncio
-async def test_studio_native_model_port_stream_eof_has_incomplete_response_cause():
- input_request = request(streaming=True)
- events = [event async for event in port(Client(), input_request).stream(input_request)]
- assert len(events) == 1
- assert events[0].result.response_kind == "provider_retryable_error"
- assert events[0].result.failure_kind == "incomplete_response"
-
-
-@pytest.mark.asyncio
-async def test_studio_native_model_port_rejects_foreign_scope_before_model_call():
- input_request = request()
- altered = input_request.model_copy(
- update={"scope": SCOPE.model_copy(update={"user_id": "other"})}
- )
- client = Client(response=response())
- with pytest.raises(ValueError, match="scope or profile"):
- await port(client, input_request).complete(altered)
- assert client.calls == []
-
-
-@pytest.mark.asyncio
-async def test_studio_native_model_port_binds_model_and_policy_from_build():
- input_request = request()
- client = Client(response=response())
- bound = StudioNativeModelPort.from_resolved_build(
- client,
- scope=SCOPE,
- resolved_agent_spec=resolved_build(),
- selected_model="fixture",
- profile_digest=input_request.profile.digest,
- )
- assert (await bound.complete(input_request)).response_kind == "final_candidate"
- assert client.calls[0][0] == MODEL
- assert client.calls[0][1]["network_policy"] == NETWORK
-
-
-@pytest.mark.parametrize(
- ("build", "selected_model", "error"),
- [
- (resolved_build(agent_id="other"), "fixture", "Agent differs"),
- (resolved_build(), "missing", "missing or ambiguous"),
- (resolved_build(models=(MODEL, MODEL)), "fixture", "missing or ambiguous"),
- ],
-)
-def test_studio_native_model_port_rejects_invalid_build_model_binding(build, selected_model, error):
- input_request = request()
- with pytest.raises(ValueError, match=error):
- StudioNativeModelPort.from_resolved_build(
- Client(response=response()),
- scope=SCOPE,
- resolved_agent_spec=build,
- selected_model=selected_model,
- profile_digest=input_request.profile.digest,
- )
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize("disclosure", [False, True])
-async def test_explicit_public_summary_crosses_native_stream_without_private_reasoning(disclosure):
- client = Client(events=(
- ModelStreamEvent(ModelStreamEventType.PUBLIC_SUMMARY_DELTA, MODEL.model, 1,
- text="Check the source first.\n"),
- ModelStreamEvent(ModelStreamEventType.REASONING_DELTA, MODEL.model, 2,
- text="PRIVATE_CHAIN_FIXTURE"),
- ModelStreamEvent(ModelStreamEventType.TEXT_DELTA, MODEL.model, 3, text="Visible answer"),
- ModelStreamEvent(ModelStreamEventType.TURN_COMPLETED, MODEL.model, 4,
- metadata={"finish_reason": "stop"}),
- ))
- req = request(streaming=True)
- public_model = MODEL.model_copy(update={"parameters": MODEL.parameters.model_copy(
- update={"public_thinking_summary": disclosure},
- )})
- events = [e async for e in port(client, req, model=public_model).stream(req)]
- assert [e.kind for e in events] == (["public_summary"] if disclosure else []) + ["text_delta", "final"]
- if disclosure:
- assert events[0].text == "Check the source first.\n"
- assert "PRIVATE_CHAIN_FIXTURE" not in "".join(e.model_dump_json() for e in events)
- assert events[-1].result.text == "Visible answer"
diff --git a/tests/studio/test_native_plugin_binding.py b/tests/studio/test_native_plugin_binding.py
deleted file mode 100644
index 7df92315c..000000000
--- a/tests/studio/test_native_plugin_binding.py
+++ /dev/null
@@ -1,62 +0,0 @@
-from __future__ import annotations
-
-import pytest
-import yaml
-from pydantic import ValidationError
-
-from ksadk.studio.codex_manifest import (
- CodexAgentManifest,
- CodexRuntimeRef,
- normalized_manifest_bytes,
-)
-from ksadk.studio.contracts import AgentBindings, NativePluginBinding
-
-_SNAPSHOT = "sha256:" + "c" * 64
-
-
-def _binding(**updates: object) -> NativePluginBinding:
- payload = {
- "ecosystem": "codex",
- "pluginRef": "plugin://io.codex.review@1.2.3",
- "snapshotDigest": _SNAPSHOT,
- "components": ["skill:review", "mcp:review-tools"],
- }
- payload.update(updates)
- return NativePluginBinding.model_validate(payload)
-
-
-def test_codex_manifest_retains_immutable_native_plugin_selection() -> None:
- manifest = CodexAgentManifest(
- name="plugin-agent",
- version="1.0.0",
- runtime=CodexRuntimeRef(version="0.147.0"),
- model="test-model",
- prompt="Review the workspace.",
- plugins=[_binding()],
- )
-
- payload = yaml.safe_load(normalized_manifest_bytes(manifest))
- restored = CodexAgentManifest.model_validate(payload)
- assert restored.plugins == manifest.plugins
- assert restored.plugins is not None
- assert restored.plugins[0].snapshot_digest == _SNAPSHOT
-
-
-def test_binding_rejects_clear_secret_material() -> None:
- with pytest.raises(ValidationError, match="Secret 引用|secret reference"):
- _binding(config={"apiToken": "clear-text"})
-
-
-def test_agent_bindings_reject_duplicate_enabled_plugin_refs() -> None:
- with pytest.raises(ValidationError, match="不能重复"):
- AgentBindings(plugins=[_binding(), _binding(snapshotDigest="sha256:" + "d" * 64)])
-
-
-def test_same_plugin_can_be_retained_disabled_during_migration() -> None:
- bindings = AgentBindings(
- plugins=[
- _binding(),
- _binding(snapshotDigest="sha256:" + "d" * 64, enabled=False),
- ]
- )
- assert [item.enabled for item in bindings.plugins] == [True, False]
diff --git a/tests/studio/test_native_product_child_approval.py b/tests/studio/test_native_product_child_approval.py
deleted file mode 100644
index 3ab54372d..000000000
--- a/tests/studio/test_native_product_child_approval.py
+++ /dev/null
@@ -1,295 +0,0 @@
-"""Ordinary Studio routes child approvals without bypassing original file tools."""
-
-import asyncio
-import json
-
-import pytest
-
-from ksadk.harness.native.state import RunPhase
-from ksadk.harness.spec import SubAgentBinding
-from ksadk.studio.contracts import (
- AgentBindings,
- AgentSpec,
- CapabilityBinding,
- Instructions,
- ModelSpec,
- NetworkPolicy,
- RunStatus,
- RuntimeRef,
- SecuritySpec,
- Usage,
-)
-from ksadk.studio.model_client import ModelResponse, ToolCall
-from ksadk.studio.service import StudioService
-from tests.studio.test_dsh_provider_registration import _managed_profile
-from tests.studio.test_native_product_edit_revision import tool_result
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize("durable", [False, True])
-@pytest.mark.parametrize("background", [False, True])
-@pytest.mark.parametrize("decision", ["approve", "deny", "cancel"])
-async def test_parent_card_resolves_real_child_file_approval(
- tmp_path, monkeypatch, durable, background, decision, *, user_input=False,
- role_timeout=120.0, approval_delay=0.0,
-):
- _managed_profile(tmp_path, monkeypatch)
- monkeypatch.setenv("NATIVE_CHILD_APPROVAL_FIXTURE_KEY", "fixture-key")
- workspace = tmp_path / "studio/.harness-tools/workspace"
- workspace.mkdir(parents=True)
- target = workspace / "demo.py"
- target.write_bytes(b"alpha = 1\n")
-
- class Client:
- def __init__(self):
- self.parent_requests, self.child_requests = [], []
-
- async def complete(self, _model, **kwargs):
- parent = any(t["function"]["name"] == "native_delegate" for t in kwargs["tools"])
- requests = self.parent_requests if parent else self.child_requests
- step = len(requests)
- requests.append(kwargs)
- name, args, text = None, {}, ""
- if parent:
- if step == 0:
- name, args = (
- "native_delegate",
- {
- "role": "writer",
- "task": "Change alpha from 1 to 2 in demo.py.",
- "background": background,
- },
- )
- elif step == 1:
- receipt = tool_result(kwargs["messages"], "parent-0")
- assert receipt["status"] == "ok", receipt
- self.child_id = receipt["content"]["child_run_id"]
- name, args = (
- "native_child_control",
- {
- "action": "wait",
- "child_run_id": self.child_id,
- },
- )
- else:
- assert step == 2
- text = "Child result received. The isolated files have not been merged."
- elif step == 0:
- name, args = "read_workspace_file", {"path": "demo.py"}
- elif step == 1:
- assert tool_result(kwargs["messages"], "child-0")["status"] == "ok"
- name, args = (
- "edit_workspace_file",
- {
- "path": "demo.py",
- "old_text": "alpha = 1",
- "new_text": "alpha = 2",
- },
- )
- else:
- assert step == 2
- if user_input:
- assert "Retain the original approval decision." in str(kwargs["messages"])
- receipt = tool_result(kwargs["messages"], "child-1")
- assert receipt["status"] == ("ok" if decision == "approve" else "error"), receipt
- text = "Updated isolated file." if decision == "approve" else "Write was denied."
- return ModelResponse(
- content=text,
- finish_reason="tool_calls" if name else "stop",
- raw_message={},
- tool_calls=[
- ToolCall(
- id=f"{'parent' if parent else 'child'}-{step}",
- name=name,
- arguments=json.dumps(args),
- )
- ]
- if name
- else [],
- usage=Usage(input_tokens=40, output_tokens=8, total_tokens=48, reported=True),
- )
-
- client = Client()
- studio = StudioService(
- tmp_path / "studio",
- model_client=client,
- native_harness_agent_ids=("child-approval-agent",),
- native_harness_durable=durable,
- )
- task = None
- try:
- tools = {item.name: item for item in studio.catalog.list(kind="tool", limit=200)}
- names = ("read_workspace_file", "edit_workspace_file")
- studio.create_agent(
- agent_id="child-approval-agent",
- name="Child approval",
- spec=AgentSpec(
- runtime=RuntimeRef(type="harness"),
- instructions=Instructions(system="Delegate and report."),
- model=ModelSpec(
- model="fixture-model",
- endpoint_url="https://example.invalid/v1/chat/completions",
- credential_ref="env://NATIVE_CHILD_APPROVAL_FIXTURE_KEY",
- ),
- bindings=AgentBindings(
- policy_template="loose",
- tools=[
- CapabilityBinding(resource_id=tools[name].resource_id) for name in names
- ],
- ),
- security=SecuritySpec(
- allowed_permissions=["process:host-user"],
- network=NetworkPolicy(allowed_hosts=["example.invalid"]),
- ),
- sub_agents=(
- SubAgentBinding(
- name="writer",
- tools=names,
- max_turns=6,
- timeout_seconds=role_timeout,
- instructions="Edit only the isolated demo.py.",
- ),
- ),
- ),
- )
- build = await studio.ensure_current_build("child-approval-agent")
- session = "child-approval-session"
- task = asyncio.create_task(
- studio.run_build(
- build.id,
- "Delegate the isolated file update and report without merging.",
- session,
- approval_mode="risk",
- )
- )
- async with asyncio.timeout(20):
- while True:
- runs = studio.event_store.list_runs(session_id=session)
- if runs and runs[0].status == RunStatus.WAITING_INPUT:
- break
- if task.done():
- raise AssertionError(
- (
- (await task).error,
- len(client.parent_requests),
- len(client.child_requests),
- )
- )
- await asyncio.sleep(0.01)
- record = runs[0]
- approval = next(
- e for e in studio.event_store.events(record.id) if e.type == "approval.requested"
- )
- detail = approval.data["detail"]
- assert detail["source"] == "child_tool"
- assert detail["tool_name"] == "edit_workspace_file"
- assert detail["arguments"] == {
- "path": "demo.py",
- "old_text": "alpha = 1",
- "new_text": "alpha = 2",
- }
- assert approval.data["callId"] == "child-1"
- from ksadk.harness.native.state import RunScope
-
- scope = RunScope.model_validate(detail["child_scope"])
- store = studio._native_product_composer.store
- child = store.load(scope, detail["child_run_id"])
- assert child.phase == RunPhase.AWAITING_INTERACTION
- files = list(
- (tmp_path / "studio/.agentkit/plugin-runtime/state/child-workspaces").glob(
- "*/work/demo.py"
- )
- )
- assert len(files) == 1
- assert files[0].parent.parent.name == child.origin["workspace_isolation_id"]
- assert files[0].read_bytes() == b"alpha = 1\n"
- # The isolation identity is opaque; obtain the actual file via the
- # read receipt produced by the child Worker rather than trusting it.
- read_receipt = next(m for m in child.messages if m.get("tool_call_id") == "child-0")
- assert "alpha = 1" in str(read_receipt)
- assert target.read_bytes() == b"alpha = 1\n"
- assert len(client.child_requests) == 2
- if approval_delay:
- await asyncio.sleep(approval_delay)
- waiting_child = store.load(scope, child.run_id)
- assert waiting_child.phase == RunPhase.AWAITING_INTERACTION
- assert waiting_child.pending_interaction == child.pending_interaction
- assert waiting_child.execution_elapsed_seconds == child.execution_elapsed_seconds
- assert studio.event_store.get(record.id).status == RunStatus.WAITING_INPUT
- assert len(client.child_requests) == 2 and not task.done()
- if user_input:
- import httpx
-
- from ksadk.studio.api import create_studio_app
-
- app = create_studio_app(tmp_path / "studio", service=studio, security_enabled=False)
- async with httpx.AsyncClient(
- transport=httpx.ASGITransport(app=app), base_url="http://testserver"
- ) as http:
- response = await http.get(f"/api/v1/runs/{record.id}/children")
- assert response.status_code == 200, response.text
- (row,) = response.json()["tasks"]
- response = await http.post(
- f"/api/v1/runs/{record.id}/children/{child.run_id}:send",
- json={
- "command_id": "waiting-child-input",
- "text": "Retain the original approval decision.",
- "expected_goal_revision": row["goal_revision"],
- },
- )
- assert response.status_code == 202, response.text
- parent_id = store.session_head(scope, session).run_id
- async with asyncio.timeout(5):
- while not any(
- event.kind == "child.input_queued" for event in store.events(scope, parent_id)
- ):
- await asyncio.sleep(0.01)
- waiting_child = store.load(scope, child.run_id)
- assert waiting_child.phase == RunPhase.AWAITING_INTERACTION
- assert waiting_child.pending_interaction == child.pending_interaction
- assert studio.event_store.get(record.id).status == RunStatus.WAITING_INPUT
- assert len(client.child_requests) == 2 and files[0].read_bytes() == b"alpha = 1\n"
- if decision == "cancel":
- await studio.run_service.cancel_run(record.id)
- else:
- await studio.run_service.submit_interaction(
- record.id,
- approval.data["approvalId"],
- name=decision,
- data={"decision": decision},
- expected_revision=1,
- idempotency_key="child-decision",
- )
- if decision == "cancel":
- with pytest.raises(asyncio.CancelledError):
- await asyncio.wait_for(task, 20)
- result = studio.event_store.get(record.id)
- assert result.status == RunStatus.CANCELLED
- else:
- result = await asyncio.wait_for(task, 20)
- assert result.status == RunStatus.COMPLETED, result.error
- assert result.verification_outcome == "unverified"
- child = store.load(scope, child.run_id)
- assert child.phase == (RunPhase.CANCELED if decision == "cancel" else RunPhase.COMPLETED)
- if user_input:
- assert child.pending_guidance_ids == ()
- assert store.commands(scope, child.run_id) == ()
- assert target.read_bytes() == b"alpha = 1\n"
- assert len(client.child_requests) == (2 if decision == "cancel" else 3)
- assert files[0].read_bytes() == (
- b"alpha = 2\n" if decision == "approve" else b"alpha = 1\n"
- )
- parent = store.session_head(scope, session)
- assert parent.descendant_model_calls == len(client.child_requests)
- assert parent.child_budget_reservations[0].settled_usage_digest is not None
- edited = [m for m in child.messages if m.get("tool_call_id") == "child-1"]
- assert len(edited) == (0 if decision == "cancel" else 1)
- if decision != "cancel":
- assert tool_result(child.messages, "child-1")["status"] == (
- "ok" if decision == "approve" else "error"
- )
- finally:
- if task is not None and not task.done():
- task.cancel()
- await asyncio.gather(task, return_exceptions=True)
- await studio.aclose()
diff --git a/tests/studio/test_native_product_child_deadline.py b/tests/studio/test_native_product_child_deadline.py
deleted file mode 100644
index 36d1c8c20..000000000
--- a/tests/studio/test_native_product_child_deadline.py
+++ /dev/null
@@ -1,267 +0,0 @@
-"""An owned child deadline must retain its original Run and consumed model call."""
-
-import asyncio
-import json
-from types import SimpleNamespace
-
-import pytest
-
-from ksadk.harness.native.state import RunScope
-from ksadk.harness.spec import SubAgentBinding
-from ksadk.studio.contracts import (
- AgentSpec,
- Instructions,
- ModelSpec,
- NetworkPolicy,
- RuntimeRef,
- SecuritySpec,
- Usage,
-)
-from ksadk.studio.model_client import ModelResponse, ToolCall
-from ksadk.studio.native_subagent_port import StudioNativeSubagentPort
-from ksadk.studio.service import StudioService
-from tests.studio.test_dsh_provider_registration import _managed_profile
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize("durable", [False, True])
-async def test_foreground_deadline_retains_owned_child_usage(
- tmp_path,
- monkeypatch,
- durable,
- *,
- slow_assembly=False,
-):
- _managed_profile(tmp_path, monkeypatch)
- monkeypatch.setenv("CHILD_DEADLINE_FIXTURE_KEY", "fixture-key")
- if slow_assembly:
- from ksadk.studio import native_subagent_port
-
- original = native_subagent_port._StudioChildPort.__init__
-
- def bind(self, **kwargs):
- factory = kwargs["factory"]
-
- async def prepare(child):
- # Host setup belongs to the parent effect lease, before this
- # child's active clock exists. Do not alter Kernel time.
- await asyncio.sleep(0.7)
- return await factory(child)
-
- original(self, **{**kwargs, "factory": prepare})
-
- monkeypatch.setattr(native_subagent_port._StudioChildPort, "__init__", bind)
-
- class Client:
- def __init__(self):
- self.parent, self.child = [], []
- self.child_cancelled = asyncio.Event()
-
- async def complete(self, _model, **kwargs):
- names = {tool["function"]["name"] for tool in kwargs["tools"]}
- if "native_delegate" not in names:
- self.child.append(kwargs)
- if slow_assembly:
- return ModelResponse(
- content="Child findings.",
- finish_reason="stop",
- raw_message={},
- tool_calls=[],
- usage=Usage(
- input_tokens=20, output_tokens=5, total_tokens=25, reported=True
- ),
- )
- try:
- await asyncio.Event().wait()
- except asyncio.CancelledError:
- self.child_cancelled.set()
- raise
- self.parent.append(kwargs)
- if len(self.parent) == 1:
- return ModelResponse(
- content="",
- finish_reason="tool_calls",
- raw_message={},
- tool_calls=[
- ToolCall(
- id="deadline-child",
- name="native_delegate",
- arguments=json.dumps({"role": "reviewer", "task": "Inspect the task."}),
- )
- ],
- usage=Usage(input_tokens=20, output_tokens=5, total_tokens=25, reported=True),
- )
- return ModelResponse(
- content="The child did not deliver a verified result.",
- finish_reason="stop",
- raw_message={},
- tool_calls=[],
- usage=Usage(input_tokens=20, output_tokens=5, total_tokens=25, reported=True),
- )
-
- client = Client()
- studio = StudioService(
- tmp_path / "studio",
- model_client=client,
- native_harness_agent_ids=("deadline-agent",),
- native_harness_durable=durable,
- )
- try:
- studio.create_agent(
- agent_id="deadline-agent",
- name="Child deadline",
- spec=AgentSpec(
- runtime=RuntimeRef(type="harness"),
- instructions=Instructions(system="Delegate the task to the reviewer."),
- model=ModelSpec(
- model="fixture-model",
- credential_ref="env://CHILD_DEADLINE_FIXTURE_KEY",
- endpoint_url="https://example.invalid/v1/chat/completions",
- ),
- security=SecuritySpec(
- allowed_permissions=["process:host-user"],
- network=NetworkPolicy(allowed_hosts=["example.invalid"]),
- ),
- sub_agents=(
- SubAgentBinding(
- name="reviewer", instructions="Inspect the task.", timeout_seconds=0.5
- ),
- ),
- ),
- )
- build = await studio.ensure_current_build("deadline-agent")
- run = await asyncio.wait_for(
- studio.run_build(build.id, "Delegate the inspection.", "deadline-session"), timeout=15
- )
- assert len(client.child) == 1, run.error
- assert client.child_cancelled.is_set() is not slow_assembly
- metadata = await studio.session_service.get_session_metadata("deadline-session")
- scope = RunScope(
- tenant_id="local-studio",
- workspace_id=studio.workspace_record.workspace_id,
- user_id=metadata.user_id,
- agent_id=metadata.agent_id,
- )
- store = studio._native_product_composer.store
- parent = store.session_head(scope, "deadline-session")
- assert len(parent.child_run_ids) == 1, (
- parent.phase,
- parent.outcome,
- parent.child_run_ids,
- parent.descendant_model_calls,
- )
- child = store.load(scope, parent.child_run_ids[0])
- assert child.phase.terminal and child.model_calls == 1
- assert parent.descendant_model_calls == child.model_calls
- assert child.origin["parent_run_id"] == parent.run_id
- assert (
- any(e.kind == "usage.unavailable" for e in store.events(scope, child.run_id))
- is not slow_assembly
- )
- prepared = next(
- e
- for e in store.events(scope, parent.run_id)
- if e.kind == "effect.prepared" and e.payload.get("kind") == "tool"
- )
- receipt = store.get_receipt(scope, parent.run_id, prepared.payload["operation_key"])
- assert receipt.status == "committed"
- assert receipt.result["content"]["child_run_id"] == child.run_id
- assert receipt.result["content"]["resource_usage_unknown"] is not slow_assembly
- assert receipt.result["resource_usage"]["model_calls"] == 1
- assert receipt.result["resource_usage"]["input_tokens"] == (20 if slow_assembly else None)
- assert receipt.result["resource_usage"]["output_tokens"] == (5 if slow_assembly else None)
- if slow_assembly:
- assert child.phase.value == "completed" and child.outcome == "unverified"
- assert len(client.parent) == 2
- assert child.execution_elapsed_seconds < 0.5
- assert run.verification_outcome != "verified"
- finally:
- await studio.aclose()
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize("durable", [False, True])
-async def test_parent_effect_owns_slow_host_assembly(tmp_path, monkeypatch, durable):
- await test_foreground_deadline_retains_owned_child_usage(
- tmp_path,
- monkeypatch,
- durable,
- slow_assembly=True,
- )
-
-
-@pytest.mark.asyncio
-@pytest.mark.local_process_heavy
-@pytest.mark.parametrize("durable", [False, True])
-@pytest.mark.parametrize("background", [False, True])
-async def test_approval_wait_does_not_consume_child_execution_budget(
- tmp_path,
- monkeypatch,
- durable,
- background,
-):
- from tests.studio import test_native_product_child_approval as approval_fixture
- from tests.studio.test_native_product_child_approval import (
- test_parent_card_resolves_real_child_file_approval,
- )
-
- now, waits = [0.0], []
- monkeypatch.setattr("ksadk.harness.native.run_clock.monotonic", lambda: now[0])
-
- class ApprovalWaitClock:
- def __getattr__(self, name):
- return getattr(asyncio, name)
-
- async def sleep(self, seconds):
- if seconds == 3.5:
- # The shared fixture has already observed AWAITING_INTERACTION.
- # Advance beyond the child's unchanged 3s budget there, while
- # excluding unrelated host/GC time from active execution.
- waits.append(seconds)
- now[0] += seconds
- await asyncio.sleep(0)
- else:
- await asyncio.sleep(seconds)
-
- monkeypatch.setattr(approval_fixture, "asyncio", ApprovalWaitClock())
- await test_parent_card_resolves_real_child_file_approval(
- tmp_path,
- monkeypatch,
- durable,
- background,
- "approve",
- role_timeout=3.0,
- approval_delay=3.5,
- )
- assert waits == [3.5]
-
-
-@pytest.mark.asyncio
-async def test_unbound_custom_child_port_retains_legacy_timeout():
- class Port:
- async def execute(self, request):
- try:
- await asyncio.Event().wait()
- finally:
- self.cancelled = True
-
- delegate = Port()
- port = StudioNativeSubagentPort(
- child_port=delegate,
- bindings={
- "reviewer": SubAgentBinding(
- name="reviewer",
- instructions="Review.",
- timeout_seconds=0.02,
- )
- },
- )
- result = await port.execute(
- SimpleNamespace(call=SimpleNamespace(arguments={"role": "reviewer"}))
- )
- assert delegate.cancelled
- assert result.status == "uncertain"
- assert result.content["error_code"] == "child_timeout_outcome_unknown"
- assert result.resource_usage.model_calls == result.resource_usage.tool_calls == 0
- assert result.resource_usage.child_run_ids == ()
- assert result.resource_usage.input_tokens is None
diff --git a/tests/studio/test_native_product_durability.py b/tests/studio/test_native_product_durability.py
deleted file mode 100644
index 4aa684b75..000000000
--- a/tests/studio/test_native_product_durability.py
+++ /dev/null
@@ -1,380 +0,0 @@
-"""Cold starts through ordinary Studio/DSH preserve the opted-in Native ledger."""
-
-from __future__ import annotations
-
-import asyncio
-import json
-
-import pytest
-
-from ksadk.harness.native.state import RunScope
-from ksadk.studio.contracts import (
- AgentBindings,
- AgentSpec,
- CapabilityBinding,
- Instructions,
- ModelSpec,
- NativeRunOptions,
- NetworkPolicy,
- RunStatus,
- RuntimeRef,
- SecuritySpec,
- Usage,
-)
-from ksadk.studio.model_client import ModelResponse, ToolCall
-from ksadk.studio.service import StudioService
-from tests.studio.test_dsh_provider_registration import _managed_profile
-
-
-class RecordingClient:
- def __init__(self, answer: str):
- self.answer = answer
- self.requests: list[dict] = []
-
- async def complete(self, _model, **kwargs):
- self.requests.append(kwargs)
- return ModelResponse(
- content=self.answer,
- finish_reason="stop",
- raw_message={},
- tool_calls=[],
- usage=Usage(input_tokens=20, output_tokens=10, total_tokens=30, reported=True),
- )
-
-
-def _create_agent(studio, *, tools=()):
- studio.create_agent(
- agent_id="durable-agent",
- name="Native durable product",
- spec=AgentSpec(
- runtime=RuntimeRef(type="harness"),
- instructions=Instructions(system="Answer the current user request."),
- model=ModelSpec(
- model="fixture-model",
- endpoint_url="https://example.invalid/v1/chat/completions",
- credential_ref="env://NATIVE_DURABILITY_TEST_KEY",
- ),
- bindings=AgentBindings(policy_template="loose", tools=list(tools)),
- security=SecuritySpec(
- allowed_permissions=["process:host-user"],
- network=NetworkPolicy(allowed_hosts=["example.invalid"]),
- ),
- ),
- )
-
-
-def _scope(studio):
- return RunScope(
- tenant_id="local-studio",
- workspace_id=studio.workspace_record.workspace_id,
- user_id="local-user",
- agent_id="durable-agent",
- )
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize("explicit_durability", [False, True])
-async def test_ordinary_studio_native_completed_turn_survives_cold_start(
- tmp_path, monkeypatch, explicit_durability,
-):
- _managed_profile(tmp_path, monkeypatch)
- monkeypatch.setenv("NATIVE_DURABILITY_TEST_KEY", "fixture-key")
- for name in ("KSADK_STUDIO_NATIVE_DEFAULT", "KSADK_STUDIO_NATIVE_AGENT_IDS",
- "KSADK_STUDIO_NATIVE_DURABLE"):
- monkeypatch.delenv(name, raising=False)
- selection = {}
- if explicit_durability:
- monkeypatch.setenv("KSADK_STUDIO_NATIVE_DURABLE", "1")
- selection["native_harness_agent_ids"] = ("durable-agent",)
- root = tmp_path / "studio"
- first_client = RecordingClient("The sealed value is cobalt-48291.")
- first = StudioService(root, model_client=first_client, **selection)
- try:
- _create_agent(first)
- build = await first.ensure_current_build("durable-agent")
- original = await first.run_build(build.id, "Remember the sealed value.", "durable-session")
- assert original.status == RunStatus.COMPLETED, original.error
- original_native_id = original.runtime_handle["run_id"]
- scope = _scope(first)
- head = first._native_product_composer.store.session_head(scope, "durable-session")
- assert head.run_id == original_native_id
- finally:
- await first.aclose()
-
- second_client = RecordingClient("It is cobalt-48291.")
- second = StudioService(root, model_client=second_client, **selection)
- try:
- head = second._native_product_composer.store.session_head(scope, "durable-session")
- assert head is not None, "ordinary Studio discarded its committed Native session head"
- assert head.run_id == original_native_id
- assert head.phase.value == "completed"
- result = await second.run_build(build.id, "What is the sealed value?", "durable-session")
- assert result.status == RunStatus.COMPLETED, result.error
- projected = json.dumps(second_client.requests[0]["messages"], ensure_ascii=False)
- assert "cobalt-48291" in projected
- current = second._native_product_composer.store.session_head(scope, "durable-session")
- assert current.parent_run_id == original_native_id
- await second.run_build(build.id, "New unrelated conversation.", "separate-session")
- assert "cobalt-48291" not in json.dumps(second_client.requests[-1]["messages"])
- finally:
- await second.aclose()
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize("ordinary_default", [False, True])
-async def test_explicit_false_preserves_memory_default_despite_environment(
- tmp_path, monkeypatch, ordinary_default,
-):
- _managed_profile(tmp_path, monkeypatch)
- monkeypatch.setenv("KSADK_STUDIO_NATIVE_DURABLE", "1")
- selection = {} if ordinary_default else {"native_harness_agent_ids": ("durable-agent",)}
- studio = StudioService(tmp_path / "studio", native_harness_durable=False, **selection)
- try:
- from ksadk.harness.stores.native_memory import MemoryRunStore
-
- assert isinstance(studio._native_product_composer.store, MemoryRunStore)
- assert not list((tmp_path / "studio").rglob("native-harness.sqlite"))
- finally:
- await studio.aclose()
-
-
-@pytest.mark.asyncio
-async def test_native_default_environment_can_explicitly_select_memory(tmp_path, monkeypatch):
- _managed_profile(tmp_path, monkeypatch)
- monkeypatch.delenv("KSADK_STUDIO_NATIVE_AGENT_IDS", raising=False)
- monkeypatch.delenv("KSADK_STUDIO_NATIVE_DEFAULT", raising=False)
- monkeypatch.setenv("KSADK_STUDIO_NATIVE_DURABLE", "0")
- studio = StudioService(tmp_path / "studio")
- try:
- from ksadk.harness.stores.native_memory import MemoryRunStore
-
- assert studio._native_harness_default
- assert isinstance(studio._native_product_composer.store, MemoryRunStore)
- finally:
- await studio.aclose()
-
-
-def test_durable_storage_requires_native_execution_when_default_disabled(tmp_path, monkeypatch):
- monkeypatch.delenv("KSADK_STUDIO_NATIVE_AGENT_IDS", raising=False)
- monkeypatch.setenv("KSADK_STUDIO_NATIVE_DURABLE", "1")
- with pytest.raises(ValueError, match="durable.*selected Studio agents"):
- StudioService(tmp_path / "studio", native_harness_default=False)
-
-
-def test_invalid_durable_flag_fails_before_opening_workspace(tmp_path, monkeypatch):
- monkeypatch.setenv("KSADK_STUDIO_NATIVE_DURABLE", "maybe")
- with pytest.raises(ValueError, match="KSADK_STUDIO_NATIVE_DURABLE"):
- StudioService(tmp_path / "studio", native_harness_agent_ids=("durable-agent",))
- assert not (tmp_path / "studio").exists()
-
-
-async def _wait_for(predicate):
- async with asyncio.timeout(15):
- while not predicate():
- await asyncio.sleep(0.01)
-
-
-async def _suspend_product(tmp_path, monkeypatch, projected_status=RunStatus.WAITING_INPUT):
- _managed_profile(tmp_path, monkeypatch)
- monkeypatch.setenv("NATIVE_DURABILITY_TEST_KEY", "fixture-key")
- monkeypatch.setenv("KSADK_STUDIO_NATIVE_DURABLE", "1")
- root = tmp_path / "studio"
-
- class WriteClient(RecordingClient):
- async def complete(self, _model, **kwargs):
- self.requests.append(kwargs)
- assert len(self.requests) == 1, "model advanced before tool approval"
- return ModelResponse(
- content="",
- finish_reason="tool_calls",
- raw_message={},
- usage=Usage(input_tokens=20, output_tokens=10, total_tokens=30, reported=True),
- tool_calls=[ToolCall(
- id="locked-write",
- name="write_workspace_file",
- arguments=json.dumps({"path": "approved.txt", "content": "written once"}),
- )],
- )
-
- first = StudioService(
- root, model_client=WriteClient("unused"), native_harness_agent_ids=("durable-agent",)
- )
- task = None
- try:
- write = next(item for item in first.catalog.list(kind="tool", limit=200)
- if item.name == "write_workspace_file")
- _create_agent(first, tools=(CapabilityBinding(resource_id=write.resource_id),))
- build = await first.ensure_current_build("durable-agent")
- task = asyncio.create_task(first.run_build(
- build.id, "Write approved.txt after approval.", "approval-session"
- ))
- await _wait_for(lambda: first.event_store.list_runs()
- and first.event_store.list_runs()[0].status == RunStatus.WAITING_INPUT)
- original = first.event_store.list_runs()[0]
- await _wait_for(lambda: first.run_service._waiting_modes.get(original.id) == "resume")
- assert not list(root.rglob("approved.txt"))
- approval = next(event for event in first.event_store.events(original.id)
- if event.type == "approval.requested")
- scope = _scope(first)
- first.run_service._detaching_recoveries = True
- task.cancel()
- await asyncio.gather(task, return_exceptions=True)
- first.run_service._detaching_recoveries = False
- # A projection can lag the canonical ledger when the process exits
- # after committing the suspension, before projecting WAITING_INPUT.
- original = first.event_store.get(original.id)
- original.status = projected_status
- first.event_store.save(original)
- finally:
- if task is not None and not task.done():
- task.cancel()
- await asyncio.gather(task, return_exceptions=True)
- await first.aclose()
- return root, original, scope, approval
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize("projected_status", [RunStatus.WAITING_INPUT, RunStatus.RUNNING])
-@pytest.mark.parametrize("decision", ["approve", "reject", "cancel"])
-async def test_ordinary_studio_cold_restore_keeps_approval_and_executes_write_once(
- tmp_path, monkeypatch, projected_status, decision
-):
- root, original, scope, approval = await _suspend_product(
- tmp_path, monkeypatch, projected_status
- )
- original_handle = original.runtime_handle
- client = RecordingClient("The approved write is complete.")
- second = StudioService(root, model_client=client, native_harness_agent_ids=("durable-agent",))
- try:
- await second.start()
- await second.run_service.recover_interrupted(second.resolve_run_spec)
- await _wait_for(lambda: (
- second.run_service._waiting_modes.get(original.id) == "resume"
- and second.event_store.get(original.id).status == RunStatus.WAITING_INPUT
- ) or second.event_store.get(original.id).status == RunStatus.INTERRUPTED)
- restored = second.event_store.get(original.id)
- assert restored.status == RunStatus.WAITING_INPUT, restored.error
- assert restored.runtime_handle == original_handle
- assert client.requests == []
- assert not list(root.rglob("approved.txt"))
- await second.run_service.submit_interaction(
- original.id, approval.data["approvalId"], name=decision,
- data={"decision": decision}, expected_revision=1,
- idempotency_key="durable-product-approval",
- )
- await _wait_for(lambda: second.event_store.get(original.id).status in {
- RunStatus.COMPLETED, RunStatus.FAILED, RunStatus.INTERRUPTED, RunStatus.CANCELLED,
- })
- await _wait_for(lambda: not second.run_service._recovery_tasks)
- finished = second.event_store.get(original.id)
- # Cancelling the approval withdraws this tool's grant; stopping the
- # entire Run is a separate control, matching the existing host contract.
- assert finished.status == RunStatus.COMPLETED, finished.error
- assert finished.runtime_handle == original_handle
- paths = list(root.rglob("approved.txt"))
- assert len(paths) == (1 if decision == "approve" else 0)
- if paths:
- assert paths[0].read_text() == "written once"
- events = second._native_product_composer.store.events(scope, original_handle["run_id"])
- receipts = []
- for event in events:
- if event.kind != "effect.prepared":
- continue
- key = event.payload["operation_key"]
- intent = second._native_product_composer.store.get_intent(
- scope, original_handle["run_id"], key
- )
- receipt = second._native_product_composer.store.get_receipt(
- scope, original_handle["run_id"], key
- )
- if intent.kind == "tool" and receipt is not None:
- receipts.append(receipt)
- assert sum(receipt.result.get("status") == "ok" for receipt in receipts) == (
- 1 if decision == "approve" else 0
- )
- studio_events = second.event_store.events(original.id)
- assert sum(event.type == "approval.requested" for event in studio_events) == 1
- assert sum(event.type == "approval.resolved" for event in studio_events) == 1
- assert sum(event.type == "run.completed" for event in studio_events) == 1
- finally:
- await second.aclose()
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize("changed_binding", ["goal", "scope", "model", "durability", "permission"])
-async def test_cold_restore_rejects_changed_binding_before_model_or_tools(
- tmp_path, monkeypatch, changed_binding
-):
- root, original, _scope, _approval = await _suspend_product(tmp_path, monkeypatch)
- if changed_binding == "durability":
- monkeypatch.setenv("KSADK_STUDIO_NATIVE_DURABLE", "0")
- client = RecordingClient("must not run")
- second = StudioService(root, model_client=client, native_harness_agent_ids=("durable-agent",))
- try:
- if changed_binding == "goal":
- original.input = "Different user objective."
- elif changed_binding == "scope":
- original.runtime_handle["native_ref"]["scope_digest"] = "foreign-scope"
- elif changed_binding == "model":
- original.model = "different-model"
- elif changed_binding == "permission":
- original.native_runtime_options = NativeRunOptions(tool_approval_mode="full")
- second.event_store.save(original)
- await second.start()
- await second.run_service.recover_interrupted(second.resolve_run_spec)
- assert second.event_store.get(original.id).status == RunStatus.INTERRUPTED
- assert client.requests == []
- assert not list(root.rglob("approved.txt"))
- assert not second.run_service._recovery_tasks
- finally:
- await second.aclose()
-
-
-@pytest.mark.asyncio
-async def test_ordinary_studio_waits_for_crashed_lease_before_restoring_approval(
- tmp_path, monkeypatch
-):
- root, original, scope, _approval = await _suspend_product(tmp_path, monkeypatch)
- client = RecordingClient("must wait for approval")
- second = StudioService(root, model_client=client, native_harness_agent_ids=("durable-agent",))
- try:
- await second.start()
- from ksadk.harness.stores import native_sqlite
-
- now = [native_sqlite.time()]
- monkeypatch.setattr(native_sqlite, "time", lambda: now[0])
- second._native_product_composer.store.acquire_lease(
- scope, original.runtime_handle["run_id"], owner_id="crashed-owner", ttl_seconds=0.7
- )
- await second.run_service.recover_interrupted(second.resolve_run_spec)
- assert second.event_store.get(original.id).status == RunStatus.WAITING_INPUT
- assert second.run_service._waiting_modes.get(original.id) is None
- # Restore preparation may perform slow I/O. Expire the owned fixture
- # lease explicitly only after proving it prevented early attachment.
- now[0] += 0.8
- await _wait_for(lambda: second.run_service._waiting_modes.get(original.id) == "resume")
- assert client.requests == []
- assert not list(root.rglob("approved.txt"))
- assert second.event_store.get(original.id).runtime_handle == original.runtime_handle
- finally:
- await second.aclose()
-
-
-@pytest.mark.asyncio
-async def test_stopping_restored_run_never_executes_the_pending_tool(tmp_path, monkeypatch):
- root, original, _scope, _approval = await _suspend_product(tmp_path, monkeypatch)
- client = RecordingClient("must not run")
- second = StudioService(root, model_client=client, native_harness_agent_ids=("durable-agent",))
- try:
- await second.start()
- await second.run_service.recover_interrupted(second.resolve_run_spec)
- await _wait_for(lambda: second.run_service._waiting_modes.get(original.id) == "resume")
- await second.run_service.cancel_run(original.id)
- await _wait_for(lambda: not second.run_service._recovery_tasks)
- assert second.event_store.get(original.id).status == RunStatus.CANCELLED
- assert not list(root.rglob("approved.txt"))
- assert client.requests == []
- events = second.event_store.events(original.id)
- assert sum(event.type == "run.cancelled" for event in events) == 1
- finally:
- await second.aclose()
diff --git a/tests/studio/test_native_product_edit_revision.py b/tests/studio/test_native_product_edit_revision.py
deleted file mode 100644
index da46ea78b..000000000
--- a/tests/studio/test_native_product_edit_revision.py
+++ /dev/null
@@ -1,150 +0,0 @@
-"""Ordinary Studio edits preserve external changes across builtin worker processes."""
-
-import json
-import os
-import sqlite3
-
-import pytest
-
-from ksadk.studio.contracts import (
- AgentBindings,
- AgentSpec,
- CapabilityBinding,
- Instructions,
- ModelSpec,
- NetworkPolicy,
- RunStatus,
- RuntimeRef,
- SecuritySpec,
- Usage,
-)
-from ksadk.studio.model_client import ModelResponse, ToolCall
-from ksadk.studio.service import StudioService
-from tests.studio.test_dsh_provider_registration import _managed_profile
-from tests.studio.test_native_workspace_diagnostics import call, surface
-
-
-def tool_result(messages, call_id):
- message = next(m for m in messages
- if m.get("role") == "tool" and m.get("tool_call_id") == call_id)
- content = message["content"]
- if isinstance(content, list):
- content = content[0]["text"]
- return json.loads(content)
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize("name", ["edit_workspace_file", "multi_edit_workspace_file"])
-async def test_ordinary_studio_rejects_stale_edit_then_uses_fresh_observed_revision(
- tmp_path, monkeypatch, name
-):
- _managed_profile(tmp_path, monkeypatch)
- monkeypatch.setenv("NATIVE_EDIT_REVISION_TEST_KEY", "fixture-key")
- root = tmp_path / "studio" / ".harness-tools" / "workspace"
- root.mkdir(parents=True)
- target = root / "demo.py"
- target.write_bytes(b"value = 1\nother = 'a'\n")
- external = b"value = 1\nother = 'b'\n"
- names = ("read_workspace_file", name, "read_workspace_file", name)
- changes = {"old_text": "value = 1", "new_text": "value = 2"}
-
- class Client:
- def __init__(self):
- self.requests = []
-
- async def complete(self, _model, **kwargs):
- step = len(self.requests)
- self.requests.append(kwargs)
- if step == 1:
- assert tool_result(kwargs["messages"], "step-0")["status"] == "ok"
- observed = target.stat()
- target.write_bytes(external)
- os.utime(target, ns=(observed.st_atime_ns, observed.st_mtime_ns))
- elif step == 2:
- stale = tool_result(kwargs["messages"], "step-1")
- assert stale["status"] == "error"
- assert stale["content"]["error_type"] == "file_modified_since_read"
- assert "read_workspace_file" in stale["content"]["suggested_action"]
- assert target.read_bytes() == external
- elif step == 3:
- fresh = tool_result(kwargs["messages"], "step-2")
- assert fresh["status"] == "ok"
- assert "other = 'b'" in fresh["content"]["content"]
- elif step == 4:
- assert tool_result(kwargs["messages"], "step-3")["status"] == "ok"
- assert target.read_bytes() == external.replace(b"value = 1", b"value = 2")
- arguments = {"path": "demo.py"}
- if step in {1, 3}:
- arguments.update({"edits": [changes]} if name.startswith("multi") else changes)
- return ModelResponse(
- content="" if step < len(names) else "Updated only the requested value.",
- finish_reason="tool_calls" if step < len(names) else "stop",
- usage=Usage(input_tokens=40, output_tokens=8, total_tokens=48, reported=True),
- raw_message={}, tool_calls=[ToolCall(id=f"step-{step}", name=names[step],
- arguments=json.dumps(arguments))] if step < len(names) else [],
- )
-
- client = Client()
- studio = StudioService(
- tmp_path / "studio", model_client=client, native_harness_agent_ids=("revision-agent",)
- )
- try:
- catalog = {item.name: item for item in studio.catalog.list(kind="tool", limit=200)}
- studio.create_agent(
- agent_id="revision-agent", name="Revision check",
- spec=AgentSpec(
- runtime=RuntimeRef(type="harness"),
- instructions=Instructions(system="Inspect the file before editing."),
- model=ModelSpec(
- model="fixture-model", endpoint_url="https://example.invalid/v1/chat/completions",
- credential_ref="env://NATIVE_EDIT_REVISION_TEST_KEY",
- ),
- bindings=AgentBindings(policy_template="loose", tools=[
- CapabilityBinding(resource_id=catalog[tool].resource_id)
- for tool in {"read_workspace_file", name}
- ]),
- security=SecuritySpec(allowed_permissions=["process:host-user"],
- network=NetworkPolicy(allowed_hosts=["example.invalid"])),
- ),
- )
- build = await studio.ensure_current_build("revision-agent")
- run = await studio.run_build(
- build.id, "Inspect demo.py and change value from 1 to 2, preserving all other content.",
- "revision-session", approval_mode="full",
- )
- assert run.status == RunStatus.COMPLETED, run.error
- assert run.runtime_handle["native_ref"]["engine_kind"] == "native"
- assert len(client.requests) == 5
- assert target.read_bytes() == external.replace(b"value = 1", b"value = 2")
- assert run.verification_outcome == "unverified"
- finally:
- await studio.aclose()
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize("name", ["edit_workspace_file", "multi_edit_workspace_file"])
-async def test_builtin_worker_legacy_read_rows_upgrade_only_after_fresh_read(tmp_path, name):
- tools, _ = surface(tmp_path, ("read_workspace_file", name))
- root = tmp_path / "studio" / ".harness-tools" / "workspace"
- root.mkdir(parents=True)
- target = root / "demo.py"
- original = b"value = 1\n"
- target.write_bytes(original)
- assert (await call(tools, "read_workspace_file", {"path": "demo.py"})).status == "ok"
- databases = list((tmp_path / "studio" / ".harness-tools" / "state").glob("*.sqlite"))
- assert len(databases) == 1
- with sqlite3.connect(databases[0]) as db:
- raw = db.execute("SELECT data FROM reads WHERE session=?", ("s",)).fetchone()[0]
- rows = json.loads(raw)
- for row in rows:
- row.pop("canonical_path", None)
- row.pop("content_sha256", None)
- db.execute("UPDATE reads SET data=? WHERE session=?", (json.dumps(rows), "s"))
- changes = {"old_text": "value = 1", "new_text": "value = 2"}
- args = {"path": "demo.py", **({"edits": [changes]} if name.startswith("multi") else changes)}
- denied = await call(tools, name, args)
- assert denied.status == "error" and denied.content["error_type"] == "file_not_read"
- assert target.read_bytes() == original
- assert (await call(tools, "read_workspace_file", {"path": "demo.py"})).status == "ok"
- assert (await call(tools, name, args)).status == "ok"
- assert target.read_bytes() == b"value = 2\n"
diff --git a/tests/studio/test_native_workspace_diagnostics.py b/tests/studio/test_native_workspace_diagnostics.py
deleted file mode 100644
index 9c162c882..000000000
--- a/tests/studio/test_native_workspace_diagnostics.py
+++ /dev/null
@@ -1,369 +0,0 @@
-"""Post-write diagnostics are repair observations, never acceptance authority."""
-
-from __future__ import annotations
-
-import hashlib
-import json
-
-import pytest
-
-from ksadk.harness.execution_policy import ExecutionPolicy, execution_policy_scope
-from ksadk.harness.native.model import ModelTextContent, ModelToolCall
-from ksadk.harness.native.ports import ToolRequest, digest
-from ksadk.harness.native.state import RunScope, RunSnapshot
-from ksadk.harness.stores.native_memory import MemoryRunStore
-from ksadk.studio.native_tool_port import build_native_locked_tool_surface
-from ksadk.toolsets import describe_agentengine_tools
-
-SCOPE = RunScope(tenant_id="a", workspace_id="w", user_id="u", agent_id="agent")
-
-
-def surface(tmp_path, names=("write_workspace_file",), authorize=None):
- store = MemoryRunStore()
- store.create(
- RunSnapshot(
- scope=SCOPE,
- run_id="run",
- session_id="s",
- turn_id="t",
- goal="Repair files",
- )
- )
-
- async def allow(_request):
- return "allow"
-
- contracts = {
- d["name"]: {
- "name": d["name"],
- "executor": "builtin",
- "inputSchema": d["input_schema"],
- "description": d["description"],
- "approval": "always",
- "sideEffect": "write",
- }
- for d in describe_agentengine_tools(profile="coding", mode="direct")
- }
- tools = build_native_locked_tool_surface(
- bundle_root=tmp_path,
- resolved_agent_spec={
- "agentId": "agent",
- "capabilities": {"tools": [contracts[n] for n in names]},
- },
- workspace_root=tmp_path / "studio",
- scope=SCOPE,
- store=store,
- authorize=authorize or allow,
- )
- return tools, store
-
-
-async def call(tools, name, arguments, *, definition=None):
- definition = definition or next(d for d in tools.definitions if d.name == name)
- return await tools.executor.execute(
- ToolRequest(
- scope=SCOPE,
- run_id="run",
- operation_key="operation",
- call=ModelToolCall(call_id="call", name=name, arguments=arguments),
- definition=definition,
- )
- )
-
-
-def diagnostics(result):
- blocks = [b for b in result.content_blocks if isinstance(b, ModelTextContent)]
- assert len(blocks) == 1
- value = json.loads(blocks[0].text)
- assert value["version"] == "workspace-diagnostics/v1"
- assert value["scope"] == "python_parse_only"
- assert value["acceptance"] == "not_evaluated"
- return value
-
-
-@pytest.mark.asyncio
-async def test_real_builtin_write_returns_diagnostic_for_actual_bytes_then_clears_it(tmp_path):
- tools, _ = surface(tmp_path)
- root = tmp_path / "studio/.harness-tools/workspace"
- invalid = "def compute(:\n return 42\n"
- broken = await call(tools, "write_workspace_file", {"path": "src/calc.py", "content": invalid})
- assert broken.status == "ok" # The write itself really succeeded.
- assert (root / "src/calc.py").read_text() == invalid
- report = diagnostics(broken)
- item = report["files"][0]
- assert item["status"] == "error"
- assert item["code"] == "python_syntax_error"
- assert item["line"] == 1 and item["column"] > 0
- assert item["path"] == "src/calc.py"
- assert item["content_digest"] == "sha256:" + hashlib.sha256(invalid.encode()).hexdigest()
- correct = "def compute():\n return 42\n"
- fixed = await call(tools, "write_workspace_file", {"path": "src/calc.py", "content": correct})
- assert diagnostics(fixed)["files"][0]["status"] == "passed"
- assert diagnostics(fixed)["files"][0]["content_digest"] != item["content_digest"]
- assert "diagnostics" not in broken.content
-
-
-@pytest.mark.asyncio
-async def test_diagnostic_reader_uses_active_policy_root_and_does_not_execute_code(tmp_path):
- tools, _ = surface(tmp_path)
- root = tmp_path / "policy-workspace"
- sentinel = tmp_path / "must-not-exist"
- content = f"from pathlib import Path\nPath({str(sentinel)!r}).write_text('ran')\n"
- with execution_policy_scope(ExecutionPolicy(workspace_root=root)):
- result = await call(tools, "write_workspace_file", {"path": "calc.py", "content": content})
- assert result.status == "ok"
- assert diagnostics(result)["files"][0]["status"] == "passed"
- assert (root / "calc.py").read_text() == content
- assert not sentinel.exists()
-
-
-@pytest.mark.asyncio
-async def test_unsupported_file_is_not_a_successful_diagnostic(tmp_path):
- tools, _ = surface(tmp_path)
- result = await call(tools, "write_workspace_file", {"path": "calc.js", "content": "broken ???"})
- item = diagnostics(result)["files"][0]
- assert result.status == "ok"
- assert item["status"] == "not_run"
- assert item["code"] == "unsupported_file_type"
-
-
-@pytest.mark.asyncio
-async def test_diagnostic_profile_is_locked_before_write_authorization(tmp_path):
- authorized = []
-
- async def allow(request):
- authorized.append(request)
- return "allow"
-
- tools, _ = surface(tmp_path, authorize=allow)
- original = tools.definitions[0]
- assert original.feedback_profile_digest.startswith("sha256:")
- assert "feedback_profile_digest" not in original.function_schema()
- legacy = original.model_copy(update={"feedback_profile_digest": None})
- assert digest(legacy) != digest(original)
- result = await call(
- tools,
- original.name,
- {"path": "calc.py", "content": "x=1"},
- definition=legacy,
- )
- assert result.status == "error" and result.content == {"code": "definition_mismatch"}
- assert authorized == []
-
-
-@pytest.mark.parametrize("name", ["edit_workspace_file", "multi_edit_workspace_file"])
-@pytest.mark.asyncio
-async def test_unobserved_file_requires_read_and_successful_edits_get_diagnostics(
- tmp_path, name
-):
- tools, _ = surface(tmp_path, ("read_workspace_file", name))
- root = tmp_path / "studio/.harness-tools/workspace"
- root.mkdir(parents=True)
- # An external file is unobserved. A successful write by this Session is
- # covered separately as an observed revision and must not require reread.
- (root / "calc.py").write_bytes(b"answer = 42\n")
- changes = {"old_text": "answer = 42", "new_text": "answer = ("}
- args = {"path": "calc.py", **({"edits": [changes]} if name.startswith("multi") else changes)}
- unread = await call(tools, name, args)
- assert unread.status == "error"
- assert unread.content_blocks == ()
- await call(tools, "read_workspace_file", {"path": "calc.py"})
- edited = await call(tools, name, args)
- assert edited.status == "ok"
- assert diagnostics(edited)["files"][0]["status"] == "error"
- assert (root / "calc.py").read_text() == "answer = (\n"
-
-
-@pytest.mark.asyncio
-async def test_multiple_write_reports_each_observed_file(tmp_path):
- tools, _ = surface(tmp_path, ("write_workspace_files",))
- result = await call(
- tools,
- "write_workspace_files",
- {
- "files": [
- {"path": "good.py", "content": "answer=42"},
- {"path": "bad.py", "content": "answer=("},
- {"path": "other.ts", "content": "???"},
- ]
- },
- )
- report = diagnostics(result)
- assert [(d["path"], d["status"]) for d in report["files"]] == [
- ("good.py", "passed"),
- ("bad.py", "error"),
- ("other.ts", "not_run"),
- ]
- assert report["omitted_file_count"] == 0
- assert len(result.content["written"]) == 3
-
-
-@pytest.mark.asyncio
-async def test_denied_write_never_reads_or_mutates_workspace(tmp_path, monkeypatch):
- from ksadk.studio import native_tool_port
-
- def never(**_args):
- raise AssertionError("diagnostic read before authorization")
-
- async def deny(_request):
- return "deny"
-
- monkeypatch.setattr(native_tool_port, "observe_workspace_writes", never)
- tools, _ = surface(tmp_path, authorize=deny)
- result = await call(tools, "write_workspace_file", {"path": "calc.py", "content": "x=1"})
- assert result.content == {"code": "policy_denied"}
- assert result.content_blocks == ()
- assert not (tmp_path / "studio/.harness-tools/workspace/calc.py").exists()
-
-
-@pytest.mark.parametrize("path", ["../private.py", "/private.py", "sub/link.py", "dir/file.py"])
-def test_diagnostic_reader_cannot_follow_escape_paths_or_symlinks(tmp_path, path):
- from ksadk.studio.native_workspace_diagnostics import observe_workspace_writes
-
- root = tmp_path / "workspace"
- root.mkdir()
- secret = tmp_path / "private.py"
- secret.write_text("hidden='do-not-disclose'\ndef bad(:")
- (root / "sub").mkdir()
- (root / "sub/link.py").symlink_to(secret)
- (root / "dir").symlink_to(tmp_path, target_is_directory=True)
- block = observe_workspace_writes(root=root, paths=(path,))
- item = json.loads(block.text)["files"][0]
- assert item["status"] == "not_run"
- assert "content_digest" not in item
- assert "do-not-disclose" not in block.text
-
-
-def test_syntax_error_feedback_does_not_return_source_or_arbitrary_parser_message(tmp_path):
- from ksadk.studio.native_workspace_diagnostics import observe_workspace_writes
-
- (tmp_path / "calc.py").write_text("secret = 'do-not-disclose\n")
- result = observe_workspace_writes(root=tmp_path, paths=("calc.py",))
- assert "do-not-disclose" not in result.text
- assert "unterminated" not in result.text
- assert json.loads(result.text)["files"][0]["code"] == "python_syntax_error"
-
-
-def test_diagnostics_bound_file_count_bytes_and_omitted_status(tmp_path):
- from ksadk.studio.native_workspace_diagnostics import (
- MAX_FILE_BYTES,
- MAX_FILES,
- observe_workspace_writes,
- )
-
- (tmp_path / "large.py").write_bytes(b"#" + b"x" * MAX_FILE_BYTES)
- paths = ("large.py", *(f"missing-{i}.py" for i in range(20)))
- report = json.loads(observe_workspace_writes(root=tmp_path, paths=paths).text)
- assert len(report["files"]) == MAX_FILES
- assert report["omitted_file_count"] == len(paths) - MAX_FILES
- assert report["files"][0]["status"] == "not_run"
- assert report["files"][0]["code"] == "byte_budget_exceeded"
-
-
-def test_absent_feedback_profile_preserves_legacy_serialization_and_digest():
- from ksadk.harness.native.ports import ToolDefinition
- from tests.harness.native.test_kernel import config
-
- definition = ToolDefinition(name="tool", description="d", parameters={})
- payload = definition.model_dump(mode="json")
- assert "feedback_profile_digest" not in payload
- legacy_payload = dict(payload)
- legacy_payload.pop("progress_observation")
- legacy_payload.pop("context_role")
- expected = hashlib.sha256(
- json.dumps(legacy_payload, sort_keys=True, separators=(",", ":")).encode()
- ).hexdigest()
- assert digest(definition) == expected
- configured = config().model_copy(update={"tools": (definition,)})
- assert "feedback_profile_digest" not in configured.model_dump(mode="json")["tools"][0]
-
-
-@pytest.mark.asyncio
-async def test_kernel_delivers_diagnostic_before_next_decision_and_keeps_acceptance_separate(
- tmp_path,
-):
- from ksadk.harness.native.engine import NativeKernel
- from tests.harness.native.test_kernel import ScriptedModel, config
-
- tools, store = surface(tmp_path)
- model = ScriptedModel(
- {
- "tool_calls": [
- {
- "call_id": "bad",
- "name": "write_workspace_file",
- "arguments": {"path": "calc.py", "content": "answer = ("},
- }
- ]
- },
- {
- "tool_calls": [
- {
- "call_id": "fix",
- "name": "write_workspace_file",
- "arguments": {"path": "calc.py", "content": "answer = 42"},
- }
- ]
- },
- {"text": "Delivered."},
- )
- cfg = config().model_copy(update={"tools": tools.definitions})
- kernel = NativeKernel(
- store=store, scope=SCOPE, configuration=cfg, model=model, tools=tools.executor
- )
- run = kernel.start(goal="Write a Python module", session_id="kernel")
- result = await kernel.run_until_idle(run.run_id)
- assert len(model.requests) == 3
- for request, expected, call_id in (
- (model.requests[1], "error", "bad"),
- (model.requests[2], "passed", "fix"),
- ):
- message = next(m for m in request.messages if m.get("tool_call_id") == call_id)
- assert isinstance(message["content"], list)
- feedback = json.loads(message["content"][1]["text"])
- assert feedback["files"][0]["status"] == expected
- assert message["receipt_ref"]
- receipt = store.get_receipt(SCOPE, run.run_id, message["receipt_ref"])
- assert receipt.result["status"] == "ok"
- assert receipt.result["content_blocks"][0]["text"] == message["content"][1]["text"]
- assert result.outcome == "unverified"
- assert result.verification is None
- assert result.model_calls == 3 and result.tool_calls == 2
-
-
-@pytest.mark.asyncio
-async def test_custom_tool_with_same_name_has_no_builtin_diagnostic_authority(
- tmp_path, monkeypatch
-):
- from types import SimpleNamespace
-
- from ksadk.studio import native_tool_port
-
- async def write(_arguments, **_kwargs):
- return {"ok": True, "path": "calc.py"}
-
- custom = SimpleNamespace(
- name="write_workspace_file",
- source="locked-python",
- description="custom",
- parameters={"type": "object"},
- call=write,
- )
- monkeypatch.setattr(
- native_tool_port, "assemble_python_tools", lambda *_a, **_k: ({custom.name: custom}, set())
- )
- tools, _ = surface(tmp_path)
- assert tools.definitions[0].feedback_profile_digest is None
- result = await call(tools, custom.name, {"path": "calc.py"})
- assert result.status == "ok" and result.content_blocks == ()
-
-
-def test_nonregular_file_cannot_block_diagnostic_reader(tmp_path):
- import os
-
- from ksadk.studio.native_workspace_diagnostics import observe_workspace_writes
-
- os.mkfifo(tmp_path / "pipe.py")
- report = json.loads(observe_workspace_writes(root=tmp_path, paths=("pipe.py",)).text)
- assert report["files"][0]["status"] == "not_run"
- assert report["files"][0]["code"] == "file_unavailable"
diff --git a/tests/studio/test_resource_authority.py b/tests/studio/test_resource_authority.py
deleted file mode 100644
index d323b7da7..000000000
--- a/tests/studio/test_resource_authority.py
+++ /dev/null
@@ -1,585 +0,0 @@
-import json
-import threading
-from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
-from types import SimpleNamespace
-from urllib.parse import parse_qs, urlsplit
-
-import pytest
-import requests
-
-from ksadk.resource_runtime.contracts import ResourceConfig
-from ksadk.studio.contracts import AgentBindings, AgentSpec
-from ksadk.studio.errors import StudioError
-from ksadk.studio.model_client import CredentialResolver
-from ksadk.studio.resource_authority import (
- ResourceAuthorityPolicy,
- SignedKnowledgeResourceAuthority,
- _HardenedSdkTransport,
- resource_authority_policy_from_environment,
-)
-from ksadk.studio.resource_connections import (
- ResourceConnectionDeclaration,
- ResourceConnectionRepository,
-)
-from ksadk.studio.workspace import Workspace
-from tests.resource_runtime.test_studio_resource_config import binding
-
-
-@pytest.fixture
-def authority_upstream():
- state = {
- "calls": [],
- "iam_status": 200,
- "iam_listing": {
- "AccessKeyList": [
- {"AccessKey": "fixture-current-ak", "UserName": "fixture-user"}
- ]
- },
- "iam_user": {
- "GetUserResult": {
- "User": {
- "UserId": "fixture-user-id",
- "UserName": "fixture-user",
- "Krn": "krn:ksc:iam::fixture-account:user/fixture-user",
- }
- }
- },
- "knowledge_status": 200,
- "knowledge": {"RequestId": "fixture-request", "Records": []},
- "knowledge_raw": None,
- "knowledge_content_length": True,
- }
-
- class Handler(BaseHTTPRequestHandler):
- def do_POST(self):
- length = int(self.headers.get("Content-Length", "0"))
- raw = self.rfile.read(length)
- state["calls"].append((self.path, dict(self.headers), raw))
- path = urlsplit(self.path)
- if path.path == "/iam":
- params = parse_qs(raw.decode())
- action = params.get("Action", [""])[0]
- payload = (
- state["iam_listing"]
- if action == "ListAllUserAccessKeys"
- else state["iam_user"]
- )
- status = state["iam_status"]
- elif path.path == "/aicp":
- payload = state["knowledge"]
- status = state["knowledge_status"]
- elif path.path == "/redirect":
- self.send_response(307)
- self.send_header("Location", "/aicp")
- self.send_header("Content-Length", "0")
- self.end_headers()
- return
- else:
- payload = {"Error": {"Code": "unexpected"}}
- status = 404
- content = (
- state["knowledge_raw"]
- if path.path == "/aicp" and state["knowledge_raw"] is not None
- else json.dumps(payload).encode()
- )
- self.send_response(status)
- self.send_header("Content-Type", "application/json")
- if path.path != "/aicp" or state["knowledge_content_length"]:
- self.send_header("Content-Length", str(len(content)))
- self.end_headers()
- self.wfile.write(content)
-
- def log_message(self, *args):
- pass
-
- server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
- thread = threading.Thread(target=server.serve_forever, daemon=True)
- thread.start()
- try:
- origin = f"http://127.0.0.1:{server.server_port}"
- yield origin, state
- finally:
- server.shutdown()
- server.server_close()
- thread.join(timeout=5)
-
-
-def _setup(tmp_path, origin, *, data_path="/aicp"):
- resolver = CredentialResolver()
- resolver.put_session("RESOURCE_AK", "fixture-current-ak")
- resolver.put_session("RESOURCE_SK", "fixture-current-sk")
- connections = ResourceConnectionRepository(Workspace(tmp_path), resolver)
- declaration = ResourceConnectionDeclaration.model_validate(
- {
- "label": "Fixture knowledge",
- "target": {
- "connectionRef": "connection-a",
- "tenantRef": "fixture-account",
- "principalRef": "fixture-user-id",
- "endpoint": origin + data_path,
- "authMode": "signed",
- },
- "credentials": {
- "accessKeyRef": "env://RESOURCE_AK",
- "secretKeyRef": "env://RESOURCE_SK",
- },
- }
- )
- connections.save(declaration, expected_revision=0)
- policy = ResourceAuthorityPolicy(
- iam_endpoint=origin + "/iam",
- allowed_data_endpoints=(origin + data_path,),
- allowed_regions=("region-a",),
- allow_loopback_http_for_tests=True,
- )
- config = ResourceConfig.model_validate(
- {
- "binding": {
- "id": "binding-a",
- "connectionRef": "connection-a",
- "resource": {
- "kind": "knowledge-base",
- "id": "dataset-a",
- "region": "region-a",
- },
- }
- }
- )
- return resolver, connections, SignedKnowledgeResourceAuthority(connections, policy), config
-
-
-def test_real_signed_transport_proves_exact_subaccount_and_knowledge_read(
- tmp_path, authority_upstream, monkeypatch
-):
- monkeypatch.setenv("KSADK_TRAFFIC_SOURCE", "admission-fixture")
- origin, state = authority_upstream
- monkeypatch.setenv("HTTP_PROXY", "http://127.0.0.1:1")
- monkeypatch.setenv("HTTPS_PROXY", "http://127.0.0.1:1")
- monkeypatch.setenv("KSYUN_IAM_URL", "http://127.0.0.1:1")
- _, _, authority, config = _setup(tmp_path, origin)
-
- grant = authority.admit(config, expected_connection_revision=1)
-
- assert grant.tenant_ref == "fixture-account"
- assert grant.resource_principal_ref == "fixture-user-id"
- assert grant.resource == config.binding.resource
- assert grant.allowed_operations == ("search_knowledge_base",)
- assert grant.request_id == "fixture-request"
- assert grant.digest.startswith("sha256:")
- assert "fixture-current-ak" not in grant.model_dump_json()
- assert "fixture-current-sk" not in grant.model_dump_json()
- assert [urlsplit(item[0]).path for item in state["calls"]] == [
- "/iam", "/iam", "/aicp"
- ]
-
- list_form = parse_qs(state["calls"][0][2].decode())
- get_form = parse_qs(state["calls"][1][2].decode())
- knowledge_query = parse_qs(urlsplit(state["calls"][2][0]).query)
- knowledge_body = json.loads(state["calls"][2][2])
- assert list_form["Action"] == ["ListAllUserAccessKeys"]
- assert get_form["Action"] == ["GetUser"] and get_form["UserName"] == ["fixture-user"]
- assert knowledge_query == {"Action": ["RetrieveKnowledge"], "Version": ["2025-11-14"]}
- assert knowledge_body["DatasetId"] == "dataset-a"
- assert knowledge_body["Query"] == "ksadk-resource-authority-probe"
- for _, headers, _ in state["calls"]:
- assert headers["X-Traffic-Source"] == "admission-fixture"
- authorization = next(
- value for key, value in headers.items() if key.lower() == "authorization"
- )
- assert "fixture-current-ak/" in authorization
- iam_authorization = next(
- value
- for key, value in state["calls"][0][1].items()
- if key.lower() == "authorization"
- )
- data_authorization = next(
- value
- for key, value in state["calls"][2][1].items()
- if key.lower() == "authorization"
- )
- assert "/cn-beijing-6/iam/aws4_request" in iam_authorization
- assert "/region-a/aicp/aws4_request" in data_authorization
-
-
-@pytest.mark.parametrize(
- "listing",
- [
- {},
- {"AccessKeyList": [], "AccessKeys": []},
- {
- "Code": 403,
- "AccessKeyList": [
- {"AccessKey": "fixture-current-ak", "UserName": "fixture-user"}
- ],
- },
- {
- "ResponseMetadata": {"Error": {"Code": "denied"}},
- "AccessKeyList": [
- {"AccessKey": "fixture-current-ak", "UserName": "fixture-user"}
- ],
- },
- {
- "AccessKeyList": [
- {"AccessKey": "fixture-current-ak", "UserName": "fixture-user"}
- ],
- "IsTruncated": True,
- },
- {"AccessKeyList": [
- {"AccessKey": "fixture-current-ak", "UserName": "fixture-user"},
- {"AccessKey": "fixture-current-ak", "UserName": "other-user"},
- ]},
- ],
-)
-def test_iam_listing_must_uniquely_prove_current_subaccount(
- tmp_path, authority_upstream, listing
-):
- origin, state = authority_upstream
- state["iam_listing"] = listing
- _, _, authority, config = _setup(tmp_path, origin)
- with pytest.raises(StudioError) as rejected:
- authority.admit(config)
- assert rejected.value.code == "RESOURCE_IDENTITY_UNVERIFIED"
- assert [urlsplit(item[0]).path for item in state["calls"]] == ["/iam"]
-
-
-def test_declared_identity_is_only_a_comparison(tmp_path, authority_upstream):
- origin, state = authority_upstream
- _, connections, authority, config = _setup(tmp_path, origin)
- current = connections.get("connection-a")
- changed = current.model_dump(exclude={"revision"})
- changed["target"]["principal_ref"] = "browser-claimed-user"
- connections.save(
- ResourceConnectionDeclaration.model_validate(changed), expected_revision=1
- )
- with pytest.raises(StudioError) as rejected:
- authority.admit(config)
- assert rejected.value.code == "RESOURCE_IDENTITY_MISMATCH"
- assert [urlsplit(item[0]).path for item in state["calls"]] == ["/iam", "/iam"]
-
-
-@pytest.mark.parametrize("response", [{}, {"Code": 200}, {"Records": None}])
-def test_incomplete_knowledge_response_never_issues_grant(
- tmp_path, authority_upstream, response
-):
- origin, state = authority_upstream
- state["knowledge"] = response
- _, _, authority, config = _setup(tmp_path, origin)
- with pytest.raises(StudioError) as rejected:
- authority.admit(config)
- assert rejected.value.code == "RESOURCE_OPERATION_UNVERIFIED"
-
-
-def test_redirect_is_not_followed(tmp_path, authority_upstream):
- origin, state = authority_upstream
- _, _, authority, config = _setup(tmp_path, origin, data_path="/redirect")
- with pytest.raises(StudioError) as rejected:
- authority.admit(config)
- assert rejected.value.code == "RESOURCE_OPERATION_UNVERIFIED"
- assert [urlsplit(item[0]).path for item in state["calls"]] == [
- "/iam", "/iam", "/redirect"
- ]
-
-
-def test_oversized_stream_is_stopped_and_response_is_closed(
- authority_upstream, monkeypatch
-):
- origin, state = authority_upstream
- state["knowledge_raw"] = b"{" + (b" " * (1024 * 1024)) + b"}"
- state["knowledge_content_length"] = False
- responses = []
- original_request = requests.Session.request
-
- def capture_response(session, *args, **kwargs):
- response = original_request(session, *args, **kwargs)
- responses.append(response)
- return response
-
- monkeypatch.setattr(requests.Session, "request", capture_response)
- request = SimpleNamespace(
- method="POST",
- uri="/",
- uri_params="",
- data=b"{}",
- header={},
- auth=None,
- )
-
- with pytest.raises(RuntimeError, match="RESOURCE_AUTHORITY_RESPONSE_TOO_LARGE"):
- _HardenedSdkTransport(origin + "/aicp", timeout=2).send_request(request)
-
- assert len(responses) == 1
- assert responses[0].raw.closed
-
-
-def test_unapproved_target_is_rejected_before_secret_or_network(
- tmp_path, authority_upstream, monkeypatch
-):
- origin, state = authority_upstream
- _, connections, _, config = _setup(tmp_path, origin)
- authority = SignedKnowledgeResourceAuthority(
- connections,
- ResourceAuthorityPolicy(
- iam_endpoint=origin + "/iam",
- allowed_data_endpoints=(origin + "/other",),
- allowed_regions=("region-a",),
- allow_loopback_http_for_tests=True,
- ),
- )
- monkeypatch.setattr(
- connections,
- "resolve_credentials",
- lambda *_: (_ for _ in ()).throw(AssertionError("secrets must not be read")),
- )
- with pytest.raises(StudioError) as rejected:
- authority.admit(config)
- assert rejected.value.code == "RESOURCE_AUTHORITY_TARGET_FORBIDDEN"
- assert state["calls"] == []
-
-
-def test_credential_rotation_during_admission_rejects_stale_result(
- tmp_path, authority_upstream
-):
- origin, _ = authority_upstream
- resolver, connections, _, config = _setup(tmp_path, origin)
-
- class RotatingAuthority(SignedKnowledgeResourceAuthority):
- def _prove_knowledge_read(self, config, data_endpoint, access_key, secret_key):
- resolver.put_session("RESOURCE_SK", "fixture-rotated-sk")
- return "fixture-request"
-
- authority = RotatingAuthority(
- connections,
- ResourceAuthorityPolicy(
- iam_endpoint=origin + "/iam",
- allowed_data_endpoints=(origin + "/aicp",),
- allowed_regions=("region-a",),
- allow_loopback_http_for_tests=True,
- ),
- )
- with pytest.raises(StudioError) as rejected:
- authority.admit(config)
- assert rejected.value.code == "RESOURCE_CONNECTION_CHANGED"
-
-
-def test_non_loopback_authority_http_is_never_permitted():
- with pytest.raises(ValueError, match="HTTPS"):
- ResourceAuthorityPolicy(
- iam_endpoint="http://iam.example.test",
- allowed_data_endpoints=("https://aicp.example.test",),
- allowed_regions=("region-a",),
- allow_loopback_http_for_tests=True,
- )
-
-
-def test_internal_http_requires_explicit_host_policy_and_exact_ksyun_host():
- with pytest.raises(ValueError, match="HTTPS"):
- ResourceAuthorityPolicy(
- iam_endpoint="http://iam.inner.api.ksyun.com",
- allowed_data_endpoints=("http://aicp.inner.api.ksyun.com",),
- allowed_regions=("region-a",),
- )
- with pytest.raises(ValueError, match="HTTPS"):
- ResourceAuthorityPolicy(
- iam_endpoint="http://iam.inner.api.ksyun.com.attacker.example",
- allowed_data_endpoints=("http://aicp.inner.api.ksyun.com",),
- allowed_regions=("region-a",),
- allow_ksyun_internal_http=True,
- )
- with pytest.raises(ValueError, match="service root"):
- ResourceAuthorityPolicy(
- iam_endpoint="http://iam.inner.api.ksyun.com:8080",
- allowed_data_endpoints=("http://aicp.inner.api.ksyun.com",),
- allowed_regions=("region-a",),
- allow_ksyun_internal_http=True,
- )
- with pytest.raises(ValueError, match="service root"):
- ResourceAuthorityPolicy(
- iam_endpoint="http://iam.inner.api.ksyun.com/alternate",
- allowed_data_endpoints=("http://aicp.inner.api.ksyun.com",),
- allowed_regions=("region-a",),
- allow_ksyun_internal_http=True,
- )
-
- policy = ResourceAuthorityPolicy(
- iam_endpoint="http://IAM.INNER.API.KSYUN.COM/",
- allowed_data_endpoints=("http://AICP.INNER.API.KSYUN.COM/",),
- allowed_regions=("region-a",),
- allow_ksyun_internal_http=True,
- )
-
- assert policy.iam_endpoint == "http://iam.inner.api.ksyun.com"
- assert policy.allowed_data_endpoints == ("http://aicp.inner.api.ksyun.com",)
-
- secure_policy = ResourceAuthorityPolicy(
- iam_endpoint="https://IAM.INNER.API.KSYUN.COM:443/",
- allowed_data_endpoints=("https://AICP.INNER.API.KSYUN.COM:443/",),
- allowed_regions=("region-a",),
- allow_ksyun_internal_http=True,
- )
- assert secure_policy.iam_endpoint == "https://iam.inner.api.ksyun.com"
-
-
-def test_environment_policy_uses_parsed_hostname_for_internal_iam(monkeypatch):
- monkeypatch.setenv("KSYUN_ACCESS_KEY", "fixture-access")
- monkeypatch.setenv("KSYUN_SECRET_KEY", "fixture-secret")
- monkeypatch.setenv("AGENTENGINE_REGION", "cn-beijing-6")
- monkeypatch.delenv("KSADK_RESOURCE_IAM_ENDPOINT", raising=False)
-
- monkeypatch.setenv(
- "AGENTENGINE_SERVER_URL",
- "https://aicp.inner.api.ksyun.com.attacker.example",
- )
- public_policy = resource_authority_policy_from_environment()
- assert public_policy is not None
- assert public_policy.iam_endpoint == "https://iam.api.ksyun.com"
-
- monkeypatch.setenv(
- "AGENTENGINE_SERVER_URL",
- "https://aicp.inner.api.ksyun.com",
- )
- internal_policy = resource_authority_policy_from_environment()
- assert internal_policy is not None
- assert internal_policy.iam_endpoint == "http://iam.inner.api.ksyun.com"
-
-
-def test_environment_policy_uses_default_control_endpoint_with_global_credentials(monkeypatch):
- monkeypatch.setenv("KSYUN_ACCESS_KEY", "fixture-access")
- monkeypatch.setenv("KSYUN_SECRET_KEY", "fixture-secret")
- monkeypatch.delenv("AGENTENGINE_SERVER_URL", raising=False)
- monkeypatch.delenv("KSADK_RESOURCE_IAM_ENDPOINT", raising=False)
-
- policy = resource_authority_policy_from_environment()
-
- assert policy is not None
- assert policy.allowed_data_endpoints == ("https://aicp.api.ksyun.com",)
- assert policy.iam_endpoint == "https://iam.api.ksyun.com"
-
-
-def test_studio_validation_only_reports_verified_after_real_authority_calls(
- tmp_path, authority_upstream
-):
- from ksadk.studio.service import StudioService
-
- origin, state = authority_upstream
- resolver = CredentialResolver()
- resolver.put_session("RESOURCE_AK", "fixture-current-ak")
- resolver.put_session("RESOURCE_SK", "fixture-current-sk")
- policy = ResourceAuthorityPolicy(
- iam_endpoint=origin + "/iam",
- allowed_data_endpoints=(origin + "/aicp",),
- allowed_regions=("region-a",),
- allow_loopback_http_for_tests=True,
- )
- studio = StudioService(
- tmp_path,
- credential_resolver=resolver,
- resource_authority_policy=policy,
- )
- studio.resource_connections.save(
- ResourceConnectionDeclaration.model_validate(
- {
- "label": "Fixture knowledge",
- "target": {
- "connectionRef": "connection-a",
- "tenantRef": "fixture-account",
- "principalRef": "fixture-user-id",
- "endpoint": origin + "/aicp",
- "authMode": "signed",
- },
- "credentials": {
- "accessKeyRef": "env://RESOURCE_AK",
- "secretKeyRef": "env://RESOURCE_SK",
- },
- }
- ),
- expected_revision=0,
- )
- plugin = binding()
- plugin.config["binding"]["resource"] = {
- "kind": "knowledge-base",
- "id": "dataset-a",
- "region": "region-a",
- }
- draft = studio.drafts.create(
- agent_id="resource-agent",
- name="Resource Agent",
- spec=AgentSpec(bindings=AgentBindings(plugins=[plugin])),
- )
-
- result = studio.validate_resource_bindings(
- "resource-agent", expected_revision=draft.metadata.revision
- )
-
- assert result == {
- "revision": draft.metadata.revision,
- "valid": True,
- "authorizationVerified": True,
- "diagnostics": [],
- }
- assert len(state["calls"]) == 3
-
-
-def test_settings_api_saved_credentials_reach_signed_resource_admission(
- tmp_path, authority_upstream, monkeypatch
-):
- from fastapi.testclient import TestClient
-
- from ksadk.studio.api import create_studio_app
- from ksadk.studio.cloud import UnavailableCloudGateway
- from ksadk.studio.service import StudioService
-
- origin, state = authority_upstream
- _, connections, fixture_authority, config = _setup(tmp_path, origin)
- declaration = connections.get("connection-a").model_dump(by_alias=True, exclude={"revision"})
- declaration["credentials"] = {
- "accessKeyRef": "env://KSYUN_ACCESS_KEY",
- "secretKeyRef": "env://KSYUN_SECRET_KEY",
- }
- connections.save(ResourceConnectionDeclaration.model_validate(declaration), expected_revision=1)
- for key in ("KSYUN_ACCESS_KEY", "KSYUN_SECRET_KEY", "AGENTENGINE_SERVER_URL"):
- monkeypatch.delenv(key, raising=False)
- studio = StudioService(
- tmp_path,
- resource_authority_policy=fixture_authority.policy,
- cloud_gateway=UnavailableCloudGateway(),
- )
- app = create_studio_app(tmp_path, service=studio, security_enabled=False)
- client = TestClient(app)
- response = client.put(
- "/api/v1/system/settings",
- json={
- "cloudAccessKey": "fixture-current-ak",
- "cloudSecretKey": "fixture-current-sk",
- "cloudServerUrl": "https://control.example.test",
- },
- )
- assert response.status_code == 200, response.text
- assert "fixture-current-ak" not in response.text
- access = studio.resource_authority.admit_runtime(config, expected_connection_revision=2)
- assert access.authority.tenant_ref == "fixture-account"
- assert access.credentials.access_key.get_secret_value() == "fixture-current-ak"
- assert [urlsplit(item[0]).path for item in state["calls"]] == ["/iam", "/iam", "/aicp"]
-
-
-def test_preprod_control_plane_http_is_exact_and_root_only():
- endpoint = "http://agent-api-pre.kspmas-internal.ksyun.com"
- environment = {
- "KSYUN_ACCESS_KEY": "fixture-access",
- "KSYUN_SECRET_KEY": "fixture-secret",
- "AGENTENGINE_REGION": "pre-online",
- "AGENTENGINE_SERVER_URL": endpoint,
- }
- policy = resource_authority_policy_from_environment(environment)
- assert policy.allowed_data_endpoints == (endpoint,)
- assert policy.iam_endpoint == "https://iam.api.ksyun.com"
- with pytest.raises(ValueError, match="HTTPS"):
- ResourceAuthorityPolicy(
- iam_endpoint="https://iam.api.ksyun.com",
- allowed_data_endpoints=(endpoint,),
- allowed_regions=("cn-beijing-6",),
- )
- for suffix in (".attacker.example", ":8080", "/alternate", "?redirect=evil", "#fragment"):
- with pytest.raises(ValueError):
- resource_authority_policy_from_environment({
- **environment, "AGENTENGINE_SERVER_URL": endpoint + suffix,
- })
diff --git a/tests/studio/test_run_service.py b/tests/studio/test_run_service.py
deleted file mode 100644
index 0e4289abe..000000000
--- a/tests/studio/test_run_service.py
+++ /dev/null
@@ -1,2356 +0,0 @@
-from __future__ import annotations
-
-import asyncio
-import json
-from collections.abc import AsyncIterator
-from datetime import datetime, timezone
-from pathlib import Path
-from types import SimpleNamespace
-from typing import Any
-
-import pytest
-
-from ksadk.events.canonical import (
- ApprovalRequest,
- ContentSnapshot,
- InteractionRequested,
- ItemCompleted,
- ItemStarted,
- ItemUpdated,
- OutputRef,
- RunCompleted,
- RunFailed,
- RunInterrupted,
- RunStarted,
- RuntimeEvent,
- SourceRef,
- StructuredInputRequest,
- UsageReported,
-)
-from ksadk.events.content import (
- DataContent,
- TextContent,
- ToolCallContent,
- ToolResultContent,
-)
-from ksadk.runtime import (
- BaseRuntime,
- CancelResult,
- CheckpointCapability,
- CheckpointDescriptor,
- PauseResult,
- ResumePayload,
- ResumeTarget,
- RunHandle,
- RuntimeAdapter,
- RuntimeExecutor,
- RuntimeLaunchContext,
- RuntimeRegistry,
- StartRequest,
-)
-from ksadk.studio.contracts import RunStatus
-from ksadk.studio.errors import StudioError
-from ksadk.studio.run_service import (
- StudioRunService,
- StudioRunSpec,
- project_runtime_event,
-)
-from ksadk.studio.workspace import Workspace
-
-
-class _FixtureRuntime(BaseRuntime):
- def __init__(self, runtime_type: str) -> None:
- self.runtime_type = runtime_type
-
- def native_capabilities(self) -> dict[str, Any]:
- return {"Framework": self.runtime_type}
-
-
-class _RecordingAdapter(RuntimeAdapter):
- def __init__(
- self,
- calls: list[tuple[str, Any]],
- runtime_type: str = "langgraph",
- ) -> None:
- super().__init__(_FixtureRuntime(runtime_type))
- self.calls = calls
- self.runtime_type = runtime_type
-
- async def start(self, request: StartRequest) -> RunHandle:
- self.calls.append(("start", request))
- return RunHandle(
- run_id=f"native-{self.runtime_type}",
- session_id=request.session_id,
- runtime_type=self.runtime_type,
- native_ref={"thread_id": "thread-1"},
- )
-
- async def stream(self, handle: RunHandle) -> AsyncIterator[RuntimeEvent]:
- self.calls.append(("stream", handle))
- common = {
- "schema_version": 2,
- "timestamp": 1.0,
- "run_id": handle.run_id,
- "scope_id": f"scope-{handle.run_id}",
- }
- framework = "ksadk" if self.runtime_type == "harness" else self.runtime_type
- source = SourceRef(framework=framework)
- yield RunStarted(
- event_id="e1",
- seq=1,
- status="running",
- source=source,
- **common,
- )
- yield ItemCompleted(
- event_id="e2",
- seq=2,
- item_id="msg-1",
- item_kind="message",
- snapshot=ContentSnapshot(
- parts=(
- TextContent(
- part_id="text-0",
- text=f"{self.runtime_type} answer",
- ),
- )
- ),
- source=source,
- **common,
- )
- yield RunCompleted(
- event_id="e3",
- seq=3,
- status="completed",
- output_refs=(
- OutputRef(
- scope_id=common["scope_id"],
- item_id="msg-1",
- part_id="text-0",
- ),
- ),
- source=SourceRef(
- framework=framework,
- metadata={"duration_ms": 42},
- ),
- **common,
- )
-
- async def cancel(self, handle: RunHandle) -> CancelResult:
- self.calls.append(("cancel", handle))
- return CancelResult.INTERRUPTED_ACTIVE_TURN
-
- async def pause(self, handle: RunHandle) -> PauseResult:
- self.calls.append(("pause", handle))
- return PauseResult.PAUSED_ACTIVE_TURN
-
- async def resume(
- self,
- handle: RunHandle,
- target: ResumeTarget,
- payload: ResumePayload | None,
- ) -> RunHandle:
- return handle
-
- async def checkpoint(self, handle: RunHandle) -> CheckpointDescriptor:
- return CheckpointDescriptor(
- checkpoint_id="checkpoint-1",
- invocation_id=handle.run_id,
- capability=CheckpointCapability(
- supported=False,
- granularity="none",
- rollback_scope="none",
- fork_supported=False,
- durable=False,
- shared_across_pods=False,
- ),
- )
-
- async def close(self, handle: RunHandle) -> None:
- self.calls.append(("close", handle))
-
-
-class _MultiMessageAdapter(_RecordingAdapter):
- async def stream(self, handle: RunHandle) -> AsyncIterator[RuntimeEvent]:
- common = {
- "schema_version": 2,
- "timestamp": 1.0,
- "run_id": handle.run_id,
- "scope_id": f"scope-{handle.run_id}",
- }
- source = SourceRef(framework=self.runtime_type)
- yield RunStarted(event_id="e1", seq=1, status="running", source=source, **common)
- for seq, item_id in ((2, "msg-a"), (3, "msg-b")):
- yield ItemCompleted(
- event_id=f"e{seq}",
- seq=seq,
- item_id=item_id,
- item_kind="message",
- snapshot=ContentSnapshot(
- parts=(TextContent(part_id=f"{item_id}-text", text="same"),)
- ),
- source=source,
- **common,
- )
- yield RunCompleted(
- event_id="e4",
- seq=4,
- status="completed",
- output_refs=(
- OutputRef(
- scope_id=common["scope_id"],
- item_id="msg-a",
- part_id="msg-a-text",
- ),
- OutputRef(
- scope_id=common["scope_id"],
- item_id="msg-b",
- part_id="msg-b-text",
- ),
- ),
- source=source,
- **common,
- )
-
-
-class _GatedStreamingAdapter(_RecordingAdapter):
- def __init__(self, calls: list[tuple[str, Any]]) -> None:
- super().__init__(calls, "plugin")
- self.delta_consumed = asyncio.Event()
- self.release = asyncio.Event()
-
- async def stream(self, handle: RunHandle) -> AsyncIterator[RuntimeEvent]:
- common = {
- "schema_version": 2,
- "timestamp": 1.0,
- "run_id": handle.run_id,
- "scope_id": f"scope-{handle.run_id}",
- }
- source = SourceRef(framework="codex")
- yield RunStarted(event_id="e1", seq=1, status="running", source=source, **common)
- yield ItemStarted(
- event_id="e2",
- seq=2,
- item_id="msg-1",
- item_kind="message",
- phase="final_answer",
- source=source,
- **common,
- )
- yield ItemUpdated(
- event_id="e3",
- seq=3,
- item_id="msg-1",
- item_kind="message",
- op="append",
- update=TextContent(part_id="text-0", text="first chunk"),
- source=source,
- **common,
- )
- self.delta_consumed.set()
- await self.release.wait()
- yield ItemCompleted(
- event_id="e4",
- seq=4,
- item_id="msg-1",
- item_kind="message",
- snapshot=ContentSnapshot(
- parts=(TextContent(part_id="text-0", text="first chunk done"),)
- ),
- source=source,
- **common,
- )
- yield RunCompleted(
- event_id="e5",
- seq=5,
- status="completed",
- output_refs=(
- OutputRef(
- scope_id=common["scope_id"],
- item_id="msg-1",
- part_id="text-0",
- ),
- ),
- source=source,
- **common,
- )
-
-
-def test_kernel_route_is_used_only_for_its_bound_studio_runtime(
- tmp_path: Path, monkeypatch: pytest.MonkeyPatch
-) -> None:
- """An enabled Kernel must not silently execute a different Studio Build."""
-
- from ksadk.kernel import bootstrap as kernel_bootstrap
- from ksadk.kernel import ingress as kernel_ingress
-
- active_context = RuntimeLaunchContext(runtime_type="codex", project_dir=tmp_path)
- runtime = SimpleNamespace(
- config=SimpleNamespace(
- launch_context=active_context,
- agent_instance_id="instance-codex",
- start_request_defaults={"agent_id": "sales-helper"},
- )
- )
- monkeypatch.setattr(kernel_ingress, "kernel_route_active", lambda: True)
- monkeypatch.setattr(kernel_bootstrap, "get_agent_kernel_runtime", lambda: runtime)
-
- matching = StudioRunSpec(
- launch_context=RuntimeLaunchContext(runtime_type="codex", project_dir=tmp_path),
- build_id="build-codex",
- agent_id="sales-helper",
- )
- assert StudioRunService._kernel_runtime_for_spec(matching) is runtime
-
- other_agent = StudioRunSpec(
- launch_context=RuntimeLaunchContext(runtime_type="codex", project_dir=tmp_path),
- build_id="build-other",
- agent_id="research-helper",
- )
- assert StudioRunService._kernel_runtime_for_spec(other_agent) is None
-
- other_runtime = StudioRunSpec(
- launch_context=RuntimeLaunchContext(runtime_type="langgraph", project_dir=tmp_path),
- build_id="build-graph",
- agent_id="sales-helper",
- )
- assert StudioRunService._kernel_runtime_for_spec(other_runtime) is None
-
-
-@pytest.mark.asyncio
-async def test_studio_run_service_uses_core_executor_and_persists_runtime_events(
- tmp_path: Path,
-) -> None:
- calls: list[tuple[str, Any]] = []
- registry = RuntimeRegistry()
- registry.register("langgraph", lambda _context: _RecordingAdapter(calls))
- workspace = Workspace(tmp_path)
- workspace.initialize()
- service = StudioRunService(workspace, RuntimeExecutor(registry))
-
- record = await service.run(
- StudioRunSpec(
- launch_context=RuntimeLaunchContext(
- runtime_type="langgraph",
- project_dir=tmp_path,
- ),
- build_id="build-lg",
- agent_id="review-helper",
- model="glm-5.2",
- request_config={"entrypoint": "agent:graph"},
- ),
- "review src/demo.py",
- session_id="ses-lg",
- )
-
- assert record.output == "langgraph answer"
- assert record.runtime_type == "langgraph"
- assert record.duration_ms == 42
- assert record.duration_source == "runtime"
- assert record.runtime_handle == {
- "run_id": "native-langgraph",
- "session_id": "ses-lg",
- "runtime_type": "langgraph",
- "native_ref": {"thread_id": "thread-1"},
- }
- assert [name for name, _value in calls] == ["start", "stream", "close"]
- request = calls[0][1]
- assert request.model == "glm-5.2"
- assert request.config == {"entrypoint": "agent:graph"}
- assert [event.type for event in service.event_store.events(record.id)] == [
- "run.created",
- "run.started",
- "message.completed",
- "run.completed",
- ]
- canonical = await service.runtime_events.list("ses-lg")
- assert [event.event_type for event in canonical] == [
- "run.started",
- "item.completed",
- "run.completed",
- ]
- assert [event.seq for event in canonical] == [1, 2, 3]
- assert {event.run_id for event in canonical} == {"native-langgraph"}
-
-
-@pytest.mark.asyncio
-async def test_harness_runtime_keeps_private_deltas_out_of_run_timeline(tmp_path: Path) -> None:
- class _HarnessDeltaAdapter(_RecordingAdapter):
- async def stream(self, handle: RunHandle) -> AsyncIterator[RuntimeEvent]:
- async for event in super().stream(handle):
- yield event
- if isinstance(event, RunStarted):
- yield ItemCompleted(
- schema_version=2,
- event_id="private-reasoning-delta",
- seq=0,
- timestamp=1.0,
- run_id=handle.run_id,
- scope_id=f"scope-{handle.run_id}",
- item_id="private-status",
- item_kind="status",
- snapshot=ContentSnapshot(
- parts=(
- TextContent(
- part_id="status-0",
- text=(
- '{"event":"reasoning.delta",'
- '"details":{"text":"private"}}'
- ),
- ),
- )
- ),
- source=SourceRef(
- framework="ksadk",
- metadata={"native_event_type": "reasoning.delta"},
- ),
- )
-
- registry = RuntimeRegistry()
- registry.register("harness", lambda _context: _HarnessDeltaAdapter([], "harness"))
- workspace = Workspace(tmp_path)
- workspace.initialize()
- service = StudioRunService(workspace, RuntimeExecutor(registry))
-
- record = await service.run(
- StudioRunSpec(
- launch_context=RuntimeLaunchContext(runtime_type="harness", project_dir=tmp_path),
- build_id="build-harness-delta",
- agent_id="harness-delta-agent",
- ),
- "run",
- )
-
- assert record.status == RunStatus.COMPLETED
- public_event_ids = {
- event.data.get("runtimeEvent", {}).get("event_id")
- for event in service.event_store.events(record.id)
- }
- assert "private-reasoning-delta" not in public_event_ids
- canonical = await service.runtime_events.list(record.session_id)
- assert "private-reasoning-delta" not in {event.event_id for event in canonical}
-
-
-@pytest.mark.asyncio
-async def test_plugin_provider_runtime_adapter_publishes_deltas_before_completion(
- tmp_path: Path,
-) -> None:
- calls: list[tuple[str, Any]] = []
- adapter = _GatedStreamingAdapter(calls)
-
- class PluginRuntime:
- def kernel_adapter_provider(self, _spec: StudioRunSpec):
- return lambda: adapter
-
- async def execute(self, *_args: Any, **_kwargs: Any):
- raise AssertionError("runtime-adapter providers must not use buffered execute()")
-
- workspace = Workspace(tmp_path)
- workspace.initialize()
- service = StudioRunService(
- workspace,
- RuntimeExecutor(RuntimeRegistry()),
- plugin_runtime=PluginRuntime(),
- )
- observed: list[str] = []
- task = asyncio.create_task(
- service.run(
- StudioRunSpec(
- launch_context=RuntimeLaunchContext(
- runtime_type="plugin",
- project_dir=tmp_path,
- ),
- build_id="build-plugin-codex",
- agent_id="plugin-codex-agent",
- model="fixture-model",
- request_config={"provider_runtime_adapter": True},
- plugin_bundle_root=tmp_path,
- ),
- "stream this",
- session_id="ses-plugin-stream",
- on_event=lambda event: observed.append(event.type),
- )
- )
-
- await asyncio.wait_for(adapter.delta_consumed.wait(), timeout=1)
- assert "message.delta" in observed
- assert not task.done()
- adapter.release.set()
- record = await asyncio.wait_for(task, timeout=1)
-
- assert record.status == RunStatus.COMPLETED
- assert record.output == "first chunk done"
-
-
-@pytest.mark.asyncio
-async def test_terminal_output_preserves_identity_distinct_message_items(
- tmp_path: Path,
-) -> None:
- registry = RuntimeRegistry()
- registry.register("codex", lambda _context: _MultiMessageAdapter([], "codex"))
- workspace = Workspace(tmp_path)
- workspace.initialize()
- service = StudioRunService(workspace, RuntimeExecutor(registry))
-
- record = await service.run(
- StudioRunSpec(
- launch_context=RuntimeLaunchContext(
- runtime_type="codex",
- project_dir=tmp_path,
- ),
- build_id="build-multi-message",
- agent_id="multi-message-agent",
- ),
- "keep both outputs",
- )
-
- assert record.output == "same\n\nsame"
-
-
-@pytest.mark.asyncio
-async def test_second_turn_receives_transport_neutral_session_history(
- tmp_path: Path,
-) -> None:
- calls: list[tuple[str, Any]] = []
- registry = RuntimeRegistry()
- registry.register("codex", lambda _context: _RecordingAdapter(calls, "codex"))
- workspace = Workspace(tmp_path)
- workspace.initialize()
- service = StudioRunService(workspace, RuntimeExecutor(registry))
- spec = StudioRunSpec(
- launch_context=RuntimeLaunchContext(
- runtime_type="codex",
- project_dir=tmp_path,
- ),
- build_id="build-codex",
- agent_id="review-helper",
- )
-
- await service.run(spec, "第一轮", session_id="ses-codex")
- await service.run(spec, "第二轮", session_id="ses-codex")
-
- starts = [value for name, value in calls if name == "start"]
- conversation = starts[1].conversation_preprocessing()
- assert conversation is not None
- assert conversation.messages == [
- {"role": "user", "content": "第一轮"},
- {"role": "assistant", "content": "codex answer"},
- {"role": "user", "content": "第二轮"},
- ]
- assert starts[1].metadata["thread_id"] == "thread-1"
-
-
-@pytest.mark.asyncio
-async def test_harness_followup_receives_verified_child_lifecycle_summary(
- tmp_path: Path,
-) -> None:
- calls: list[tuple[str, Any]] = []
- registry = RuntimeRegistry()
- registry.register("harness", lambda _context: _RecordingAdapter(calls, "harness"))
- workspace = Workspace(tmp_path)
- workspace.initialize()
- service = StudioRunService(workspace, RuntimeExecutor(registry))
- spec = StudioRunSpec(
- launch_context=RuntimeLaunchContext(runtime_type="harness", project_dir=tmp_path),
- build_id="build-harness",
- agent_id="research-helper",
- )
-
- first = await service.run(spec, "并行调研", session_id="ses-harness")
- assert first.status == RunStatus.COMPLETED, first.error
- assert first.runtime_type == "harness"
- service.event_store.append(
- first.id,
- "item.completed",
- {
- "runtimeEvent": {
- "event_id": "child-terminal",
- "run_id": first.runtime_handle["run_id"],
- "item_kind": "status",
- "source": {
- "native_run_id": first.runtime_handle["run_id"],
- "metadata": {"session_id": "ses-harness"},
- },
- "snapshot": {
- "parts": [
- {
- "type": "text",
- "part_id": "text-0",
- "text": json.dumps(
- {
- "event": "run.progress",
- "details": {
- "kind": "subagent.event",
- "call_id": "research-one",
- "label": "调研主题一",
- "status": "succeeded",
- },
- },
- ensure_ascii=False,
- ),
- }
- ]
- },
- }
- },
- )
-
- await service.run(spec, "进展如何?", session_id="ses-harness")
-
- starts = [value for name, value in calls if name == "start"]
- conversation = starts[1].conversation_preprocessing()
- assert conversation is not None
- assert conversation.messages[-3:] == [
- {"role": "user", "content": "并行调研"},
- {
- "role": "assistant",
- "content": (
- "harness answer\n\n"
- "[Harness 执行记录] 子智能体“调研主题一”已完成。"
- ),
- },
- {"role": "user", "content": "进展如何?"},
- ]
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize("stale_resume", [False, True])
-async def test_codex_build_change_starts_fresh_native_thread_with_session_history(
- tmp_path: Path,
- stale_resume: bool,
-) -> None:
- calls: list[tuple[str, Any]] = []
- registry = RuntimeRegistry()
- registry.register("codex", lambda _context: _RecordingAdapter(calls, "codex"))
- workspace = Workspace(tmp_path)
- workspace.initialize()
- service = StudioRunService(workspace, RuntimeExecutor(registry))
- for build_id, prompt in [("before-plugin", "第一轮"), ("with-plugin", "使用 Figma")]:
- if build_id == "with-plugin" and stale_resume:
- # Old Studio versions persisted the old thread under a new build
- # even when its rollout could not be resumed there.
- old = service.event_store.list_runs(session_id="ses-plugin-update")[0]
- failed = old.model_copy(
- update={
- "id": "run_failed_migration",
- "build_id": build_id,
- "status": RunStatus.FAILED,
- "started_at": datetime.now(timezone.utc),
- }
- )
- service.event_store.create(failed)
- await service.run(
- StudioRunSpec(
- launch_context=RuntimeLaunchContext(runtime_type="codex", project_dir=tmp_path),
- build_id=build_id,
- agent_id="review-helper",
- ),
- prompt,
- session_id="ses-plugin-update",
- )
-
- starts = [value for name, value in calls if name == "start"]
- # Build homes contain distinct plugin snapshots and native rollout stores.
- assert "thread_id" not in starts[1].metadata
- conversation = starts[1].conversation_preprocessing()
- assert conversation is not None
- assert conversation.messages == [
- {"role": "user", "content": "第一轮"},
- {"role": "assistant", "content": "codex answer"},
- {"role": "user", "content": "使用 Figma"},
- ]
-
-
-@pytest.mark.asyncio
-async def test_codex_feedback_turn_reuses_native_thread_after_cancelled_approval(
- tmp_path: Path,
-) -> None:
- calls: list[tuple[str, Any]] = []
- registry = RuntimeRegistry()
- registry.register("codex", lambda _context: _RecordingAdapter(calls, "codex"))
- workspace = Workspace(tmp_path)
- workspace.initialize()
- service = StudioRunService(workspace, RuntimeExecutor(registry))
- spec = StudioRunSpec(
- launch_context=RuntimeLaunchContext(runtime_type="codex", project_dir=tmp_path),
- build_id="build-codex",
- agent_id="review-helper",
- )
-
- cancelled = await service.run(spec, "执行原命令", session_id="ses-feedback")
- cancelled.status = RunStatus.CANCELLED
- service.event_store.save(cancelled)
- await service.run(spec, "请改成 echo 你好", session_id="ses-feedback")
-
- starts = [value for name, value in calls if name == "start"]
- assert starts[1].metadata["thread_id"] == "thread-1"
- conversation = starts[1].conversation_preprocessing()
- assert conversation is not None
- assert conversation.messages == [{"role": "user", "content": "请改成 echo 你好"}]
-
-
-@pytest.mark.asyncio
-async def test_structured_runtime_input_is_separate_from_persisted_display_text(
- tmp_path: Path,
-) -> None:
- calls: list[tuple[str, Any]] = []
- registry = RuntimeRegistry()
- registry.register("codex", lambda _context: _RecordingAdapter(calls, "codex"))
- workspace = Workspace(tmp_path)
- workspace.initialize()
- service = StudioRunService(workspace, RuntimeExecutor(registry))
- spec = StudioRunSpec(
- launch_context=RuntimeLaunchContext(runtime_type="codex", project_dir=tmp_path),
- build_id="build-codex",
- agent_id="review-helper",
- )
- structured = [
- {"type": "text", "text": "分析图片"},
- {"type": "image", "url": "data:image/png;base64,AAAA"},
- ]
-
- record = await service.run(
- spec,
- "分析图片",
- runtime_input=structured,
- session_id="ses-attachment",
- )
-
- request = next(value for name, value in calls if name == "start")
- assert record.input == "分析图片"
- assert request.input == structured
-
-
-@pytest.mark.asyncio
-async def test_run_persists_plan_and_goal_context_for_refresh_recovery(
- tmp_path: Path,
-) -> None:
- calls: list[tuple[str, Any]] = []
- registry = RuntimeRegistry()
- registry.register("codex", lambda _context: _RecordingAdapter(calls, "codex"))
- workspace = Workspace(tmp_path)
- workspace.initialize()
- service = StudioRunService(workspace, RuntimeExecutor(registry))
-
- record = await service.run(
- StudioRunSpec(
- launch_context=RuntimeLaunchContext(runtime_type="codex", project_dir=tmp_path),
- build_id="build-codex",
- agent_id="review-helper",
- request_config={
- "collaboration_mode": "plan",
- "goal_objective": "完成 Studio 交互重构",
- },
- ),
- "完成 Studio 交互重构",
- session_id="ses-goal",
- )
-
- assert record.collaboration_mode == "plan"
- assert record.goal_objective == "完成 Studio 交互重构"
- persisted = service.event_store.get(record.id)
- assert persisted.collaboration_mode == "plan"
- assert persisted.goal_objective == "完成 Studio 交互重构"
-
-
-@pytest.mark.asyncio
-async def test_runtime_reported_usage_and_duration_are_authoritative(
- tmp_path: Path,
-) -> None:
- class _MetricsAdapter(_RecordingAdapter):
- async def stream(self, handle: RunHandle) -> AsyncIterator[RuntimeEvent]:
- common = {
- "schema_version": 2,
- "timestamp": 1.0,
- "run_id": handle.run_id,
- "scope_id": f"scope-{handle.run_id}",
- }
- source = SourceRef(framework="codex")
- yield UsageReported(
- event_id="e1",
- seq=1,
- input_tokens=128,
- cached_tokens=16,
- output_tokens=32,
- reasoning_tokens=8,
- total_tokens=160,
- source=source,
- **common,
- )
- yield RunCompleted(
- event_id="e2",
- seq=2,
- status="completed",
- output_refs=(),
- source=SourceRef(
- framework="codex",
- metadata={"duration_ms": 1340},
- ),
- **common,
- )
-
- registry = RuntimeRegistry()
- registry.register("codex", lambda _context: _MetricsAdapter([], "codex"))
- workspace = Workspace(tmp_path)
- workspace.initialize()
- service = StudioRunService(workspace, RuntimeExecutor(registry))
-
- record = await service.run(
- StudioRunSpec(
- launch_context=RuntimeLaunchContext(
- runtime_type="codex",
- project_dir=tmp_path,
- ),
- build_id="build-codex",
- agent_id="review-helper",
- model="glm-5.2",
- ),
- "review",
- session_id="ses-metrics",
- )
-
- assert record.usage.model_dump(by_alias=True) == {
- "inputTokens": 128,
- "outputTokens": 32,
- "totalTokens": 160,
- "cachedInputTokens": 16,
- "reasoningOutputTokens": 8,
- "reported": True,
- "source": "codex",
- }
- assert record.duration_ms == 1340
- assert record.duration_source == "runtime"
-
-
-@pytest.mark.asyncio
-async def test_explicit_operation_cancellation_calls_executor_cancel_and_persists_terminal(
- tmp_path: Path,
-) -> None:
- class _BlockingAdapter(_RecordingAdapter):
- async def stream(self, handle: RunHandle) -> AsyncIterator[RuntimeEvent]:
- yield RunStarted(
- event_id="e1",
- seq=1,
- status="running",
- schema_version=2,
- timestamp=1.0,
- run_id=handle.run_id,
- scope_id=f"scope-{handle.run_id}",
- source=SourceRef(framework="codex"),
- )
- await asyncio.Event().wait()
-
- calls: list[tuple[str, Any]] = []
- registry = RuntimeRegistry()
- registry.register("codex", lambda _context: _BlockingAdapter(calls, "codex"))
- workspace = Workspace(tmp_path)
- workspace.initialize()
- service = StudioRunService(workspace, RuntimeExecutor(registry))
- task = asyncio.create_task(
- service.run(
- StudioRunSpec(
- launch_context=RuntimeLaunchContext(
- runtime_type="codex",
- project_dir=tmp_path,
- ),
- build_id="build-codex",
- agent_id="review-helper",
- ),
- "分析代码库",
- session_id="ses-cancel",
- )
- )
- await asyncio.sleep(0.02)
-
- task.cancel()
- with pytest.raises(asyncio.CancelledError):
- await task
-
- record = service.event_store.list_runs(session_id="ses-cancel")[0]
- assert record.status == "CANCELLED"
- assert record.completed_at is not None
- assert service.event_store.events(record.id)[-1].type == "run.cancelled"
- assert [name for name, _value in calls][-2:] == ["cancel", "close"]
-
-
-@pytest.mark.asyncio
-async def test_cancel_request_is_bounded_when_runtime_interrupt_stalls(
- tmp_path: Path,
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- import ksadk.studio.run_service as run_service_module
-
- class _StalledCancelAdapter(_RecordingAdapter):
- async def stream(self, handle: RunHandle) -> AsyncIterator[RuntimeEvent]:
- yield RunStarted(
- event_id="e1",
- seq=1,
- status="running",
- schema_version=2,
- timestamp=1.0,
- run_id=handle.run_id,
- scope_id=f"scope-{handle.run_id}",
- source=SourceRef(framework="codex"),
- )
- await asyncio.Event().wait()
-
- async def cancel(self, handle: RunHandle) -> CancelResult:
- await asyncio.Event().wait()
- return CancelResult.INTERRUPTED_ACTIVE_TURN
-
- monkeypatch.setattr(run_service_module, "_CANCEL_TIMEOUT_SECONDS", 0.02)
- calls: list[tuple[str, Any]] = []
- registry = RuntimeRegistry()
- registry.register("codex", lambda _context: _StalledCancelAdapter(calls, "codex"))
- workspace = Workspace(tmp_path)
- workspace.initialize()
- service = StudioRunService(workspace, RuntimeExecutor(registry))
- task = asyncio.create_task(
- service.run(
- StudioRunSpec(
- launch_context=RuntimeLaunchContext(runtime_type="codex", project_dir=tmp_path),
- build_id="build-codex",
- agent_id="review-helper",
- ),
- "等待输入",
- session_id="ses-stalled-cancel",
- )
- )
- await asyncio.sleep(0.02)
- run_id = service.event_store.list_runs(session_id="ses-stalled-cancel")[0].id
-
- result = await asyncio.wait_for(service.cancel_run(run_id), timeout=0.2)
-
- assert result == {"runId": run_id, "status": "cancelling"}
- task.cancel()
- with pytest.raises(asyncio.CancelledError):
- await task
-
-
-@pytest.mark.asyncio
-async def test_runtime_interruption_is_not_reported_as_user_cancellation(
- tmp_path: Path,
-) -> None:
- class _InterruptedAdapter(_RecordingAdapter):
- async def stream(self, handle: RunHandle) -> AsyncIterator[RuntimeEvent]:
- yield RunInterrupted(
- event_id="e1",
- seq=1,
- status="interrupted",
- reason="attach_unavailable",
- schema_version=2,
- timestamp=1.0,
- run_id=handle.run_id,
- scope_id=f"scope-{handle.run_id}",
- source=SourceRef(framework="codex"),
- )
-
- calls: list[tuple[str, Any]] = []
- registry = RuntimeRegistry()
- registry.register("codex", lambda _context: _InterruptedAdapter(calls, "codex"))
- workspace = Workspace(tmp_path)
- workspace.initialize()
-
- record = await StudioRunService(workspace, RuntimeExecutor(registry)).run(
- StudioRunSpec(
- launch_context=RuntimeLaunchContext(
- runtime_type="codex",
- project_dir=tmp_path,
- ),
- build_id="build-codex",
- agent_id="review-helper",
- ),
- "继续运行",
- session_id="ses-interrupted",
- )
-
- assert record.status == "INTERRUPTED"
- assert record.error == {
- "code": "RUN_INTERRUPTED",
- "message": "attach_unavailable",
- }
- assert service_event_types(workspace, record.id)[-1] == "run.interrupted"
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize(
- ("runtime_type", "pause_reason"),
- [("codex", "user_pause"), ("harness", "paused")],
-)
-async def test_pause_preserves_run_and_resume_continues_same_runtime_handle(
- tmp_path: Path,
- runtime_type: str,
- pause_reason: str,
-) -> None:
- running = asyncio.Event()
- paused = asyncio.Event()
-
- class _PausableAdapter(_RecordingAdapter):
- def __init__(self, calls: list[tuple[str, Any]]) -> None:
- super().__init__(calls, runtime_type)
- self.turn = 0
- self.interrupt = asyncio.Event()
-
- async def stream(self, handle: RunHandle) -> AsyncIterator[RuntimeEvent]:
- self.turn += 1
- common = {
- "schema_version": 2,
- "timestamp": 1.0,
- "run_id": handle.run_id,
- "scope_id": f"scope-{handle.run_id}",
- }
- source = SourceRef(
- framework="codex" if runtime_type == "codex" else "ksadk",
- metadata={"engine_kind": "native"} if runtime_type == "harness" else {},
- )
- yield RunStarted(
- event_id=f"e{self.turn}0",
- seq=self.turn * 10,
- status="running",
- source=source,
- **common,
- )
- if self.turn == 1:
- # Resuming this iterator proves RunStarted was consumed; a
- # fixed startup sleep does not synchronize the persisted state.
- running.set()
- await self.interrupt.wait()
- yield RunInterrupted(
- event_id=f"e{self.turn}1",
- seq=self.turn * 10 + 1,
- status="interrupted",
- reason=pause_reason,
- source=source,
- **common,
- )
- return
- yield ItemCompleted(
- event_id=f"e{self.turn}1",
- seq=self.turn * 10 + 1,
- item_id="msg-1",
- item_kind="message",
- snapshot=ContentSnapshot(
- parts=(
- TextContent(
- part_id="text-0",
- text="resumed answer",
- ),
- )
- ),
- source=source,
- **common,
- )
- yield RunCompleted(
- event_id=f"e{self.turn}2",
- seq=self.turn * 10 + 2,
- status="completed",
- output_refs=(
- OutputRef(
- scope_id=common["scope_id"],
- item_id="msg-1",
- part_id="text-0",
- ),
- ),
- source=source,
- **common,
- )
-
- async def pause(self, handle: RunHandle) -> PauseResult:
- self.calls.append(("pause", handle))
- self.interrupt.set()
- return PauseResult.PAUSED_ACTIVE_TURN
-
- async def resume(self, handle, target, payload):
- self.calls.append(("resume", (handle, target, payload)))
- return handle
-
- calls: list[tuple[str, Any]] = []
- registry = RuntimeRegistry()
- registry.register(runtime_type, lambda _context: _PausableAdapter(calls))
- workspace = Workspace(tmp_path)
- workspace.initialize()
- service = StudioRunService(workspace, RuntimeExecutor(registry))
-
- def on_event(event):
- if event.type == "run.paused":
- paused.set()
-
- task = asyncio.create_task(
- service.run(
- StudioRunSpec(
- launch_context=RuntimeLaunchContext(
- runtime_type=runtime_type, project_dir=tmp_path
- ),
- build_id="build-codex",
- agent_id="review-helper",
- ),
- "分析代码库",
- session_id="ses-pause",
- on_event=on_event,
- )
- )
- await asyncio.wait_for(running.wait(), timeout=2)
- run = service.event_store.list_runs(session_id="ses-pause")[0]
-
- assert await service.pause_run(run.id) == {"runId": run.id, "status": "pausing"}
- await asyncio.wait_for(paused.wait(), timeout=2)
- assert service.event_store.get(run.id).status == RunStatus.PAUSED
- assert not task.done()
-
- assert await service.resume_run(run.id) == {"runId": run.id, "status": "resuming"}
- record = await asyncio.wait_for(task, timeout=2)
- assert record.status == RunStatus.COMPLETED
- assert record.output == "resumed answer"
- assert [event.type for event in service.event_store.events(record.id)].count("run.paused") == 1
- assert "run.resumed" in [event.type for event in service.event_store.events(record.id)]
- assert [name for name, _ in calls] == ["start", "pause", "resume", "close"]
- resumed = next(value for name, value in calls if name == "resume")
- assert resumed[0].run_id == run.runtime_handle["run_id"]
- assert resumed[2] is None # Continue the paused task without a synthetic user message.
-
-
-@pytest.mark.asyncio
-async def test_live_a2ui_interaction_submits_structured_answer_and_continues(
- tmp_path: Path,
-) -> None:
- class _InteractiveAdapter(_RecordingAdapter):
- def __init__(self, calls: list[tuple[str, Any]]) -> None:
- super().__init__(calls, "codex")
- self.answered = asyncio.Event()
-
- async def stream(self, handle: RunHandle) -> AsyncIterator[RuntimeEvent]:
- common = {
- "schema_version": 2,
- "timestamp": 1.0,
- "run_id": handle.run_id,
- "scope_id": f"scope-{handle.run_id}",
- }
- source = SourceRef(framework="codex")
- yield ItemStarted(
- event_id="e1",
- seq=1,
- item_id="surface-1",
- item_kind="data",
- initial=ContentSnapshot(
- parts=(
- DataContent(
- part_id="data-0",
- data={
- "surface_id": "surface-1",
- "surface": {
- "components": [
- {
- "id": "scope",
- "component": "CheckboxGroup",
- "name": "scope",
- "options": ["前端", "服务端"],
- }
- ]
- },
- },
- ),
- )
- ),
- source=SourceRef(
- framework="codex",
- protocol="a2ui",
- metadata={"surface_id": "surface-1"},
- ),
- **common,
- )
- yield InteractionRequested(
- event_id="e2",
- seq=2,
- interaction_id="question-1",
- interaction_kind="structured_input",
- request=StructuredInputRequest(
- prompt="检查范围",
- schema={
- "type": "object",
- "properties": {"scope": {"type": "array", "minItems": 1}},
- "required": ["scope"],
- },
- ),
- source=source,
- **common,
- )
- await self.answered.wait()
- yield ItemCompleted(
- event_id="e3",
- seq=3,
- item_id="msg-1",
- item_kind="message",
- snapshot=ContentSnapshot(
- parts=(
- TextContent(
- part_id="text-0",
- text="已按选择继续",
- ),
- )
- ),
- source=source,
- **common,
- )
- yield RunCompleted(
- event_id="e4",
- seq=4,
- status="completed",
- output_refs=(
- OutputRef(
- scope_id=common["scope_id"],
- item_id="msg-1",
- part_id="text-0",
- ),
- ),
- source=source,
- **common,
- )
-
- async def submit(self, handle: RunHandle, payload: ResumePayload) -> None:
- self.calls.append(("submit", payload))
- if payload.data.get("note") == "provider-failure":
- raise RuntimeError("provider rejected interaction")
- self.answered.set()
-
- calls: list[tuple[str, Any]] = []
- registry = RuntimeRegistry()
- registry.register("codex", lambda _context: _InteractiveAdapter(calls))
- workspace = Workspace(tmp_path)
- workspace.initialize()
- service = StudioRunService(workspace, RuntimeExecutor(registry))
- task = asyncio.create_task(
- service.run(
- StudioRunSpec(
- launch_context=RuntimeLaunchContext(runtime_type="codex", project_dir=tmp_path),
- build_id="build-codex",
- agent_id="review-helper",
- ),
- "检查项目",
- session_id="ses-interaction",
- )
- )
- async with asyncio.timeout(5):
- while True:
- if task.done():
- await task # Surface a real startup failure instead of timing out.
- pytest.fail("Run finished before requesting input")
- runs = service.event_store.list_runs(session_id="ses-interaction")
- if runs and runs[0].status == RunStatus.WAITING_INPUT:
- run = runs[0]
- break
- await asyncio.sleep(0.01)
- assert run.status == RunStatus.WAITING_INPUT
-
- with pytest.raises(StudioError) as stale:
- await service.submit_interaction(
- run.id,
- "question-1",
- name="submit",
- data={},
- expected_revision=2,
- idempotency_key="interaction:question-1:stale",
- )
- assert stale.value.code == "INTERACTION_REVISION_MISMATCH"
-
- with pytest.raises(StudioError) as empty_answer:
- await service.submit_interaction(
- run.id,
- "question-1",
- name="submit",
- data={},
- expected_revision=1,
- idempotency_key="empty-answer",
- )
- assert empty_answer.value.code == "INTERACTION_RESPONSE_INVALID"
- assert service.event_store.get(run.id).status == RunStatus.WAITING_INPUT
-
- with pytest.raises(StudioError) as provider_failure:
- await service.submit_interaction(
- run.id,
- "question-1",
- name="submit",
- data={"scope": ["前端"], "note": "provider-failure"},
- expected_revision=1,
- idempotency_key="interaction:question-1:provider-failure",
- )
- assert provider_failure.value.code == "INTERACTION_SUBMIT_FAILED"
- assert not any(event.type == "a2ui.action" for event in service.event_store.events(run.id))
-
- request = {
- "name": "submit",
- "data": {"scope": ["前端", "服务端"], "note": "忽略生成文件"},
- "expected_revision": 1,
- "idempotency_key": "interaction:question-1:revision-1",
- }
- first, replay = await asyncio.gather(
- service.submit_interaction(run.id, "question-1", **request),
- service.submit_interaction(run.id, "question-1", **request),
- )
- assert first == replay
- assert first["status"] == "resolved"
- assert first["revision"] == 2
-
- with pytest.raises(StudioError) as replay_conflict:
- await service.submit_interaction(
- run.id,
- "question-1",
- name="submit",
- data={"scope": ["后端"]},
- expected_revision=1,
- idempotency_key="interaction:question-1:revision-1",
- )
- assert replay_conflict.value.code == "INTERACTION_IDEMPOTENCY_CONFLICT"
-
- with pytest.raises(StudioError) as already_resolved:
- await service.submit_interaction(
- run.id,
- "question-1",
- name="submit",
- data=request["data"],
- expected_revision=1,
- idempotency_key="interaction:question-1:other-attempt",
- )
- assert already_resolved.value.code == "INTERACTION_ALREADY_RESOLVED"
- completed = await asyncio.wait_for(task, timeout=2)
- assert completed.status == RunStatus.COMPLETED
- assert completed.output == "已按选择继续"
- submitted = [value for name, value in calls if name == "submit"][-1]
- assert submitted.kind == "hitl_answer"
- assert submitted.call_id == "question-1"
- assert submitted.data == {
- "decision": "submit",
- "scope": ["前端", "服务端"],
- "note": "忽略生成文件",
- }
- assert [name for name, _ in calls].count("submit") == 2
- assert "a2ui.action" in service_event_types(workspace, run.id)
-
-
-@pytest.mark.parametrize(
- ("action", "response", "expected_decision", "expected_outcome", "expected_summary"),
- [
- ("approve", {}, "approve", "approved", "已同意"),
- ("reject", {"decision": "reject"}, "deny", "rejected", "已拒绝"),
- (
- "cancel",
- {"feedback": "请改成 echo 你好"},
- "cancel",
- "cancelled",
- "已反馈给 Agent",
- ),
- ],
-)
-@pytest.mark.asyncio
-async def test_live_approval_submits_with_native_provider_call_id(
- tmp_path: Path,
- action: str,
- response: dict[str, str],
- expected_decision: str,
- expected_outcome: str,
- expected_summary: str,
-) -> None:
- class _ApprovalAdapter(_RecordingAdapter):
- def __init__(self, calls: list[tuple[str, Any]]) -> None:
- super().__init__(calls, "codex")
- self.answered = asyncio.Event()
-
- async def stream(self, handle: RunHandle) -> AsyncIterator[RuntimeEvent]:
- common = {
- "schema_version": 2,
- "timestamp": 1.0,
- "run_id": handle.run_id,
- "scope_id": f"scope-{handle.run_id}",
- "source": SourceRef(framework="codex"),
- }
- yield InteractionRequested(
- event_id="approval-requested",
- seq=1,
- interaction_id="item-canonical-approval",
- interaction_kind="approval",
- request=ApprovalRequest(
- call_id="call-native-tool",
- kind="command_execution",
- detail={"command": "echo approval-ok"},
- ),
- **common,
- )
- yield RunInterrupted(
- event_id="approval-waiting",
- seq=2,
- status="interrupted",
- reason="Codex requires user interaction",
- interaction_id="item-canonical-approval",
- continuation_id="thread-1",
- **common,
- )
- await self.answered.wait()
- yield RunCompleted(
- event_id="approval-completed",
- seq=3,
- status="completed",
- output_refs=(),
- **common,
- )
-
- async def submit(self, handle: RunHandle, payload: ResumePayload) -> None:
- self.calls.append(("submit", payload))
- self.answered.set()
-
- calls: list[tuple[str, Any]] = []
- registry = RuntimeRegistry()
- registry.register("codex", lambda _context: _ApprovalAdapter(calls))
- workspace = Workspace(tmp_path)
- workspace.initialize()
- service = StudioRunService(workspace, RuntimeExecutor(registry))
- task = asyncio.create_task(
- service.run(
- StudioRunSpec(
- launch_context=RuntimeLaunchContext(
- runtime_type="codex",
- project_dir=tmp_path,
- ),
- build_id="build-codex",
- agent_id="approval-helper",
- ),
- "执行审批命令",
- session_id="ses-approval",
- )
- )
- for _ in range(30):
- await asyncio.sleep(0.01)
- run = service.event_store.list_runs(session_id="ses-approval")[0]
- if run.status == RunStatus.WAITING_INPUT:
- break
- assert run.status == RunStatus.WAITING_INPUT
-
- await service.submit_interaction(
- run.id,
- "item-canonical-approval",
- name=action,
- data=response,
- expected_revision=1,
- idempotency_key=f"interaction:item-canonical-approval:{action}:revision-1",
- )
- completed = await asyncio.wait_for(task, timeout=2)
- assert completed.status == RunStatus.COMPLETED
-
- submitted = [value for name, value in calls if name == "submit"][-1]
- assert submitted.kind == "approval_decision"
- assert submitted.call_id == "call-native-tool"
- assert submitted.data == {**response, "decision": expected_decision}
- resolved = next(
- event for event in service.event_store.events(run.id) if event.type == "approval.resolved"
- )
- assert resolved.data["interactionId"] == "item-canonical-approval"
- assert resolved.data["callId"] == "call-native-tool"
- assert resolved.data["action"] == action
- assert resolved.data["outcome"] == expected_outcome
- assert resolved.data["actor"] == "user"
- assert resolved.data["responseSummary"] == expected_summary
- assert [name for name, _ in calls].count("submit") == 1
- assert "a2ui.action" in service_event_types(workspace, run.id)
- assert "run.interrupted" not in service_event_types(workspace, run.id)
- assert service_event_types(workspace, run.id).count("approval.resolved") == 1
-
-
-@pytest.mark.asyncio
-async def test_terminal_run_expires_an_unresolved_approval_card(tmp_path: Path) -> None:
- class _FailingApprovalAdapter(_RecordingAdapter):
- async def stream(self, handle: RunHandle) -> AsyncIterator[RuntimeEvent]:
- common = {
- "schema_version": 2,
- "timestamp": 1.0,
- "run_id": handle.run_id,
- "scope_id": f"scope-{handle.run_id}",
- "source": SourceRef(framework="codex"),
- }
- yield InteractionRequested(
- event_id="approval-requested",
- seq=1,
- interaction_id="approval-orphan",
- interaction_kind="approval",
- request=ApprovalRequest(
- call_id="call-orphan",
- kind="command_execution",
- detail={"command": "echo never-ran"},
- ),
- **common,
- )
- yield RunFailed(
- event_id="approval-failed",
- seq=2,
- status="failed",
- error={
- "code": "RUNTIME_RUN_FAILED",
- "message": "transport closed",
- "source": "codex",
- "scope_id": handle.run_id,
- },
- **common,
- )
-
- registry = RuntimeRegistry()
- registry.register("codex", lambda _context: _FailingApprovalAdapter([], "codex"))
- workspace = Workspace(tmp_path)
- workspace.initialize()
- service = StudioRunService(workspace, RuntimeExecutor(registry))
-
- record = await service.run(
- StudioRunSpec(
- launch_context=RuntimeLaunchContext(runtime_type="codex", project_dir=tmp_path),
- build_id="build-codex",
- agent_id="approval-helper",
- ),
- "执行审批命令",
- session_id="ses-failed-approval",
- )
-
- assert record.status == RunStatus.FAILED
- expired = [
- event
- for event in service.event_store.events(record.id)
- if event.type == "interaction.expired"
- ]
- assert len(expired) == 1
- assert expired[0].data["interactionId"] == "approval-orphan"
- assert expired[0].data["callId"] == "call-orphan"
-
-
-def test_a2ui_runtime_events_are_persisted_as_official_operations() -> None:
- event_type, payload = project_runtime_event(
- ItemStarted(
- event_id="e1",
- seq=1,
- item_id="surface-1",
- item_kind="data",
- initial=ContentSnapshot(
- parts=(
- DataContent(
- part_id="data-0",
- data=[
- {
- "version": "v0.9",
- "createSurface": {
- "surfaceId": "surface-1",
- "catalogId": "catalog-1",
- },
- },
- {
- "version": "v0.9",
- "updateComponents": {
- "surfaceId": "surface-1",
- "components": [
- {"id": "root", "component": "Text", "text": "Hello"}
- ],
- },
- },
- {
- "version": "v0.9",
- "updateDataModel": {
- "surfaceId": "surface-1",
- "path": "/",
- "value": {"ready": True},
- },
- },
- ],
- ),
- )
- ),
- schema_version=2,
- timestamp=1.0,
- run_id="run-1",
- scope_id="scope-1",
- source=SourceRef(
- framework="ksadk",
- protocol="a2ui",
- metadata={"surface_id": "surface-1"},
- ),
- )
- )
- assert event_type == "a2ui.surface.begin"
- assert payload["surfaceId"] == "surface-1"
- assert [
- next(iter(operation.keys() - {"version"})) for operation in payload["a2uiOperations"]
- ] == [
- "createSurface",
- "updateComponents",
- "updateDataModel",
- ]
-
-
-def test_completed_a2ui_operation_batch_keeps_surface_visible() -> None:
- event_type, payload = project_runtime_event(
- ItemCompleted(
- event_id="e2",
- seq=2,
- item_id="surface-batch-1",
- item_kind="data",
- snapshot=ContentSnapshot(
- parts=(
- DataContent(
- part_id="a2ui-surface",
- data={
- "surface_id": "surface-1",
- "components": [{"id": "root", "component": "Text", "text": "Hello"}],
- },
- ),
- )
- ),
- schema_version=2,
- timestamp=2.0,
- run_id="run-1",
- scope_id="scope-1",
- source=SourceRef(
- framework="codex",
- protocol="a2ui",
- metadata={
- "surface_id": "surface-1",
- "operation_batch": True,
- "surface_lifecycle": "begin",
- },
- ),
- )
- )
-
- assert event_type == "a2ui.surface.begin"
- assert [
- next(iter(operation.keys() - {"version"})) for operation in payload["a2uiOperations"]
- ] == ["createSurface", "updateComponents"]
-
-
-def service_event_types(workspace: Workspace, run_id: str) -> list[str]:
- return [
- event.type
- for event in StudioRunService(
- workspace,
- RuntimeExecutor(RuntimeRegistry()),
- ).event_store.events(run_id)
- ]
-
-
-def test_generic_tool_events_project_normalized_fields() -> None:
- """MCP 等非命令工具事件必须投影出 tool/args/output,trace 层才能成 span。"""
- tool_args = {
- "server": "metaso-inner",
- "tool": "metaso_web_search",
- "arguments": {"q": "x"},
- }
- begin_type, begin_payload = project_runtime_event(
- ItemStarted(
- event_id="e1",
- seq=1,
- item_id="tool-mcp-1",
- item_kind="tool_call",
- initial=ContentSnapshot(
- parts=(
- ToolCallContent(
- part_id="tool-0",
- call_id="mcp-1",
- name="mcp.metaso-inner.metaso_web_search",
- arguments=tool_args,
- ),
- )
- ),
- schema_version=2,
- timestamp=1.0,
- run_id="run-1",
- scope_id="scope-1",
- source=SourceRef(framework="ksadk"),
- )
- )
- assert begin_type == "tool.started"
- assert begin_payload["callId"] == "mcp-1"
- assert begin_payload["tool"] == "mcp.metaso-inner.metaso_web_search"
- assert begin_payload["args"]["arguments"] == {"q": "x"}
- assert "runtimeEvent" in begin_payload
-
- end_type, end_payload = project_runtime_event(
- ItemCompleted(
- event_id="e2",
- seq=2,
- item_id="tool-mcp-1",
- item_kind="tool_call",
- snapshot=ContentSnapshot(
- parts=(
- ToolCallContent(
- part_id="tool-0",
- call_id="mcp-1",
- name="mcp.metaso-inner.metaso_web_search",
- arguments=tool_args,
- ),
- ToolResultContent(
- part_id="tool-0",
- call_id="mcp-1",
- result={"status": "completed", "duration_ms": 12, "output": "结果"},
- ),
- )
- ),
- schema_version=2,
- timestamp=1.0,
- run_id="run-1",
- scope_id="scope-1",
- source=SourceRef(framework="ksadk"),
- )
- )
- assert end_type == "tool.completed"
- assert end_payload["callId"] == "mcp-1"
- assert end_payload["tool"] == "mcp.metaso-inner.metaso_web_search"
- assert end_payload["status"] == "completed"
- assert end_payload["durationMs"] == 12
- assert end_payload["output"] == "结果"
-
-
-def test_generic_tool_error_marks_completed_event_failed() -> None:
- _, payload = project_runtime_event(
- ItemCompleted(
- event_id="e1",
- seq=1,
- item_id="tool-mcp-2",
- item_kind="tool_call",
- snapshot=ContentSnapshot(
- parts=(
- ToolCallContent(
- part_id="tool-0",
- call_id="mcp-2",
- name="mcp.metaso-inner.metaso_web_search",
- arguments={},
- ),
- ToolResultContent(
- part_id="tool-0",
- call_id="mcp-2",
- result={"status": "failed", "error": "boom", "output": "boom"},
- is_error=True,
- ),
- )
- ),
- schema_version=2,
- timestamp=1.0,
- run_id="run-1",
- scope_id="scope-1",
- source=SourceRef(framework="ksadk"),
- )
- )
- assert payload["status"] == "failed"
- assert payload["error"] == "boom"
-
-
-@pytest.mark.asyncio
-async def test_same_session_rejects_overlap_before_start_and_releases_on_cancel(tmp_path):
- calls = []
- entered = asyncio.Event()
- release = asyncio.Event()
-
- class BlockingAdapter(_RecordingAdapter):
- async def stream(self, handle):
- entered.set()
- await release.wait()
- async for event in super().stream(handle):
- yield event
-
- registry = RuntimeRegistry()
- registry.register("langgraph", lambda _: BlockingAdapter(calls))
- workspace = Workspace(tmp_path)
- workspace.initialize()
- service = StudioRunService(workspace, RuntimeExecutor(registry))
- spec = StudioRunSpec(
- launch_context=RuntimeLaunchContext(runtime_type="langgraph", project_dir=tmp_path),
- build_id="build",
- agent_id="agent",
- )
- first = asyncio.create_task(service.run(spec, "first", session_id="same"))
- await asyncio.wait_for(entered.wait(), 2)
- try:
- with pytest.raises(StudioError) as caught:
- await service.run(spec, "overlap", session_id="same")
- assert caught.value.code == "SESSION_RUN_ACTIVE"
- assert caught.value.status_code == 409
- assert len([c for c in calls if c[0] == "start"]) == 1
- finally:
- first.cancel()
- await asyncio.gather(first, return_exceptions=True)
- release.set()
- next_run = await service.run(spec, "next", session_id="same")
- assert next_run.status == RunStatus.COMPLETED
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize("cancel_first", [False, True])
-async def test_same_session_queued_followups_are_ordered_and_cancelable(
- tmp_path, cancel_first
-):
- calls = []
- entered = asyncio.Event()
- release = asyncio.Event()
-
- class BlockingAdapter(_RecordingAdapter):
- async def stream(self, handle):
- if not entered.is_set():
- entered.set()
- await release.wait()
- async for event in super().stream(handle):
- yield event
-
- registry = RuntimeRegistry()
- registry.register("langgraph", lambda _: BlockingAdapter(calls))
- workspace = Workspace(tmp_path)
- workspace.initialize()
- service = StudioRunService(workspace, RuntimeExecutor(registry))
- spec = StudioRunSpec(
- launch_context=RuntimeLaunchContext(runtime_type="langgraph", project_dir=tmp_path),
- build_id="build",
- agent_id="agent",
- )
- first = asyncio.create_task(service.run(spec, "first", session_id="same"))
- await asyncio.wait_for(entered.wait(), 2)
- canceled = asyncio.create_task(
- service.run(spec, "cancel-me", session_id="same", queue_if_active=True)
- )
- second = asyncio.create_task(
- service.run(spec, "second", session_id="same", queue_if_active=True)
- )
- third = asyncio.create_task(
- service.run(spec, "third", session_id="same", queue_if_active=True)
- )
- await asyncio.sleep(0)
- assert len([call for call in calls if call[0] == "start"]) == 1
- canceled.cancel()
- canceled_result = (await asyncio.gather(canceled, return_exceptions=True))[0]
- assert isinstance(canceled_result, asyncio.CancelledError)
- with pytest.raises(StudioError) as caught:
- await service.run(spec, "jump-ahead", session_id="same")
- assert caught.value.code == "SESSION_RUN_ACTIVE"
- if cancel_first:
- first.cancel()
- first_result = (await asyncio.gather(first, return_exceptions=True))[0]
- assert isinstance(first_result, asyncio.CancelledError)
- assert service.event_store.list_runs(session_id="same")[0].status == RunStatus.CANCELLED
- else:
- release.set()
- results = await asyncio.wait_for(asyncio.gather(second, third), 5)
- if not cancel_first:
- results.insert(0, await asyncio.wait_for(first, 5))
- assert all(result.status == RunStatus.COMPLETED for result in results)
- assert [call[1].input for call in calls if call[0] == "start"] == [
- "first",
- "second",
- "third",
- ]
- assert not service._session_turn_users
- assert not service._session_turn_locks
-
-
-@pytest.mark.asyncio
-async def test_same_session_followup_waits_while_tool_call_is_in_flight(tmp_path):
- calls = []
- tool_entered = asyncio.Event()
- tool_release = asyncio.Event()
-
- class ToolBlockedAdapter(_RecordingAdapter):
- async def stream(self, handle):
- parent = super().stream(handle)
- yield await anext(parent)
- blocked = not tool_entered.is_set()
- if blocked:
- common = {
- "schema_version": 2,
- "timestamp": 1.0,
- "run_id": handle.run_id,
- "scope_id": f"scope-{handle.run_id}",
- "source": SourceRef(framework="langgraph"),
- }
- yield ItemStarted(
- event_id="tool-started",
- seq=2,
- item_id="tool-1",
- item_kind="tool_call",
- initial=ContentSnapshot(
- parts=(
- ToolCallContent(
- part_id="tool-0",
- call_id="call-1",
- name="fixture.read",
- arguments={},
- ),
- )
- ),
- **common,
- )
- tool_entered.set()
- await tool_release.wait()
- yield ItemCompleted(
- event_id="tool-completed",
- seq=3,
- item_id="tool-1",
- item_kind="tool_call",
- snapshot=ContentSnapshot(
- parts=(
- ToolCallContent(
- part_id="tool-0",
- call_id="call-1",
- name="fixture.read",
- arguments={},
- ),
- ToolResultContent(
- part_id="result-0",
- call_id="call-1",
- result={"ok": True},
- ),
- )
- ),
- **common,
- )
- async for event in parent:
- yield event.model_copy(update={"seq": event.seq + 2}) if blocked else event
-
- registry = RuntimeRegistry()
- registry.register("langgraph", lambda _: ToolBlockedAdapter(calls))
- workspace = Workspace(tmp_path)
- workspace.initialize()
- service = StudioRunService(workspace, RuntimeExecutor(registry))
- spec = StudioRunSpec(
- launch_context=RuntimeLaunchContext(runtime_type="langgraph", project_dir=tmp_path),
- build_id="build",
- agent_id="agent",
- )
- first = asyncio.create_task(service.run(spec, "first", session_id="same"))
- await asyncio.wait_for(tool_entered.wait(), 2)
- second = asyncio.create_task(
- service.run(spec, "second", session_id="same", queue_if_active=True)
- )
- await asyncio.sleep(0)
- records = service.event_store.list_runs(session_id="same")
- assert len(records) == 1
- assert "tool.started" in service_event_types(workspace, records[0].id)
- assert len([call for call in calls if call[0] == "start"]) == 1
- tool_release.set()
- completed = await asyncio.wait_for(asyncio.gather(first, second), 5)
- assert all(record.status == RunStatus.COMPLETED for record in completed)
- assert [call[1].input for call in calls if call[0] == "start"] == ["first", "second"]
-
-
-def test_native_question_projection_preserves_schema_and_submit_identity():
- event = InteractionRequested(
- schema_version=2,
- event_id="question",
- seq=1,
- timestamp=1,
- run_id="run",
- scope_id="scope",
- interaction_id="canonical-question",
- interaction_kind="structured_input",
- request=StructuredInputRequest(
- prompt="选择范围",
- schema={
- "type": "object",
- "properties": {"scope": {"type": "string"}},
- "required": ["scope"],
- },
- ),
- source=SourceRef(framework="codex", native_event_id="native-question"),
- )
- _, data = project_runtime_event(event)
- assert data["inputSchema"]["required"] == ["scope"]
- assert data["callId"] == "native-question"
- assert data["message"] == "选择范围"
-
-
-@pytest.mark.asyncio
-async def test_plugin_run_streams_session_store_events_live_without_duplicates(
- tmp_path: Path,
-) -> None:
- """_plugin_run 必须在 execute 进行中转发 canonical 增量,且终局零重复。"""
-
- gate = asyncio.Event()
- service_holder: dict[str, Any] = {}
-
- class _LiveBufferedPluginRuntime:
- async def execute(self, _spec: StudioRunSpec, request: dict[str, Any], *, session_id: str):
- run_id = str(request["invocation_id"])
- store = service_holder["service"].runtime_events
- common = {
- "schema_version": 2,
- "timestamp": 1.0,
- "run_id": run_id,
- "scope_id": f"scope-{run_id}",
- "source": SourceRef(framework="ksadk"),
- }
- await store.append_one(
- session_id,
- RunStarted(event_id="live-e1", seq=0, status="running", **common),
- )
- await store.append_one(
- session_id,
- ItemStarted(
- event_id="live-e2",
- seq=0,
- item_id="msg-1",
- item_kind="message",
- phase="final_answer",
- initial=ContentSnapshot(parts=(TextContent(part_id="text-0", text="hel"),)),
- **common,
- ),
- )
- await store.append_one(
- session_id,
- ItemUpdated(
- event_id="live-e3",
- seq=0,
- item_id="msg-1",
- item_kind="message",
- op="append",
- update=TextContent(part_id="text-0", text="lo"),
- **common,
- ),
- )
- await store.append_one(
- session_id,
- ItemCompleted(
- event_id="live-private-child-delta",
- seq=0,
- item_id="private-status-1",
- item_kind="status",
- snapshot=ContentSnapshot(
- parts=(
- TextContent(
- part_id="status-0",
- text='{"event":"text.delta","details":{"text":"private"}}',
- ),
- )
- ),
- **{
- **common,
- "source": SourceRef(
- framework="ksadk",
- native_run_id=f"{run_id}:sub:child-1:child-1",
- metadata={
- "native_event_type": "text.delta",
- "parent_run_id": run_id,
- },
- ),
- },
- ),
- )
- await asyncio.wait_for(gate.wait(), timeout=2)
- await store.append_one(
- session_id,
- ItemUpdated(
- event_id="live-e4",
- seq=0,
- item_id="msg-1",
- item_kind="message",
- op="append",
- update=TextContent(part_id="text-0", text="!"),
- **common,
- ),
- )
- await store.append_one(
- session_id,
- RunCompleted(
- event_id="live-e5",
- seq=0,
- status="completed",
- output_refs=(),
- **common,
- ),
- )
- return SimpleNamespace(output_text="hello!", session_id=session_id, usage={})
-
- workspace = Workspace(tmp_path)
- workspace.initialize()
- service = StudioRunService(
- workspace,
- RuntimeExecutor(RuntimeRegistry()),
- plugin_runtime=_LiveBufferedPluginRuntime(),
- )
- service_holder["service"] = service
- observed: list[tuple[str, str]] = []
-
- task = asyncio.create_task(
- service.run(
- StudioRunSpec(
- launch_context=RuntimeLaunchContext(
- runtime_type="harness",
- project_dir=tmp_path,
- ),
- build_id="build-harness-live",
- agent_id="harness-live-agent",
- model="fixture-model",
- plugin_bundle_root=tmp_path,
- ),
- "stream this live",
- session_id="ses-plugin-live",
- on_event=lambda event: observed.append(
- (
- event.type,
- str(event.data.get("text") or event.data.get("delta") or ""),
- )
- ),
- )
- )
-
- # execute 完成前,session store 中已有的增量必须已经到达订阅端。
- # 等到含 "lo" 的增量出现(ItemStarted 首块 "hel" 可能先到/被合并)。
- for _ in range(200):
- if any(
- event_type == "message.delta" and "lo" in text
- for event_type, text in observed
- ):
- break
- await asyncio.sleep(0.01)
- assert any(
- event_type == "message.delta" and "lo" in text
- for event_type, text in observed
- )
- assert not task.done()
-
- gate.set()
- record = await asyncio.wait_for(task, timeout=2)
-
- assert record.status == RunStatus.COMPLETED
- assert record.output == "hello!"
- # 终局:最后一个 delta 与 run.completed 恰好各出现一次(live + 补发去重)。
- deltas = [text for event_type, text in observed if event_type == "message.delta"]
- assert deltas.count("!") == 1
- assert [event_type for event_type, _ in observed].count("run.completed") == 1
- assert "private" not in [text for _, text in observed]
- assert all(
- event.data.get("runtimeEvent", {}).get("event_id") != "live-private-child-delta"
- for event in await service.events(record.id)
- )
-
-
-@pytest.mark.asyncio
-async def test_run_progress_watchdog_dumps_task_stacks_when_no_progress(
- tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
-) -> None:
- """无进展看门狗必须把"当时在干什么"写进日志。
-
- 依据:2026-09-18 一次 run 静默 437s、进程 CPU ~20%,日志里没有任何可归因
- 记录;macOS 上 py-spy 需要 root,只能靠进程内 dump。
- """
-
- import logging
-
- monkeypatch.setenv("KSADK_RUN_STALL_WARN_SECONDS", "0.05")
- monkeypatch.setenv("KSADK_RUN_STALL_DUMP_SECONDS", "0.1")
- workspace = Workspace(tmp_path)
- workspace.initialize()
- service = StudioRunService(workspace, RuntimeExecutor(RuntimeRegistry()))
-
- watchdog = asyncio.create_task(service._watch_run_progress())
- try:
- with caplog.at_level(logging.WARNING, logger="ksadk.studio.run_service"):
- await asyncio.sleep(0.5)
- finally:
- watchdog.cancel()
- with pytest.raises(asyncio.CancelledError):
- await watchdog
-
- messages = [record.getMessage() for record in caplog.records]
- assert any("没有新事件" in message for message in messages)
- assert any("asyncio 任务现场" in message for message in messages)
-
-
-@pytest.mark.asyncio
-async def test_run_progress_watchdog_disabled_by_non_positive_threshold(
- tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
-) -> None:
- import logging
-
- monkeypatch.setenv("KSADK_RUN_STALL_WARN_SECONDS", "0")
- workspace = Workspace(tmp_path)
- workspace.initialize()
- service = StudioRunService(workspace, RuntimeExecutor(RuntimeRegistry()))
-
- with caplog.at_level(logging.WARNING, logger="ksadk.studio.run_service"):
- await service._watch_run_progress()
-
- assert [record for record in caplog.records] == []
-
-
-def test_progress_marker_counts_non_persisted_runtime_chunks(tmp_path: Path) -> None:
- """私有 reasoning delta 不落盘,但必须让无进展看门狗续期。"""
-
- workspace = Workspace(tmp_path)
- workspace.initialize()
- service = StudioRunService(workspace, RuntimeExecutor(RuntimeRegistry()))
- before = service._progress_marker()
-
- service._runtime_progress_seq += 1
-
- after = service._progress_marker()
- assert after[0] == before[0]
- assert after[1] == before[1]
- assert after[2] == before[2] + 1
-
-
-@pytest.mark.asyncio
-async def test_task_stack_dump_walks_nested_await_chain() -> None:
- """dump 必须穿透 ``await`` 链(上一版只给当前协程一帧,run 本体只剩一帧)。"""
-
- import ksadk.studio.run_service as rs
-
- async def inner() -> None:
- await asyncio.Future() # 永不解锁的边界
-
- async def outer() -> None:
- await inner()
-
- task = asyncio.create_task(outer())
- try:
- await asyncio.sleep(0) # 让任务跑到 inner 里的 await
- dump = rs._format_task_stacks()
- finally:
- task.cancel()
- with pytest.raises(asyncio.CancelledError):
- await task
-
- # 链上两层协程的帧都在:外层的 "await inner()" 与内层的 "await asyncio.Future()"
- assert "await inner()" in dump
- assert "await asyncio.Future()" in dump
- # 撞到 Future 边界时被显式记录(fut_waiter/await-boundary)
- assert "Future" in dump
-
-
-@pytest.mark.asyncio
-async def test_watchdog_dumps_repeatedly_while_stall_persists(
- tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
-) -> None:
- """持续卡住必须反复 dump,直到次数上限。
-
- 依据:一次性 dump 区分不了"卡住"和"只是慢"——2026-09-18 那次静默 10 分钟,
- 仅存的一份 dump 早在 6 分钟前,说明不了当时状态。
- """
-
- import logging
-
- monkeypatch.setenv("KSADK_RUN_STALL_WARN_SECONDS", "0.05")
- monkeypatch.setenv("KSADK_RUN_STALL_DUMP_SECONDS", "0.1")
- monkeypatch.setenv("KSADK_RUN_STALL_MAX_DUMPS", "3")
- workspace = Workspace(tmp_path)
- workspace.initialize()
- service = StudioRunService(workspace, RuntimeExecutor(RuntimeRegistry()))
-
- watchdog = asyncio.create_task(service._watch_run_progress())
- try:
- with caplog.at_level(logging.WARNING, logger="ksadk.studio.run_service"):
- await asyncio.sleep(1.0)
- finally:
- watchdog.cancel()
- with pytest.raises(asyncio.CancelledError):
- await watchdog
-
- dumps = [r for r in caplog.records if "次现场" in r.getMessage()]
- assert len(dumps) == 3
- assert all("事件循环最近的定时器" in r.getMessage() for r in dumps)
-
-
-@pytest.mark.asyncio
-async def test_loop_timer_dump_reveals_pending_long_sleep() -> None:
- """dump 必须能看出"有一个很久以后才到期的 sleep"——这正是本次要判定的分叉。"""
-
- import ksadk.studio.run_service as rs
-
- async def long_sleep() -> None:
- await asyncio.sleep(30)
-
- task = asyncio.create_task(long_sleep())
- try:
- await asyncio.sleep(0) # 让 sleep 定时器挂进事件循环
- dump = rs._format_loop_timers()
- finally:
- task.cancel()
- with pytest.raises(asyncio.CancelledError):
- await task
-
- assert "没有待触发的定时器" not in dump
- first_line = dump.splitlines()[0]
- seconds = float(first_line.strip().split("s 后")[0])
- assert seconds > 20
-
-
-def test_require_delivery_rejects_empty_output() -> None:
- """空交付必须抛 EMPTY_DELIVERY,不得判成功。
-
- 依据:2026-09-18 实测——一次 harness run(runtimeType=harness)以
- COMPLETED + output 长度 0 + 产物 0 收场;第一版守卫被错放在
- ``_schedule_run``,真正的完成点 ``_plugin_run`` 没有闸门。
- """
-
- from ksadk.studio.errors import StudioError
- from ksadk.studio.run_service import _require_delivery
-
- _require_delivery("有交付内容") # 非空不抛
-
- for empty in ("", " ", None):
- with pytest.raises(StudioError) as excinfo:
- _require_delivery(empty)
- assert excinfo.value.code == "EMPTY_DELIVERY"
-
-
-def test_consumed_model_output_narrows_empty_delivery_guard() -> None:
- """空交付只在"跑过模型、烧了输出 token"时才成立;合法空输出(审批流)不受影响。"""
-
- from types import SimpleNamespace
-
- from ksadk.studio.run_service import _consumed_model_output
-
- assert _consumed_model_output(SimpleNamespace(usage=SimpleNamespace(output_tokens=96)))
- assert not _consumed_model_output(SimpleNamespace(usage=SimpleNamespace(output_tokens=0)))
- assert not _consumed_model_output(SimpleNamespace(usage=None))
-
-
-@pytest.mark.asyncio
-async def test_empty_delivery_publishes_only_failed_terminal_event(tmp_path: Path) -> None:
- """Provider completion is provisional until Studio accepts the delivery."""
-
- class EmptyDeliveryAdapter(_RecordingAdapter):
- async def stream(self, handle: RunHandle) -> AsyncIterator[RuntimeEvent]:
- common = {
- "schema_version": 2,
- "timestamp": 1.0,
- "run_id": handle.run_id,
- "scope_id": f"scope-{handle.run_id}",
- "source": SourceRef(framework="ksadk"),
- }
- yield RunStarted(event_id="empty-start", seq=1, status="running", **common)
- yield UsageReported(
- event_id="empty-usage",
- seq=2,
- input_tokens=10,
- output_tokens=20,
- total_tokens=30,
- **common,
- )
- yield RunCompleted(
- event_id="empty-completed",
- seq=3,
- status="completed",
- output_refs=(),
- **common,
- )
-
- registry = RuntimeRegistry()
- registry.register("harness", lambda _context: EmptyDeliveryAdapter([], "harness"))
- workspace = Workspace(tmp_path)
- workspace.initialize()
- service = StudioRunService(workspace, RuntimeExecutor(registry))
-
- record = await service.run(
- StudioRunSpec(
- launch_context=RuntimeLaunchContext(runtime_type="harness", project_dir=tmp_path),
- build_id="build-empty-delivery",
- agent_id="empty-delivery-agent",
- ),
- "执行任务",
- session_id="ses-empty-delivery",
- )
-
- assert record.status == RunStatus.FAILED
- canonical = await service.runtime_events.list("ses-empty-delivery")
- terminal_types = [
- event.event_type
- for event in canonical
- if event.event_type in {"run.completed", "run.failed", "run.canceled"}
- ]
- assert terminal_types == ["run.failed"]
diff --git a/tests/studio/test_runtime_prewarm.py b/tests/studio/test_runtime_prewarm.py
deleted file mode 100644
index 77978cb73..000000000
--- a/tests/studio/test_runtime_prewarm.py
+++ /dev/null
@@ -1,45 +0,0 @@
-"""A speculative UI warmup has no authority over the next Run's claims."""
-
-import pytest
-
-from ksadk.plugins.host import PluginHost
-from ksadk.studio.contracts import RunStatus
-from ksadk.studio.runtime_prewarm import prewarm_runtime_build
-from ksadk.studio.service import StudioService
-from tests.studio.native_control_fixture import ControlledGateway
-from tests.studio.test_dsh_provider_registration import _managed_profile, _spec
-
-
-@pytest.mark.asyncio
-async def test_host_warmup_does_not_activate_session_before_actual_run_settings(
- tmp_path, monkeypatch
-):
- _managed_profile(tmp_path, monkeypatch)
- monkeypatch.setenv("MODEL_API_KEY", "fixture-key")
- model = ControlledGateway()
- model.release.set()
- studio = StudioService(
- tmp_path / "workspace", model_client=model, native_harness_agent_ids=("agent",)
- )
- calls = []
- original = PluginHost.open_activation
-
- async def observed(self, *args, **kwargs):
- calls.append(kwargs.get("activation_claims"))
- return await original(self, *args, **kwargs)
-
- monkeypatch.setattr(PluginHost, "open_activation", observed)
- try:
- studio.create_agent(agent_id="agent", name="Warmup fixture", spec=_spec())
- build = await studio.ensure_current_build("agent")
- await prewarm_runtime_build(studio, build.id)
- assert studio.plugin_runs._hosts # Host really prepared; not a no-op warmup.
- assert calls == [] and model.requests == []
- result = await studio.run_build(
- build.id, "ACK_NEXT_TURN", "session", approval_mode="never", reasoning_effort="low"
- )
- assert result.status == RunStatus.COMPLETED, result.error
- assert result.output == "ACK_NEXT_TURN"
- assert len(calls) == 1 and len(model.requests) == 1
- finally:
- await studio.aclose()
diff --git a/tests/studio/test_scheduler_dsh_harness_product.py b/tests/studio/test_scheduler_dsh_harness_product.py
deleted file mode 100644
index cded0fe99..000000000
--- a/tests/studio/test_scheduler_dsh_harness_product.py
+++ /dev/null
@@ -1,349 +0,0 @@
-from __future__ import annotations
-
-import asyncio
-import json
-import shutil
-from pathlib import Path
-
-import pytest
-
-from ksadk.events.session_event import session_event_to_envelope
-from ksadk.harness.reasoner import HarnessReasoningTurn
-from ksadk.plugins.dsh_home import prepare_studio_dsh_home
-from ksadk.plugins.dsh_toolchain import DSH_VERSION
-from ksadk.plugins.providers.harness_dsh import shipped_harness_dsh_bundle
-from ksadk.scheduler.contracts import ScheduleSpec
-from ksadk.studio.contracts import AgentSpec
-from ksadk.studio.errors import StudioError
-from ksadk.studio.service import StudioService
-from tests.e2e.chat_completions_stub import DeterministicChatCompletionsStub
-
-
-class _Reasoner:
- def __init__(self) -> None:
- self.calls: list[tuple[dict[str, object], ...]] = []
-
- async def complete(self, *, model, prompt, messages, tools): # type: ignore[no-untyped-def]
- del model, prompt, tools
- self.calls.append(tuple(messages))
- return HarnessReasoningTurn(final_text="scheduled product result")
-
-
-class _UsageReasoner(_Reasoner):
- """Reasoner that reports per-turn usage the way the real model client does."""
-
- async def complete(self, *, model, prompt, messages, tools): # type: ignore[no-untyped-def]
- del model, prompt, tools
- self.calls.append(tuple(messages))
- return HarnessReasoningTurn(
- final_text="scheduled product result",
- usage={
- "input_tokens": 210,
- "output_tokens": 33,
- "cached_tokens": 12,
- "reasoning_tokens": 9,
- },
- )
-
-
-def _install_managed_harness_profile(root: Path, monkeypatch: pytest.MonkeyPatch) -> None:
- home = root / ".agentkit" / "dsh-home"
- prepare_studio_dsh_home(home)
- profile = home / "profiles" / "studio"
- installed = profile / "node_modules" / "@kingsoftcloud" / "ksadk-harness-provider"
- installed.parent.mkdir(parents=True)
- shutil.copytree(shipped_harness_dsh_bundle().root, installed)
- (profile / "package.json").write_text(
- json.dumps(
- {
- "dependencies": {"@kingsoftcloud/ksadk-harness-provider": "1.0.0"},
- "dsh": {
- "profile": {
- "bundles": ["@kingsoftcloud/ksadk-harness-provider"]
- }
- },
- }
- ),
- encoding="utf-8",
- )
- executable = root / ".agentkit" / "dsh-fixture"
- executable.write_text(
- "#!/bin/sh\n"
- 'case "$*" in\n'
- f" *--version*) echo {DSH_VERSION};;\n"
- " *--dump-config*) echo 'profile: studio; harness: 1.0.0';;\n"
- " *) exit 2;;\n"
- "esac\n",
- encoding="utf-8",
- )
- executable.chmod(0o700)
- monkeypatch.setenv("KSADK_DSH_HOME", str(home))
- monkeypatch.setenv("KSADK_DSH_PROFILE", "studio")
- monkeypatch.setenv("KSADK_DSH_BIN", str(executable))
- monkeypatch.setenv("KSADK_AGENT_KERNEL", "1")
-
-
-def _spec(*, allow_host_process: bool = True) -> AgentSpec:
- return AgentSpec.model_validate(
- {
- "description": "Scheduler managed DSH Harness fixture",
- "runtime": {"type": "harness"},
- "instructions": {
- "system": "You are the managed DSH Harness fixture.",
- "task": "Complete scheduled work.",
- },
- "model": {
- "provider": "openai-compatible",
- "model": "fixture-model",
- "endpointUrl": "https://model.example.com/v1/chat/completions",
- "credentialRef": "env://MODEL_API_KEY",
- },
- "capabilities": {"skills": [], "mcpServers": [], "tools": []},
- "execution": {
- "strategy": "direct",
- "maxSteps": 4,
- "timeoutSeconds": 30,
- "retry": {"maxAttempts": 1, "backoffSeconds": 0},
- },
- "context": {
- "maxInputTokens": 4096,
- "reserveOutputTokens": 512,
- "compaction": {"enabled": True, "thresholdRatio": 0.8},
- },
- "security": {
- "toolPolicy": "deny-by-default",
- "allowedPermissions": (
- ["process:host-user"] if allow_host_process else []
- ),
- "network": {
- "mode": "restricted",
- "allowedHosts": ["model.example.com"],
- "allowPrivateNetwork": False,
- },
- },
- }
- )
-
-
-@pytest.mark.asyncio
-async def test_scheduler_settles_real_managed_dsh_harness_provider(
- tmp_path: Path,
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """Exercise the product service through DSH discovery, Kernel and terminal facts."""
-
- _install_managed_harness_profile(tmp_path, monkeypatch)
- reasoner = _Reasoner()
- service = StudioService(tmp_path, harness_reasoner=reasoner)
- spec = _spec()
- service.create_studio_agent(
- agent_id="scheduler-dsh-harness",
- name="Scheduler DSH Harness",
- description=spec.description,
- spec=spec,
- runtime=spec.runtime,
- )
- await service.start()
- try:
- task = await service.create_agent_schedule(
- "scheduler-dsh-harness",
- display_name="Managed DSH Harness",
- prompt="execute managed DSH harness",
- schedule=ScheduleSpec(kind="interval", every_seconds=3600),
- )
- accepted = await service.run_agent_schedule_now(
- "scheduler-dsh-harness", task.task_id
- )
- current = accepted
- for _ in range(200):
- await service.scheduler.engine.reconcile()
- current = service.scheduler.list_occurrences(task.task_id)[0]
- if current.state in {"succeeded", "failed", "cancelled", "skipped"}:
- break
- await asyncio.sleep(0.01)
-
- if current.state not in {"succeeded", "failed", "cancelled", "skipped"}:
- stored = await service.session_service.get_events(current.session_id)
- envelopes = [
- envelope
- for item in stored
- if (envelope := session_event_to_envelope(item)) is not None
- ]
- event_summary = [
- (item.seq, item.event_type, item.run_id, item.causation_id)
- for item in envelopes
- ]
- pytest.fail(
- "managed DSH Harness occurrence did not settle: "
- f"{current.model_dump(mode='json', by_alias=True)!r}; "
- f"events={event_summary!r}"
- )
-
- assert current.state == "succeeded", current
- assert current.run_id
- assert len(reasoner.calls) == 1
- # Provider 持久装配:Workspace 状态目录由 harness_state_dir 穿线建立
- state_dir = tmp_path / ".agentkit" / "plugin-runtime" / "state"
- assert state_dir.is_dir()
- assert (state_dir / "checkpoints.sqlite").is_file()
- # Kernel and canonical session events now share one SQLite transaction
- # boundary instead of writing a separate database per build.
- kernel = service.scheduler_runtimes.runtime_for_build(task.target.agent_version_ref)
- assert kernel.kernel_store.db_path.resolve() == service.session_service.db_path
- finally:
- await service.scheduler.stop()
- await service.aclose()
-
-
-@pytest.mark.asyncio
-async def test_managed_dsh_harness_reports_nonzero_usage(
- tmp_path: Path,
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """Engine 链路必须把 reasoner 提供的用量上报为非零 usage.reported 事件。"""
-
- _install_managed_harness_profile(tmp_path, monkeypatch)
- reasoner = _UsageReasoner()
- service = StudioService(tmp_path, harness_reasoner=reasoner)
- spec = _spec()
- service.create_studio_agent(
- agent_id="scheduler-dsh-usage",
- name="Scheduler DSH Usage",
- description=spec.description,
- spec=spec,
- runtime=spec.runtime,
- )
- await service.start()
- try:
- task = await service.create_agent_schedule(
- "scheduler-dsh-usage",
- display_name="Managed DSH Usage",
- prompt="execute managed DSH harness usage",
- schedule=ScheduleSpec(kind="interval", every_seconds=3600),
- )
- accepted = await service.run_agent_schedule_now(
- "scheduler-dsh-usage", task.task_id
- )
- current = accepted
- for _ in range(200):
- await service.scheduler.engine.reconcile()
- current = service.scheduler.list_occurrences(task.task_id)[0]
- if current.state in {"succeeded", "failed", "cancelled", "skipped"}:
- break
- await asyncio.sleep(0.01)
-
- assert current.state == "succeeded", current
- stored = await service.session_service.get_events(current.session_id)
- usage_events = [
- event
- for event in stored
- if event.event_type == "usage.reported"
- ]
- assert usage_events, "usage.reported event missing from session events"
- reported = usage_events[-1]
- payload = reported.content["session_event"]["payload"]
- assert payload.get("input_tokens") == 210, payload
- assert payload.get("output_tokens") == 33, payload
- assert payload.get("cached_tokens") == 12, payload
- assert payload.get("reasoning_tokens") == 9, payload
- finally:
- await service.scheduler.stop()
- await service.aclose()
-
-
-@pytest.mark.asyncio
-async def test_scheduler_rejects_unapproved_dsh_provider_before_acceptance(
- tmp_path: Path,
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """A permission failure produces no task, Inbox command, Run, or retry storm."""
-
- _install_managed_harness_profile(tmp_path, monkeypatch)
- service = StudioService(tmp_path, harness_reasoner=_Reasoner())
- spec = _spec(allow_host_process=False)
- service.create_studio_agent(
- agent_id="scheduler-dsh-denied",
- name="Scheduler DSH Denied",
- description=spec.description,
- spec=spec,
- runtime=spec.runtime,
- )
- await service.start()
- try:
- with pytest.raises(StudioError) as denied:
- await service.create_agent_schedule(
- "scheduler-dsh-denied",
- display_name="Denied DSH Harness",
- prompt="must not enter Inbox",
- schedule=ScheduleSpec(kind="interval", every_seconds=3600),
- )
- assert denied.value.code == "PLUGIN_PERMISSION_DENIED"
- details = denied.value.details
- assert details["reason"] == "plugin_permission_denied"
- assert "process:host-user" in details["missingPermissions"]
- assert "重新构建" in details["hint"]
- assert service.scheduler.list_tasks() == []
- assert service.scheduler.list_all_occurrences() == []
- assert service.scheduler_runtimes.active_runtime_count == 0
- assert await service.session_service.list_sessions("scheduler-dsh-denied") == []
- finally:
- await service.scheduler.stop()
- await service.aclose()
-
-
-@pytest.mark.asyncio
-async def test_default_native_scheduler_preserves_session_owner_and_exact_history(
- tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """Production Build/DSH/Kernel/HTTP ports; only external inference is a fixture."""
- _install_managed_harness_profile(tmp_path, monkeypatch)
- monkeypatch.delenv("KSADK_STUDIO_NATIVE_DEFAULT", raising=False)
- monkeypatch.setenv("MODEL_API_KEY", "harness-fixture-key")
- with DeterministicChatCompletionsStub() as model:
- payload = _spec().model_dump(mode="json", by_alias=True)
- payload["model"]["endpointUrl"] = model.endpoint_url
- payload["security"]["network"].update({
- "allowedHosts": ["127.0.0.1"], "allowPrivateNetwork": True,
- })
- spec = AgentSpec.model_validate(payload)
- service = StudioService(tmp_path)
- assert service._native_harness_default is True
- service.create_studio_agent(
- agent_id="native-scheduler", name="Native Scheduler", description=spec.description,
- spec=spec, runtime=spec.runtime,
- )
- await service.session_service.create_session("native-scheduler", "local-user", "owned")
- try:
- task = await service.create_agent_schedule(
- "native-scheduler", display_name="Native continuation", prompt="请答复当前状态",
- schedule=ScheduleSpec(kind="interval", every_seconds=3600),
- continuity="continue_session", session_id="owned",
- )
- kernel = service.scheduler_runtimes.runtime_for_build(task.target.agent_version_ref)
- for turn in range(2):
- await service.run_agent_schedule_now("native-scheduler", task.task_id)
- async with asyncio.timeout(35):
- while True:
- await service.scheduler.engine.reconcile()
- occurrences = service.scheduler.list_occurrences(task.task_id)
- if len(occurrences) == turn + 1 and all(
- item.state == "succeeded" for item in occurrences
- ):
- break
- await asyncio.sleep(0.02)
- run = await kernel.kernel_store.load_run(occurrences[0].run_id)
- assert run.metadata["handle"]["native_ref"]["engine_kind"] == "native"
- assert run.session_id == "owned"
- session = await service.session_service.get_session_metadata("owned")
- assert session.user_id == "local-user"
- requests = model.requests()
- assert len(requests) == 2
- assert [len(row.payload["messages"]) for row in requests] == [2, 4]
- assert requests[1].payload["messages"][1:] == [
- {"role": "user", "content": "请答复当前状态"},
- {"role": "assistant", "content": "scheduled harness result 1"},
- {"role": "user", "content": "请答复当前状态"},
- ]
- finally:
- await service.scheduler.stop()
- await service.aclose()
diff --git a/tests/studio/test_scheduler_history.py b/tests/studio/test_scheduler_history.py
deleted file mode 100644
index 906fb0ee7..000000000
--- a/tests/studio/test_scheduler_history.py
+++ /dev/null
@@ -1,121 +0,0 @@
-"""Scheduled Kernel output remains visible through the shared Studio history."""
-
-from datetime import datetime, timezone
-
-import pytest
-
-from ksadk.events.canonical import (
- ContentSnapshot,
- ItemCompleted,
- RunCompleted,
- RunStarted,
- SourceRef,
-)
-from ksadk.events.canonical_store import RuntimeEventStore
-from ksadk.events.content import TextContent
-from ksadk.studio.contracts import RunRecord, RunStatus
-from ksadk.studio.errors import StudioError
-from ksadk.studio.service import StudioService
-from ksadk.studio.shared_web import StudioSharedWebBridge
-
-
-@pytest.mark.asyncio
-async def test_scheduler_history_replays_beside_foreground_turn_without_duplicates(tmp_path):
- studio = StudioService(tmp_path)
- try:
- await studio.session_service.create_session("agent", "local-studio", "scheduled")
- await studio.session_service.create_session("agent", "another-user", "unrelated")
- bridge = StudioSharedWebBridge(studio)
- common = dict(
- schema_version=2,
- seq=0,
- run_id="kernel-run",
- scope_id="kernel-run",
- source=SourceRef(framework="ksadk"),
- )
- store = RuntimeEventStore(studio.session_service)
- await store.append(
- "scheduled",
- [
- RunStarted(event_id="start", timestamp=10, status="running", **common),
- ItemCompleted(
- event_id="answer",
- timestamp=11,
- item_id="answer",
- item_kind="message",
- snapshot=ContentSnapshot(
- parts=(TextContent(part_id="text", text="定时执行结果"),)
- ),
- **common,
- ),
- RunCompleted(
- event_id="done", timestamp=12, status="completed", output_refs=(), **common
- ),
- ],
- )
- assert studio.event_store.list_runs() == []
- sessions = await bridge.list_sessions("agent")
- assert [item["SessionId"] for item in sessions["Sessions"]] == ["scheduled"]
- messages = await bridge.list_messages("scheduled")
- assert [item["Content"]["text"] for item in messages["Messages"]] == ["定时执行结果"]
- assert messages["Messages"][0]["InvocationId"] == "kernel-run"
- events = await bridge.list_session_events("scheduled")
- assert [item["EventType"] for item in events["Events"]] == [
- "run.started",
- "message.completed",
- "run.completed",
- ]
- stream = [
- item
- async for item in bridge.subscribe_run_events("scheduled", "kernel-run", after_seq_id=1)
- ]
- assert "message.completed" in stream[0]
- assert "[DONE]" in stream[-1]
- with pytest.raises(StudioError):
- await bridge.subscription_run_id("unrelated", "kernel-run")
-
- record = RunRecord(
- id="run_foreground",
- build_id="b",
- agent_id="agent",
- session_id="scheduled",
- trace_id="t",
- input="继续分析",
- output="人工追问结果",
- status=RunStatus.COMPLETED,
- started_at=datetime.fromtimestamp(20, timezone.utc),
- completed_at=datetime.fromtimestamp(22, timezone.utc),
- runtime_handle={"run_id": "native-foreground"},
- )
- studio.event_store.create(record)
- await store.append(
- "scheduled",
- [
- ItemCompleted(
- schema_version=2,
- seq=0,
- event_id="foreground-answer",
- timestamp=21,
- run_id="native-foreground",
- scope_id="native-foreground",
- source=SourceRef(framework="ksadk"),
- item_id="answer",
- item_kind="message",
- snapshot=ContentSnapshot(
- parts=(TextContent(part_id="text", text="人工追问结果"),)
- ),
- ),
- ],
- )
- mixed = await bridge.list_messages("scheduled")
- assert [item["Content"]["text"] for item in mixed["Messages"]] == [
- "定时执行结果",
- "继续分析",
- "人工追问结果",
- ]
- first_page = await bridge.list_messages("scheduled", limit=2)
- assert first_page["HasMore"] is True
- previous = await bridge.list_messages("scheduled", before_seq_id=first_page["NextCursor"])
- assert [item["Content"]["text"] for item in previous["Messages"]] == ["定时执行结果"]
- finally:
- await studio.aclose()
diff --git a/tests/studio/test_scheduler_runtime.py b/tests/studio/test_scheduler_runtime.py
deleted file mode 100644
index d1cb36cac..000000000
--- a/tests/studio/test_scheduler_runtime.py
+++ /dev/null
@@ -1,382 +0,0 @@
-from __future__ import annotations
-
-import asyncio
-import re
-from datetime import datetime, timedelta, timezone
-from pathlib import Path
-
-import pytest
-
-from ksadk.events.canonical import ItemCompleted
-from ksadk.events.canonical_store import RuntimeEventStore
-from ksadk.harness import HarnessConfig, HarnessReasoningTurn, HarnessRuntimeAdapter
-from ksadk.kernel.ingress import get_agent_kernel
-from ksadk.runtime import RuntimeLaunchContext
-from ksadk.scheduler.contracts import (
- ScheduleCommandTemplate,
- ScheduledTask,
- ScheduledTaskTarget,
- ScheduleSpec,
-)
-from ksadk.sessions.in_memory import InMemorySessionService
-from ksadk.studio.run_service import StudioRunSpec
-from ksadk.studio.scheduler_runtime import (
- StudioScheduledKernelRegistry,
- StudioSchedulerRuntimeError,
-)
-from ksadk.studio.scheduler_service import StudioSchedulerService
-from ksadk.studio.workspace import Workspace
-
-
-class _Reasoner:
- def __init__(self, label: str) -> None:
- self.label = label
-
- async def complete(self, *, model, prompt, messages, tools): # type: ignore[no-untyped-def]
- del model, prompt, tools
- return HarnessReasoningTurn(
- final_text=f"{self.label}:{messages[-1]['content']}",
- tool_calls=(),
- )
-
-
-def _spec(root: Path, build_id: str, agent_id: str) -> StudioRunSpec:
- return StudioRunSpec(
- launch_context=RuntimeLaunchContext(
- runtime_type="harness",
- project_dir=root / build_id,
- ),
- build_id=build_id,
- agent_id=agent_id,
- model="fixture-model",
- request_config={"prompt": f"system:{agent_id}"},
- manifest_sha256=f"sha256:{build_id}",
- )
-
-
-def _task(
- task_id: str,
- *,
- target,
- content: str,
-) -> ScheduledTask:
- return ScheduledTask(
- task_id=task_id,
- target=ScheduledTaskTarget(
- agent_id=target.agent_id,
- tenant_id=target.tenant_id,
- agent_instance_id=target.agent_instance_id,
- agent_version_ref=target.build_id,
- authorization_ref="runtime://studio-scheduler-kernel",
- ),
- schedule=ScheduleSpec(
- kind="once",
- at=datetime.now(timezone.utc) + timedelta(days=1),
- ),
- command=ScheduleCommandTemplate(payload={"content": content}),
- )
-
-
-async def _wait_terminal(
- service: StudioSchedulerService,
- task_id: str,
- occurrence_id: str,
-):
- for _ in range(200):
- await service.engine.reconcile()
- current = next(
- item
- for item in service.list_occurrences(task_id)
- if item.occurrence_id == occurrence_id
- )
- if current.state in {"succeeded", "failed", "cancelled", "skipped"}:
- return current
- await asyncio.sleep(0.01)
- pytest.fail(f"occurrence {occurrence_id} did not settle")
-
-
-@pytest.mark.asyncio
-async def test_studio_scheduler_starts_build_pinned_kernels_without_global_ingress(
- tmp_path: Path,
-) -> None:
- specs = {
- "build-a": _spec(tmp_path, "build-a", "agent-a"),
- "build-b": _spec(tmp_path, "build-b", "agent-b"),
- }
- sessions = InMemorySessionService()
- factory_calls = 0
-
- def provider(spec: StudioRunSpec):
- def create_adapter() -> HarnessRuntimeAdapter:
- nonlocal factory_calls
- factory_calls += 1
- return HarnessRuntimeAdapter(
- HarnessConfig(
- model="fixture-model",
- prompt=str(spec.request_config["prompt"]),
- ),
- agent_name=spec.agent_id,
- reasoner=_Reasoner(spec.build_id),
- workspace_root=tmp_path,
- )
-
- return create_adapter
-
- global_before = get_agent_kernel()
- registry = StudioScheduledKernelRegistry(
- resolve_build=specs.__getitem__,
- resolve_adapter_provider=provider,
- session_service=sessions,
- poll_interval=0.005,
- lease_ttl_seconds=5,
- )
- workspace = Workspace(tmp_path)
- workspace.initialize()
- scheduler = StudioSchedulerService(workspace, runtime_registry=registry)
- await scheduler.start_if_available()
- try:
- target_a = await registry.ensure_build("build-a", expected_agent_id="agent-a")
- target_b = await registry.ensure_build("build-b", expected_agent_id="agent-b")
- # Registration snapshots capabilities with one adapter per Build. The
- # same retained instances are consumed by the first workers; no second
- # discarded probe is created at either boundary.
- assert factory_calls == 2
- scheduler.create_task(_task("task-agent-a", target=target_a, content="alpha"))
- scheduler.create_task(_task("task-agent-b", target=target_b, content="beta"))
-
- first = await scheduler.run_now("task-agent-a")
- second = await scheduler.run_now("task-agent-b")
- first = await _wait_terminal(scheduler, "task-agent-a", first.occurrence_id)
- second = await _wait_terminal(scheduler, "task-agent-b", second.occurrence_id)
-
- assert first.state == "succeeded", first
- assert second.state == "succeeded", second
- assert first.run_id and second.run_id and first.run_id != second.run_id
- assert registry.active_runtime_count == 2
- assert factory_calls == 2
- assert target_a.agent_instance_id != target_b.agent_instance_id
- assert get_agent_kernel() is global_before
-
- first_events = await RuntimeEventStore(sessions).list(first.session_id)
- second_events = await RuntimeEventStore(sessions).list(second.session_id)
- first_text = [
- "".join(str(getattr(part, "text", "")) for part in event.snapshot.parts)
- for event in first_events
- if isinstance(event, ItemCompleted) and event.item_kind == "message"
- ]
- second_text = [
- "".join(str(getattr(part, "text", "")) for part in event.snapshot.parts)
- for event in second_events
- if isinstance(event, ItemCompleted) and event.item_kind == "message"
- ]
- assert first_text == ["build-a:alpha"]
- assert second_text == ["build-b:beta"]
- finally:
- await scheduler.stop()
-
- assert registry.active_runtime_count == 0
- assert not registry.started
- assert get_agent_kernel() is global_before
-
-
-@pytest.mark.asyncio
-async def test_scheduler_registry_rejects_a_stale_or_cross_agent_target(tmp_path: Path) -> None:
- spec = _spec(tmp_path, "build-a", "agent-a")
- registry = StudioScheduledKernelRegistry(
- resolve_build=lambda _build_id: spec,
- resolve_adapter_provider=lambda _spec: lambda: HarnessRuntimeAdapter(
- HarnessConfig(model="fixture-model", prompt="system"),
- reasoner=_Reasoner("build-a"),
- workspace_root=tmp_path,
- ),
- session_service=InMemorySessionService(),
- )
- await registry.start()
- try:
- with pytest.raises(StudioSchedulerRuntimeError) as mismatch:
- await registry.ensure_build("build-a", expected_agent_id="agent-b")
- assert mismatch.value.code == "SCHEDULER_AGENT_MISMATCH"
-
- target = await registry.ensure_build("build-a", expected_agent_id="agent-a")
- with pytest.raises(StudioSchedulerRuntimeError) as stale:
- await registry.ensure_target(
- ScheduledTaskTarget(
- agent_id="agent-a",
- tenant_id=target.tenant_id,
- agent_instance_id="wrong-instance",
- agent_version_ref="build-a",
- authorization_ref="runtime://studio-scheduler-kernel",
- )
- )
- assert stale.value.code == "SCHEDULER_TARGET_MISMATCH"
- finally:
- await registry.close()
-
-
-# G11 环境 Section 内容(日期动态),以 system 角色随每次装配注入。
-_ENV_SECTION_RE = re.compile(
- r"当前日期:\d{4}-\d{2}-\d{2}(时区 .+)\nAgent:agent-a\n平台:\w+"
-)
-
-
-@pytest.mark.asyncio
-async def test_managed_harness_scheduler_restores_history_after_registry_restart(
- tmp_path: Path,
-) -> None:
- from ksadk.harness.managed_runtime import ManagedHarnessRuntimeAdapter
- from ksadk.harness.spec import HarnessSpec, ModelBinding, PromptSpec
- from ksadk.sessions.local_service import LocalSessionService
-
- requests: list[list[dict]] = []
-
- class RecordingReasoner:
- async def complete(self, *, model, prompt, messages, tools, max_output_tokens=None):
- requests.append([dict(message) for message in messages])
- return HarnessReasoningTurn(final_text=f"answer-{len(requests)}")
-
- spec = _spec(tmp_path, "build-a", "agent-a")
- harness_spec = HarnessSpec(
- agent_revision_ref="agent-revision://agent-a@1",
- model=ModelBinding(profile_ref="model-profile://fixture@1"),
- prompt=PromptSpec(instructions="system-role"),
- )
- workspace = Workspace(tmp_path)
- workspace.initialize()
-
- async def start_scheduler():
- registry = StudioScheduledKernelRegistry(
- resolve_build=lambda _build: spec,
- resolve_adapter_provider=lambda _spec: lambda: ManagedHarnessRuntimeAdapter(
- harness_spec, reasoner=RecordingReasoner(), workspace_root=tmp_path,
- ),
- session_service=LocalSessionService(project_dir=str(tmp_path)),
- state_dir=tmp_path / "scheduler-state",
- poll_interval=0.005,
- lease_ttl_seconds=5,
- )
- scheduler = StudioSchedulerService(workspace, runtime_registry=registry)
- await scheduler.start_if_available()
- return scheduler, registry
-
- scheduler, registry = await start_scheduler()
- try:
- target = await registry.ensure_build("build-a", expected_agent_id="agent-a")
- task = _task("continued", target=target, content="remember alpha")
- task = task.model_copy(update={
- "continuity": "continue_session",
- "target": task.target.model_copy(
- update={"session_id": "continued-session"},
- ),
- })
- scheduler.create_task(task)
- first = await scheduler.run_now(task.task_id)
- first = await _wait_terminal(scheduler, task.task_id, first.occurrence_id)
- assert first.state == "succeeded", first
- finally:
- await scheduler.stop()
-
- # A fresh registry, adapter, and SessionService must recover from durable facts.
- scheduler, registry = await start_scheduler()
- try:
- second = await scheduler.run_now("continued")
- second = await _wait_terminal(scheduler, "continued", second.occurrence_id)
- assert second.state == "succeeded", second
- assert second.session_id == first.session_id == "continued-session"
- assert second.run_id != first.run_id
- actual = [(m["role"], m["content"]) for m in requests[1]]
- # The current Build's empty Skill directory is a stable, low-trust
- # context section. It is not a recovered conversation turn.
- assert actual[1][0] == "assistant", actual
- assert "<<>>" in actual[1][1]
- assert "当前没有已绑定 Skill" in actual[1][1]
- actual = [actual[0], *actual[2:]]
- expected = [
- ("system", "system-role"),
- # G11 环境上下文段(system trust)随每次装配注入,日期动态。
- ("system", _ENV_SECTION_RE),
- ("user", "remember alpha"),
- ("assistant", "answer-1"),
- ("user", "remember alpha"),
- ]
- assert len(actual) == len(expected), actual
- for (arole, atext), (erole, epat) in zip(actual, expected):
- assert arole == erole, actual
- if isinstance(epat, re.Pattern):
- assert epat.fullmatch(atext), atext
- else:
- assert atext == epat, actual
- finally:
- await scheduler.stop()
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize(
- "mismatch",
- [
- None, "command_agent", "command_session", "command_tenant",
- "run_agent", "run_session", "failed",
- ],
-)
-async def test_harness_history_scopes_durable_facts_and_deduplicates_completion(mismatch) -> None:
- from types import SimpleNamespace
- from unittest.mock import AsyncMock
- from uuid import uuid4
-
- from ksadk.events.canonical import RunCompleted, SourceRef
- from ksadk.events.content import ContentSnapshot, TextContent
- from ksadk.kernel.contracts import AgentControlCommand, ControlSource
- from ksadk.kernel.state import RunState
- from ksadk.kernel.store import RunRecord
- from ksadk.kernel.worker_history import harness_conversation_messages
-
- command = AgentControlCommand(
- command_id=uuid4(), idempotency_key="current", tenant_id="tenant-a",
- agent_instance_id="agent-a", session_id="session-a", command_type="enqueue",
- payload={"content": "current"}, source=ControlSource(kind="scheduler", ref="task-a"),
- authorization_ref="fixture", submitted_at=datetime.now(timezone.utc).isoformat(),
- )
- previous = command.model_copy(update={
- "command_id": uuid4(), "payload": {"content": "previous"},
- })
- command_mismatches = {
- "command_agent": {"agent_instance_id": "agent-b"},
- "command_session": {"session_id": "session-b"},
- "command_tenant": {"tenant_id": "tenant-b"},
- }
- previous = previous.model_copy(update=command_mismatches.get(mismatch, {}))
- run = RunRecord(
- run_id="prior-run", agent_instance_id="agent-b" if mismatch == "run_agent" else "agent-a",
- session_id="session-b" if mismatch == "run_session" else "session-a",
- state=RunState.FAILED if mismatch == "failed" else RunState.COMPLETED,
- metadata={"command_id": str(previous.command_id)},
- )
- store = SimpleNamespace(
- list_messages=AsyncMock(return_value=[SimpleNamespace(command=previous)]),
- load_run=AsyncMock(return_value=run),
- )
- sessions = InMemorySessionService()
- await sessions.create_session("agent-a", "user-a", "session-a")
- event_store = RuntimeEventStore(sessions)
- envelope = dict(
- schema_version=2, seq=0, timestamp=1.0, run_id="prior-run", scope_id="root",
- source=SourceRef(framework="langgraph"),
- )
- # Distinct canonical items remain separate messages, even with one role.
- for index in range(2):
- await event_store.append_one("session-a", ItemCompleted(
- **envelope, event_id=f"message-{index}", item_id=f"item-{index}", item_kind="message",
- snapshot=ContentSnapshot(parts=(TextContent(part_id="text", text=f"answer-{index}"),)),
- ))
- # A duplicate terminal fact must not replay the same complete turn twice.
- for index in range(2):
- await event_store.append_one("session-a", RunCompleted(
- **envelope, event_id=f"completed-{index}", status="completed", output_refs=(),
- ))
- messages = await harness_conversation_messages(command, store=store, session_events=sessions)
- expected = [] if mismatch else [
- {"role": "user", "content": "previous"},
- {"role": "assistant", "content": "answer-0"},
- {"role": "assistant", "content": "answer-1"},
- ]
- assert messages == [*expected, {"role": "user", "content": "current"}]
- store.list_messages.assert_awaited_once_with("agent-a", "session-a")
diff --git a/tests/studio/test_shared_web.py b/tests/studio/test_shared_web.py
deleted file mode 100644
index 2c3288e42..000000000
--- a/tests/studio/test_shared_web.py
+++ /dev/null
@@ -1,1413 +0,0 @@
-from __future__ import annotations
-
-import asyncio
-from types import SimpleNamespace
-from unittest.mock import AsyncMock
-from datetime import datetime, timezone
-from pathlib import Path
-from types import SimpleNamespace
-from unittest.mock import AsyncMock, Mock
-
-import pytest
-from fastapi.testclient import TestClient
-
-from ksadk.events.canonical import (
- ContentSnapshot,
- ItemCompleted,
- ItemStarted,
- ItemUpdated,
- OutputRef,
- RunCompleted,
- RunStarted,
- SourceRef,
-)
-from ksadk.events.content import TextContent
-from ksadk.plugins.contracts import PluginManifest
-from ksadk.studio.api import create_studio_app
-from ksadk.studio.codex_provider_build import CODEX_PROVIDER_REF
-from ksadk.studio.contracts import ModelSpec, RunRecord, RunStatus, Usage
-from ksadk.studio.errors import StudioError
-from ksadk.studio.model_client import ModelResponse
-from ksadk.studio.service import StudioService
-from ksadk.studio.shared_web import StudioSharedWebBridge
-from ksadk.studio.templates import default_agent_spec
-from tests.studio.runtime_adapter_fixtures import RuntimeFixture
-
-
-@pytest.mark.asyncio
-async def test_cancel_run_preserves_canonical_run_cancellation() -> None:
- run_service = SimpleNamespace(cancel_run=AsyncMock(return_value={"status": "cancelling"}))
- operations = SimpleNamespace(cancel=Mock())
- studio = SimpleNamespace(
- _require_direct_run=Mock(),
- run_service=run_service,
- operations=operations,
- event_store=SimpleNamespace(
- get=Mock(
- side_effect=[
- SimpleNamespace(status=RunStatus.CREATED),
- SimpleNamespace(status=RunStatus.RUNNING),
- SimpleNamespace(status=RunStatus.CANCELLED),
- ]
- )
- ),
- )
- bridge = StudioSharedWebBridge(studio)
- bridge._operations_by_invocation["inv-1"] = "op-1"
- bridge._run_ids_by_invocation["inv-1"] = "run-1"
-
- result = await bridge.cancel_run("inv-1")
-
- run_service.cancel_run.assert_awaited_once_with("run-1")
- operations.cancel.assert_not_called()
- assert studio.event_store.get.call_count == 3
- assert result == {
- "InvocationId": "inv-1",
- "RunId": "run-1",
- "Cancelled": True,
- }
-
-
-@pytest.mark.asyncio
-async def test_cancel_run_falls_back_before_canonical_run_is_created() -> None:
- run_service = SimpleNamespace(cancel_run=AsyncMock())
- operations = SimpleNamespace(cancel=Mock())
- studio = SimpleNamespace(
- _require_direct_run=Mock(),
- run_service=run_service,
- operations=operations,
- event_store=SimpleNamespace(get=Mock(side_effect=KeyError("not found"))),
- )
- bridge = StudioSharedWebBridge(studio)
- bridge._operations_by_invocation["inv-1"] = "op-1"
-
- result = await bridge.cancel_run("inv-1")
-
- operations.cancel.assert_called_once_with("op-1")
- run_service.cancel_run.assert_not_awaited()
- assert result["Cancelled"] is True
- assert result["RunId"] == ""
-
-
-@pytest.mark.asyncio
-async def test_cancel_run_accepts_durable_run_id_after_page_reload() -> None:
- run_service = SimpleNamespace(cancel_run=AsyncMock(return_value={"status": "cancelling"}))
- operations = SimpleNamespace(cancel=Mock())
- studio = SimpleNamespace(
- _require_direct_run=Mock(),
- run_service=run_service,
- operations=operations,
- event_store=SimpleNamespace(
- get=Mock(
- side_effect=[
- SimpleNamespace(status=RunStatus.RUNNING),
- SimpleNamespace(status=RunStatus.CANCELLED),
- ]
- )
- ),
- )
- bridge = StudioSharedWebBridge(studio)
-
- result = await bridge.cancel_run("run-restored")
-
- run_service.cancel_run.assert_awaited_once_with("run-restored")
- operations.cancel.assert_not_called()
- assert result == {
- "InvocationId": "run-restored",
- "RunId": "run-restored",
- "Cancelled": True,
- }
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize("delivery", ["replace", "guide"])
-async def test_steer_run_resolves_invocation_and_preserves_direct_run_gate(delivery) -> None:
- run_service = SimpleNamespace(
- steer_run=AsyncMock(return_value={"runId": "run-1", "status": "steering"})
- )
- studio = SimpleNamespace(_require_direct_run=Mock(), run_service=run_service)
- bridge = StudioSharedWebBridge(studio)
- bridge._run_ids_by_invocation["inv-1"] = "run-1"
-
- result = await bridge.steer_run("inv-1", "correct the current turn", delivery=delivery)
-
- studio._require_direct_run.assert_called_once_with("run-1")
- run_service.steer_run.assert_awaited_once_with(
- "run-1", "correct the current turn", delivery=delivery
- )
- assert result == {
- "InvocationId": "inv-1",
- "RunId": "run-1",
- "Status": "steering",
- }
-
-
-def test_response_session_id_resolves_live_waiting_invocation() -> None:
- studio = SimpleNamespace(
- event_store=SimpleNamespace(
- get=Mock(return_value=SimpleNamespace(session_id="session-live"))
- )
- )
- bridge = StudioSharedWebBridge(studio)
- bridge._run_ids_by_invocation["response-live"] = "run-live"
-
- assert bridge.response_session_id("response-live") == "session-live"
- studio.event_store.get.assert_called_once_with("run-live")
-
-
-class RecordingModelClient:
- def __init__(self) -> None:
- self.messages: list[list[dict]] = []
-
- async def complete(self, _model, *, messages, **_kwargs):
- self.messages.append(messages)
- turn = len(self.messages)
- content = f"共享会话回复 {turn}"
- return ModelResponse(
- content=content,
- finish_reason="stop",
- usage=Usage(input_tokens=5, output_tokens=3, total_tokens=8),
- tool_calls=[],
- raw_message={"role": "assistant", "content": content},
- )
-
-
-def _codex_provider_manifest() -> PluginManifest:
- return PluginManifest.model_validate(
- {
- "metadata": {"id": "io.ksadk.codex-provider", "version": "1.0.0"},
- "spec": {
- "domain": "runtime-native",
- "runtime": "process",
- "entrypoint": "deepseek-harness:profile-agent-provider",
- "provides": [
- {
- "definition": "agent.provider/v1",
- "slot": "agent.execution",
- "mode": "unique",
- }
- ],
- "permissions": ["process:host-user"],
- "isolation": "sidecar",
- "compatibility": {
- "kernelApi": ">=1,<2",
- "runtimeProtocols": ["AgentControlChannel/v1"],
- },
- "healthContract": "plugin.health/v1",
- "provenance": {
- "source": "runtime-native",
- "digest": "sha256:" + "1" * 64,
- },
- },
- }
- )
-
-
-def _valid_spec():
- return {
- "description": "Shared Web test",
- "runtime": {
- "type": "langgraph",
- "projectPath": "agents/demo-agent/source",
- "entryPoint": "agent.py",
- "agentVariable": "graph",
- },
- "instructions": {
- "system": "You are a shared Web test agent.",
- "task": "Answer the request.",
- },
- "model": {
- "provider": "openai-compatible",
- "model": "glm-5.1",
- "endpointUrl": "https://model.example.com/v1/chat/completions",
- "credentialRef": "env://MODEL_API_KEY",
- "parameters": {"temperature": 0.2, "maxTokens": 128},
- },
- "capabilities": {"skills": [], "mcpServers": [], "tools": []},
- "execution": {
- "strategy": "direct",
- "maxSteps": 4,
- "timeoutSeconds": 30,
- "retry": {"maxAttempts": 1, "backoffSeconds": 0},
- },
- "context": {
- "maxInputTokens": 4096,
- "reserveOutputTokens": 512,
- "compaction": {"enabled": True, "thresholdRatio": 0.8},
- },
- "security": {
- "toolPolicy": "deny-by-default",
- "allowedPermissions": [],
- "network": {
- "mode": "restricted",
- "allowedHosts": ["model.example.com"],
- "allowPrivateNetwork": False,
- },
- },
- "evaluation": {"suiteRefs": [], "minimumPassRate": 1},
- }
-
-
-async def _shared_runtime_events(request, handle):
- turn = int(handle.run_id.rsplit("-", 1)[-1])
- text = f"共享会话回复 {turn}"
- common = {
- "schema_version": 2,
- "timestamp": 1.0,
- "run_id": handle.run_id,
- "scope_id": f"scope-{handle.run_id}",
- }
- source = SourceRef(framework="langgraph")
- yield RunStarted(
- event_id=f"{handle.run_id}:e1",
- seq=1,
- status="running",
- source=source,
- **common,
- )
- yield ItemUpdated(
- event_id=f"{handle.run_id}:e2",
- seq=2,
- item_id="msg-1",
- item_kind="message",
- op="append",
- update=TextContent(part_id="text-0", text=text),
- source=source,
- **common,
- )
- yield ItemCompleted(
- event_id=f"{handle.run_id}:e3",
- seq=3,
- item_id="msg-1",
- item_kind="message",
- snapshot=ContentSnapshot(parts=(TextContent(part_id="text-0", text=text),)),
- source=source,
- **common,
- )
- yield RunCompleted(
- event_id=f"{handle.run_id}:e4",
- seq=4,
- status="completed",
- output_refs=(
- OutputRef(
- scope_id=common["scope_id"],
- item_id="msg-1",
- part_id="text-0",
- ),
- ),
- source=SourceRef(
- framework="langgraph",
- metadata={"duration_ms": 9},
- ),
- **common,
- )
-
-
-def _create_agent(client: TestClient) -> None:
- created = client.post(
- "/api/v1/agents",
- json={"id": "demo-agent", "name": "Demo Agent", "template": "blank"},
- )
- assert created.status_code == 201
- updated = client.put(
- "/api/v1/agents/demo-agent",
- headers={"If-Match": '"1"'},
- json=_valid_spec(),
- )
- assert updated.status_code == 200
-
-
-def _run_shared_chat(
- client: TestClient,
- *,
- session_id: str,
- invocation_id: str,
- text: str,
-) -> str:
- with client.stream(
- "POST",
- "/agentengine/api/v1/RunAgent",
- json={
- "AgentId": "demo-agent",
- "SessionId": session_id,
- "InvocationId": invocation_id,
- "ApiFormat": "responses",
- "ResponsesInput": [
- {
- "role": "user",
- "content": [{"type": "input_text", "text": text}],
- }
- ],
- },
- ) as response:
- assert response.status_code == 200
- return "".join(response.iter_text())
-
-
-def test_react_chat_has_one_root_entry_and_no_standalone_chat(tmp_path: Path):
- app = create_studio_app(tmp_path, security_enabled=False)
-
- with TestClient(app) as client:
- _create_agent(client)
- root = client.get("/")
- standalone = client.get("/chat?agentId=demo-agent")
- shared_theme = client.get("/static/shared-chat.css")
-
- system = client.get("/api/v1/system/bootstrap").json()
- route_paths = {getattr(route, "path", "") for route in app.routes}
-
- assert root.status_code == 200
- assert standalone.status_code == 404
- assert standalone.headers["x-frame-options"] == "DENY"
- assert shared_theme.status_code == 404
- assert "/chat" not in route_paths
- assert "/chat/" not in route_paths
- assert system["features"]["reactChat"] is True
- assert "sharedChat" not in system["features"]
-
-
-def test_shared_chat_run_output_accepts_serialized_status():
- record = RunRecord(
- id="run_status_only",
- build_id="build_status_only",
- agent_id="demo-agent",
- session_id="ses_status_only",
- trace_id="trace_status_only",
- status=RunStatus.RUNNING,
- input="hello",
- )
-
- assert StudioSharedWebBridge._run_output(record) == "运行状态:RUNNING"
-
-
-@pytest.mark.asyncio
-async def test_active_run_output_replays_persisted_canonical_message() -> None:
- record = RunRecord(
- id="run_active",
- build_id="build_active",
- agent_id="demo-agent",
- session_id="ses_active",
- trace_id="trace_active",
- status=RunStatus.RUNNING,
- input="hello",
- )
- common = {
- "schema_version": 2,
- "timestamp": 1.0,
- "run_id": "native-run",
- "scope_id": "scope-1",
- "source": SourceRef(framework="langgraph"),
- }
- canonical = [
- ItemStarted(
- event_id="event-1",
- seq=1,
- item_id="answer",
- item_kind="message",
- initial=ContentSnapshot(parts=(TextContent(part_id="text", text="正在"),)),
- **common,
- ),
- ItemUpdated(
- event_id="event-2",
- seq=2,
- item_id="answer",
- item_kind="message",
- op="append",
- update=TextContent(part_id="text", text="生成"),
- **common,
- ),
- ItemUpdated(
- event_id="event-3",
- seq=3,
- item_id="private-reasoning",
- item_kind="reasoning",
- op="append",
- update=TextContent(part_id="text", text="不应展示"),
- **common,
- ),
- ]
- studio = SimpleNamespace(
- run_service=SimpleNamespace(
- events=AsyncMock(
- return_value=[
- SimpleNamespace(data={"runtimeEvent": event.model_dump(mode="json")})
- for event in canonical
- ]
- )
- )
- )
-
- from ksadk.studio.active_run_output import active_run_output
-
- output = await active_run_output(studio.run_service, record)
-
- assert output == "正在生成"
-
-
-def test_shared_chat_empty_session_survives_session_reload(tmp_path: Path):
- app = create_studio_app(tmp_path, security_enabled=False)
-
- with TestClient(app) as client:
- _create_agent(client)
- created_response = client.post(
- "/agentengine/api/v1/CreateSession",
- json={"AgentId": "demo-agent"},
- )
- assert created_response.status_code == 200
- created = created_response.json()["Data"]["Session"]
-
- reloaded_app = create_studio_app(tmp_path, security_enabled=False)
- with TestClient(reloaded_app) as client:
- sessions = client.post(
- "/agentengine/api/v1/ListSessions",
- json={"AgentId": "demo-agent", "Page": 1, "PageSize": 30},
- ).json()["Data"]
- assert sessions["Total"] == 1
- assert sessions["Sessions"][0]["SessionId"] == created["SessionId"]
- assert sessions["Sessions"][0]["Title"] == "新会话"
-
- restored = client.post(
- "/agentengine/api/v1/GetSession",
- json={"SessionId": created["SessionId"]},
- )
- assert restored.status_code == 200
- assert restored.json()["Data"]["Session"]["SessionId"] == created["SessionId"]
-
- messages = client.post(
- "/agentengine/api/v1/ListSessionMessages",
- json={"SessionId": created["SessionId"], "Limit": 50},
- ).json()["Data"]
- assert messages["Messages"] == []
-
- deleted = client.post(
- "/agentengine/api/v1/DeleteSession",
- json={"SessionId": created["SessionId"]},
- )
- assert deleted.status_code == 200
- sessions_after_delete = client.post(
- "/agentengine/api/v1/ListSessions",
- json={"AgentId": "demo-agent"},
- ).json()["Data"]
- assert sessions_after_delete["Total"] == 0
-
-
-def test_shared_chat_resolves_bound_model_profile(tmp_path: Path):
- service = StudioService(tmp_path)
- service.catalog.create_model_profile(
- name="glm-5.1",
- display_name="GLM-5.1",
- version="1.0.0",
- description="",
- spec=ModelSpec(
- provider="openai-compatible",
- model="glm-5.1",
- endpoint_url="https://api.openai.com/v1/chat/completions",
- credential_ref="env://AGENTKIT_MODEL_API_KEY",
- ),
- )
- model_profile = service.catalog.list(kind="model")[0]
- spec = default_agent_spec("blank")
- spec.bindings.model_profile_id = model_profile.resource_id
- service.create_agent(
- agent_id="bound-model-agent",
- name="Bound Model Agent",
- spec=spec,
- )
-
- bridge = StudioSharedWebBridge(service)
- bootstrap = bridge.bootstrap("bound-model-agent")
- models = bridge.list_models("bound-model-agent")
-
- assert bootstrap["Model"]["id"] == "glm-5.1"
- assert bootstrap["Model"]["display_name"] == "GLM-5.1"
- assert models["Current"] == "glm-5.1"
- assert models["Models"] == [bootstrap["Model"]]
-
-
-def test_shared_chat_skips_missing_default_provider_without_index_error(
- tmp_path: Path, monkeypatch
-) -> None:
- service = StudioService(tmp_path)
- profiles = []
- for name in ("missing-primary", "available-fallback"):
- profiles.append(
- service.catalog.create_model_profile(
- name=name,
- display_name=name,
- version="1.0.0",
- description="",
- spec=ModelSpec(
- provider="openai-compatible",
- model=name,
- endpoint_url="https://api.openai.com/v1/chat/completions",
- credential_ref="env://AGENTKIT_MODEL_API_KEY",
- ),
- )
- )
- spec = default_agent_spec("blank")
- spec.bindings.model_profile_id = profiles[0].resource_id
- spec.bindings.model_profile_ids = [item.resource_id for item in profiles]
- service.create_agent(agent_id="provider-fallback", name="Provider Fallback", spec=spec)
-
- original_resolve = service.catalog.resolve_model
-
- def resolve_available(bindings):
- if bindings.model_profile_id == profiles[0].resource_id:
- raise StudioError("RESOURCE_NOT_FOUND", "provider catalog not loaded", status_code=404)
- return original_resolve(bindings)
-
- monkeypatch.setattr(service.catalog, "resolve_model", resolve_available)
-
- models = StudioSharedWebBridge(service).list_models("provider-fallback")
-
- assert models["Current"] == "available-fallback"
- assert [item["id"] for item in models["Models"]] == ["available-fallback"]
-
-
-def test_shared_chat_keeps_unbound_agent_model_explicit(tmp_path: Path):
- service = StudioService(tmp_path)
- service.create_agent(agent_id="unbound-agent", name="Unbound Agent")
-
- model = StudioSharedWebBridge(service).bootstrap("unbound-agent")["Model"]
-
- assert model["id"] == "unconfigured-model"
- assert model["display_name"] == "未配置模型"
-
-
-def test_shared_chat_explains_unbound_model_profile(tmp_path: Path):
- service = StudioService(tmp_path)
- service.create_agent(agent_id="unbound-agent", name="Unbound Agent")
- app = create_studio_app(
- tmp_path,
- service=service,
- security_enabled=False,
- )
-
- with TestClient(app) as client:
- with client.stream(
- "POST",
- "/agentengine/api/v1/RunAgent",
- json={
- "AgentId": "unbound-agent",
- "SessionId": "ses_unbound",
- "InvocationId": "run_unbound",
- "ResponsesInput": [
- {
- "role": "user",
- "content": [{"type": "input_text", "text": "你好"}],
- }
- ],
- },
- ) as response:
- stream = "".join(response.iter_text())
-
- assert "当前 Agent 未绑定 Model Profile" in stream
- assert "API Key 只提供访问凭证" in stream
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize(
- ("extra", "message"),
- [
- ({"Messages": []}, "请输入消息后再发送"),
- ({"Messages": "invalid"}, "会话输入格式无效"),
- ({"Model": "not-bound"}, "当前 Agent 未绑定 Model Profile"),
- ({"AgentId": "missing-agent"}, "agent 不存在"),
- ],
-)
-async def test_stream_preflight_errors_are_not_empty_responses(tmp_path, extra, message):
- studio = StudioService(tmp_path)
- studio.create_agent(agent_id="demo-agent", name="Demo Agent")
- payload = {
- "AgentId": "demo-agent",
- "InvocationId": "resp-invalid-input",
- "Messages": [{"role": "user", "content": "你好"}],
- **extra,
- }
- try:
- events = [event async for event in StudioSharedWebBridge(studio).stream_run(payload)]
- assert len(events) == 1
- assert "event: response.failed" in events[0]
- assert message in events[0]
- finally:
- await studio.aclose()
-
-
-@pytest.mark.asyncio
-async def test_stream_does_not_acknowledge_when_durable_run_never_starts(tmp_path, monkeypatch):
- studio = StudioService(tmp_path)
- studio.create_agent(agent_id="demo-agent", name="Demo Agent")
- bridge = StudioSharedWebBridge(studio)
- started = asyncio.Event()
-
- monkeypatch.setattr(bridge, "_select_build_model", lambda *_args: "test-model")
- monkeypatch.setattr(bridge, "_ensure_build", AsyncMock(return_value=SimpleNamespace(
- id="b", runtime_lock={"model": "test-model", "models": ["test-model"]},
- )))
- monkeypatch.setattr(bridge, "_validate_conversation_turn", lambda **_kwargs: None)
-
- async def execute(**_kwargs):
- started.set()
- raise RuntimeError("test must close before execution completes")
-
- monkeypatch.setattr(bridge, "_execute_run", execute)
- stream = bridge.stream_run(
- {
- "AgentId": "demo-agent",
- "SessionId": "ses-ack",
- "InvocationId": "resp-ack",
- "Messages": [{"role": "user", "content": "hello"}],
- }
- )
- first = await anext(stream)
- assert "event: response.failed" in first
- assert started.is_set()
- await stream.aclose()
- await studio.aclose()
-
-
-@pytest.mark.asyncio
-async def test_stream_builds_before_validating_cold_provider_model(tmp_path, monkeypatch):
- studio = StudioService(tmp_path)
- studio.create_agent(agent_id="demo-agent", name="Demo Agent")
- bridge = StudioSharedWebBridge(studio)
- calls: list[str] = []
-
- async def ensure_build(_agent_id):
- calls.append("build")
- return SimpleNamespace(id="b")
-
- def select_model(*_args):
- calls.append("model")
- assert calls == ["build", "model"]
- return "test-model"
-
- monkeypatch.setattr(bridge, "_ensure_build", ensure_build)
- monkeypatch.setattr(bridge, "_select_build_model", select_model)
- monkeypatch.setattr(bridge, "_validate_conversation_turn", lambda **_kwargs: None)
- monkeypatch.setattr(
- bridge,
- "_execute_run",
- AsyncMock(side_effect=RuntimeError("stop after preflight")),
- )
-
- events = [
- event
- async for event in bridge.stream_run(
- {
- "AgentId": "demo-agent",
- "InvocationId": "resp-cold-model",
- "Messages": [{"role": "user", "content": "hello"}],
- }
- )
- ]
- assert calls == ["build", "model"]
- assert any("event: response.failed" in event for event in events)
- await studio.aclose()
-
-
-@pytest.mark.asyncio
-async def test_stream_projects_user_cancellation_as_cancelled_not_failed(
- tmp_path, monkeypatch
-):
- studio = StudioService(tmp_path)
- studio.create_agent(agent_id="demo-agent", name="Demo Agent")
- bridge = StudioSharedWebBridge(studio)
-
- monkeypatch.setattr(bridge, "_select_build_model", lambda *_args: "test-model")
- monkeypatch.setattr(bridge, "_ensure_build", AsyncMock(return_value=SimpleNamespace(
- id="b", runtime_lock={"model": "test-model", "models": ["test-model"]},
- )))
- monkeypatch.setattr(bridge, "_validate_conversation_turn", lambda **_kwargs: None)
-
- async def execute(**_kwargs):
- raise StudioError("RUN_CANCELLED", "运行已取消", status_code=409)
-
- monkeypatch.setattr(bridge, "_execute_run", execute)
- events = [
- event
- async for event in bridge.stream_run(
- {
- "AgentId": "demo-agent",
- "SessionId": "ses-cancelled",
- "InvocationId": "resp-cancelled",
- "Messages": [{"role": "user", "content": "hello"}],
- }
- )
- ]
-
- assert any("event: response.cancelled" in event for event in events)
- assert not any("event: response.failed" in event for event in events)
- await studio.aclose()
-
-
-def test_failed_run_output_prefers_terminal_error_over_retry_progress() -> None:
- run = SimpleNamespace(
- status=RunStatus.FAILED,
- output="模型服务繁忙(timeout),1 秒后自动重试(第 2/2 次)",
- error={"message": "model stream made no progress for 60 seconds"},
- )
-
- assert StudioSharedWebBridge._run_output(run) == (
- "model stream made no progress for 60 seconds"
- )
-
-
-def test_shared_chat_runs_and_replays_two_turn_session(tmp_path: Path):
- model_client = RecordingModelClient()
- runtime_fixture = RuntimeFixture(
- _shared_runtime_events,
- runtime_types=("langgraph",),
- )
- service = StudioService(
- tmp_path,
- model_client=model_client,
- runtime_executor=runtime_fixture.executor,
- )
- app = create_studio_app(
- tmp_path,
- service=service,
- security_enabled=False,
- )
-
- with TestClient(app) as client:
- _create_agent(client)
- first_stream = _run_shared_chat(
- client,
- session_id="ses_shared",
- invocation_id="invocation-one",
- text="第一轮",
- )
- assert "response.output_text.delta" in first_stream
- assert "共享会话回复 1" in first_stream
- assert "response.completed" in first_stream
-
- second_stream = _run_shared_chat(
- client,
- session_id="ses_shared",
- invocation_id="invocation-two",
- text="第二轮",
- )
- assert "共享会话回复 2" in second_stream
- conversation = runtime_fixture.start_requests[-1].conversation_preprocessing()
- assert conversation is not None
- assert [message["role"] for message in conversation.messages] == [
- "user",
- "assistant",
- "user",
- ]
-
- sessions = client.post(
- "/agentengine/api/v1/ListSessions",
- json={"AgentId": "demo-agent", "Page": 1, "PageSize": 30},
- ).json()["Data"]
- assert sessions["Total"] == 1
- assert sessions["Sessions"][0]["SessionId"] == "ses_shared"
- assert sessions["Sessions"][0]["TokenUsage"]["turns"] == 2
-
- messages = client.post(
- "/agentengine/api/v1/ListSessionMessages",
- json={"SessionId": "ses_shared", "Limit": 50},
- ).json()["Data"]
- assert messages["LatestSeqId"] == 4
- assert [message["Role"] for message in messages["Messages"]] == [
- "user",
- "assistant",
- "user",
- "assistant",
- ]
- assert messages["Messages"][-1]["Content"]["text"] == "共享会话回复 2"
-
- deleted = client.post(
- "/agentengine/api/v1/DeleteSession",
- json={"SessionId": "ses_shared"},
- )
- assert deleted.status_code == 200
- sessions_after_delete = client.post(
- "/agentengine/api/v1/ListSessions",
- json={"AgentId": "demo-agent"},
- ).json()["Data"]
- assert sessions_after_delete["Total"] == 0
-
-
-@pytest.mark.asyncio
-async def test_shared_chat_history_preserves_a2ui_activity(tmp_path: Path):
- service = StudioService(tmp_path)
- service.create_agent(agent_id="demo-agent", name="Demo Agent")
- record = RunRecord(
- id="run_a2ui",
- build_id="build_a2ui",
- agent_id="demo-agent",
- session_id="ses_a2ui",
- trace_id="trace_a2ui",
- status=RunStatus.COMPLETED,
- input="打开配置面板",
- output="请完成配置。",
- started_at=datetime.now(timezone.utc),
- completed_at=datetime.now(timezone.utc),
- )
- service.event_store.create(record)
- operations = [
- {
- "version": "v0.9",
- "createSurface": {
- "surfaceId": "surface-config",
- "catalogId": "https://a2ui.org/specification/v0_9/basic_catalog.json",
- },
- }
- ]
- service.event_store.append(
- record.id,
- "a2ui.surface.created",
- {
- "surfaceId": "surface-config",
- "a2ui_operations": operations,
- },
- )
-
- messages = await StudioSharedWebBridge(service).list_messages("ses_a2ui")
- assistant = messages["Messages"][1]
- assert assistant["Activities"] == [
- {
- "SeqId": 1,
- "Type": "a2ui.surface.created",
- "MessageId": "run_a2ui:assistant",
- "SurfaceId": "surface-config",
- "Content": {"a2ui_operations": operations},
- }
- ]
-
-
-def test_shared_chat_api_requires_local_studio_session(tmp_path: Path):
- service = StudioService(tmp_path)
- service.create_agent(agent_id="demo-agent", name="Demo Agent")
- app = create_studio_app(
- tmp_path,
- service=service,
- session_token="local-session-token-that-is-long-enough",
- csrf_token="csrf-token-that-is-long-enough",
- security_enabled=True,
- )
-
- with TestClient(app) as client:
- denied = client.post(
- "/agentengine/api/v1/GetAgentUiBootstrap",
- json={"AgentId": "demo-agent"},
- )
- assert denied.status_code == 401
-
- client.get("/")
- allowed = client.post(
- "/agentengine/api/v1/GetAgentUiBootstrap",
- json={"AgentId": "demo-agent"},
- )
- assert allowed.status_code == 200
- assert allowed.json()["Data"]["Agent"]["AgentId"] == "demo-agent"
- assert allowed.json()["Data"]["Capabilities"]["InteractionV1"] is True
-
-
-def test_shared_chat_submit_interaction_returns_canonical_receipt(tmp_path: Path):
- service = StudioService(tmp_path)
- service.create_agent(agent_id="demo-agent", name="Demo Agent")
- submitted: list[dict] = []
-
- async def submit_interaction(run_id: str, interaction_id: str, **kwargs):
- submitted.append({"run_id": run_id, "interaction_id": interaction_id, **kwargs})
- return {"resolutionEventId": 8, "eventId": 9}
-
- service.run_service.submit_interaction = submit_interaction # type: ignore[method-assign]
- app = create_studio_app(tmp_path, service=service, security_enabled=False)
-
- with TestClient(app) as client:
- response = client.post(
- "/agentengine/api/v1/SubmitInteraction",
- json={
- "AgentId": "demo-agent",
- "SessionId": "session-1",
- "RunId": "run-1",
- "InteractionId": "approval-1",
- "ExpectedRevision": 1,
- "Action": "approve",
- "Response": {"decision": "approve"},
- "IdempotencyKey": "interaction:approval-1:revision-1",
- },
- )
-
- assert response.status_code == 200
- assert response.json()["Data"] == {
- "schema_version": 1,
- "command_id": "9",
- "status": "accepted",
- "message_id": None,
- "run_id": "run-1",
- "accepted_seq": 9,
- }
- assert submitted == [
- {
- "run_id": "run-1",
- "interaction_id": "approval-1",
- "name": "approve",
- "data": {"decision": "approve"},
- "expected_revision": 1,
- "idempotency_key": "interaction:approval-1:revision-1",
- }
- ]
-
-
-@pytest.mark.asyncio
-async def test_responses_approval_resume_submits_pending_interaction() -> None:
- record = SimpleNamespace(
- id="run-1",
- model="test-model",
- status=RunStatus.WAITING_INPUT,
- )
- interaction = SimpleNamespace(
- type="a2ui.interaction",
- data={
- "interactionId": "approval-1",
- "callId": "call-1",
- "revision": 2,
- },
- )
- submit = AsyncMock(return_value={"status": "accepted"})
- studio = SimpleNamespace(
- event_store=SimpleNamespace(
- get=Mock(return_value=record),
- events=Mock(return_value=[interaction]),
- ),
- run_service=SimpleNamespace(submit_interaction=submit),
- )
- bridge = StudioSharedWebBridge(studio)
- bridge._run_ids_by_invocation["response-1"] = "run-1"
-
- resumed = await bridge._submit_response_resume(
- previous_response_id="response-1",
- response_id="response-2",
- resume_input={
- "type": "mcp_approval_response",
- "approval_request_id": "approval-1",
- "approve": True,
- },
- )
-
- assert resumed is record
- submit.assert_awaited_once_with(
- "run-1",
- "approval-1",
- name="approve",
- data={"decision": "approve"},
- expected_revision=2,
- idempotency_key="responses:response-2:approval-1:2",
- )
- assert bridge.resolve_run_reference("response-2") == "run-1"
-
-
-def test_shared_response_approval_item_uses_interaction_identity():
- event_name, payload = StudioSharedWebBridge._response_item_event(
- "approval.requested",
- {
- "approvalId": "approval-1",
- "callId": "call-1",
- "runId": "run-1",
- "kind": "command",
- "detail": {"command": "echo safe"},
- },
- {},
- )
-
- assert event_name == "response.output_item.added"
- assert payload["item"] == {
- "id": "approval-1",
- "call_id": "call-1",
- "type": "mcp_approval_request",
- "name": "command",
- "arguments": '{"command": "echo safe"}',
- "run_id": "run-1",
- "status": "in_progress",
- }
-
-
-@pytest.mark.parametrize("status", [RunStatus.RUNNING, RunStatus.WAITING_INPUT])
-def test_session_active_run_survives_newer_failed_turn(status):
- bridge = StudioSharedWebBridge.__new__(StudioSharedWebBridge)
- active = RunRecord(
- id="active",
- build_id="b",
- agent_id="a",
- session_id="s",
- trace_id="t1",
- status=status,
- input="first",
- started_at=datetime(2026, 9, 7, tzinfo=timezone.utc),
- )
- failed = RunRecord(
- id="failed",
- build_id="b",
- agent_id="a",
- session_id="s",
- trace_id="t2",
- status=RunStatus.FAILED,
- input="second",
- started_at=datetime(2026, 9, 8, tzinfo=timezone.utc),
- )
- result = bridge._session_record([active, failed])
- assert result["ActiveInvocationId"] == "active"
- assert result["ActiveRunStatus"] == "running"
-
-
-@pytest.mark.asyncio
-async def test_shared_ui_form_keeps_response_open_until_execution_finishes(tmp_path, monkeypatch):
- studio = StudioService(tmp_path)
- bridge = StudioSharedWebBridge(studio)
- release = asyncio.Event()
- record = RunRecord(id="waiting", build_id="b", agent_id="a", session_id="s",
- trace_id="t", input="ask", status=RunStatus.COMPLETED, output="done")
- monkeypatch.setattr(bridge, "resolve_agent_id", lambda value: "a")
- monkeypatch.setattr(bridge, "_select_model", lambda *args: "test-model")
- monkeypatch.setattr(bridge, "_ensure_build", AsyncMock(return_value=SimpleNamespace(
- id="b", runtime_lock={"model": "test-model", "models": ["test-model"]},
- )))
- monkeypatch.setattr(bridge, "_validate_conversation_turn", lambda **kwargs: None)
-
- async def execute(**kwargs):
- bridge._run_ids_by_invocation[kwargs["invocation_id"]] = record.id
- await release.wait()
- return record
-
- sent = False
-
- async def project(**kwargs):
- nonlocal sent
- if sent:
- return []
- sent = True
- return [("a2ui.interaction", {"kind": "form", "interactionId": "q"})]
-
- monkeypatch.setattr(bridge, "_execute_run", execute)
- monkeypatch.setattr(bridge, "_project_response_events", project)
- stream = bridge.stream_run({
- "AgentId": "a", "SessionId": "s",
- "Messages": [{"role": "user", "content": "ask"}],
- }, shared_ui=True)
- try:
- assert "response.created" in await asyncio.wait_for(anext(stream), timeout=5)
- assert "response.in_progress" in await asyncio.wait_for(anext(stream), timeout=5)
- assert "a2ui.interaction" in await asyncio.wait_for(anext(stream), timeout=5)
- assert "keep-alive" in await asyncio.wait_for(anext(stream), timeout=2)
- release.set()
- remaining = "".join([frame async for frame in stream])
- assert "response.completed" in remaining
- finally:
- release.set()
- await stream.aclose()
- await studio.aclose()
-
-
-@pytest.mark.parametrize("reference", ["client-invocation", "canonical-run"])
-async def test_cancel_accepts_the_canonical_identity_reported_by_get_session(reference):
- cancelled = []
- checked = []
- cancelled_runs = []
-
- async def cancel_run(run_id):
- cancelled_runs.append(run_id)
-
- bridge = StudioSharedWebBridge(SimpleNamespace(
- _require_direct_run=checked.append,
- operations=SimpleNamespace(cancel=cancelled.append),
- run_service=SimpleNamespace(cancel_run=cancel_run),
- ))
- bridge._run_ids_by_invocation["client-invocation"] = "canonical-run"
- bridge._operations_by_invocation["client-invocation"] = "operation"
- assert (await bridge.cancel_run(reference))["Cancelled"] is True
- assert cancelled_runs == ["canonical-run"]
- assert checked == ["canonical-run"]
-
-
-@pytest.mark.asyncio
-async def test_run_subscription_waits_through_user_input_and_replays_terminal(tmp_path):
- studio = StudioService(tmp_path)
- bridge = StudioSharedWebBridge(studio)
- record = RunRecord(
- id="waiting",
- build_id="b",
- agent_id="a",
- session_id="s",
- trace_id="t",
- input="ask",
- status=RunStatus.WAITING_INPUT,
- )
- studio.event_store.create(record)
- studio.event_store.append(record.id, "a2ui.interaction", {"interactionId": "q"})
- stream = bridge.subscribe_run_events("s", record.id, after_seq_id=0)
- first = await anext(stream)
- assert "a2ui.interaction" in first
- # A waiting request is live; subscription must not emit [DONE].
- heartbeat = await anext(stream)
- assert "[DONE]" not in heartbeat
- assert "ping" in heartbeat
- record.status = RunStatus.COMPLETED
- studio.event_store.save(record)
- studio.event_store.append(record.id, "run.completed", {})
- terminal = await anext(stream)
- assert "run.completed" in terminal
- assert "[DONE]" in await anext(stream)
- await stream.aclose()
- await studio.aclose()
-
-
-@pytest.mark.asyncio
-async def test_history_has_one_activity_per_surface_snapshot(tmp_path):
- studio = StudioService(tmp_path)
- bridge = StudioSharedWebBridge(studio)
- record = RunRecord(
- id="r", build_id="b", agent_id="a", session_id="s", trace_id="t", input="ask"
- )
- studio.event_store.create(record)
- operations = [{"createSurface": {"surfaceId": "input-q"}}]
- for kind in ["a2ui.surface.begin", "a2ui.surface.end"]:
- studio.event_store.append("r", kind, {"surfaceId": "input-q", "a2uiOperations": operations})
- activities = await bridge._run_activities(record)
- assert len(activities) == 1
- assert activities[0]["Content"]["a2ui_operations"] == operations
- await studio.aclose()
-
-
-def test_model_input_budget_is_not_reported_as_model_window():
- from types import SimpleNamespace
-
- draft = SimpleNamespace(spec=SimpleNamespace(context=SimpleNamespace(max_input_tokens=32000)))
- spec = ModelSpec.model_validate(_valid_spec()["model"])
- descriptor = StudioSharedWebBridge._model_descriptor_from_spec(draft, spec)
- assert descriptor["context_window_tokens"] is None
- assert descriptor["input_budget_tokens"] == 32000
-
-
-@pytest.mark.asyncio
-async def test_compaction_rejects_active_and_foreign_sessions(tmp_path):
- from types import SimpleNamespace
-
- from ksadk.studio.errors import StudioError
-
- store = SimpleNamespace(
- list_runs=lambda **kwargs: (
- [
- SimpleNamespace(
- runtime_type="codex",
- status=RunStatus.WAITING_INPUT,
- )
- ]
- if kwargs["agent_id"] == "owner"
- else []
- )
- )
- bridge = StudioSharedWebBridge(
- SimpleNamespace(
- event_store=store,
- run_service=SimpleNamespace(_active_sessions=set()),
- _require_direct_session=lambda _session_id: None,
- )
- )
- with pytest.raises(StudioError) as active:
- await bridge.compact_session("owner", "s")
- assert active.value.code == "SESSION_RUN_ACTIVE"
- with pytest.raises(StudioError) as foreign:
- await bridge.compact_session("other", "s")
- assert foreign.value.status_code == 404
-
-
-def test_shared_history_uses_public_run_identity_without_mutating_native_event():
- native = {"run_id": "native-run", "event_type": "item.completed", "item_id": "answer"}
- persisted = {"runtimeEvent": native, "text": "answer"}
- projected = StudioSharedWebBridge._shared_event_content(persisted, "studio-run")
- assert projected["runtimeEvent"]["run_id"] == "studio-run"
- assert native["run_id"] == "native-run"
- assert projected["runtimeEvent"]["item_id"] == "answer"
-
-
-def test_completed_harness_history_hides_non_authoritative_final_snapshot(
- tmp_path: Path,
-) -> None:
- studio = StudioService(tmp_path)
- bridge = StudioSharedWebBridge(studio)
- run = RunRecord(
- id="run-current",
- build_id="build",
- agent_id="agent",
- session_id="session",
- trace_id="trace",
- runtime_type="harness",
- status=RunStatus.COMPLETED,
- input="new task",
- output="current answer",
- )
- stale = {
- "runtimeEvent": {
- "run_id": "native-run",
- "item_kind": "message",
- "source": {
- "metadata": {
- "native_event_type": "text.completed",
- "phase": "final_answer",
- }
- },
- "snapshot": {
- "parts": [
- {"content_type": "text", "part_id": "text-0", "text": "old answer"}
- ]
- },
- }
- }
-
- presented = bridge._presentation_event_content(stale, run)["runtimeEvent"]
-
- assert presented["run_id"] == run.id
- assert presented["item_kind"] == "status"
- rendered = presented["snapshot"]["parts"][0]["text"]
- assert "old answer" not in rendered
- assert "non_authoritative_final" in rendered
- assert stale["runtimeEvent"]["item_kind"] == "message"
-
-
-def test_shared_history_keeps_resumable_interruption_pending():
- pending = {"runtimeEvent": {"interaction_id": "question-1"}}
- assert StudioSharedWebBridge._shared_event_type("run.interrupted", pending) == "run.waiting"
- assert StudioSharedWebBridge._shared_event_type("run.interrupted", {}) == "run.interrupted"
- assert StudioSharedWebBridge._shared_event_type("run.cancelled", pending) == "run.cancelled"
-
-
-@pytest.mark.asyncio
-async def test_old_interaction_receipt_replay_preserves_new_pending_form(tmp_path):
- import hashlib
- import json
-
- studio = StudioService(tmp_path)
- record = RunRecord(
- id="run_replay", build_id="b", agent_id="a", session_id="s", trace_id="t",
- input="ask", status=RunStatus.WAITING_INPUT,
- )
- studio.event_store.create(record)
- digest = hashlib.sha256(json.dumps(
- {"name": "approve", "data": {}}, sort_keys=True, separators=(",", ":"),
- ).encode()).hexdigest()
- receipt = {"interactionId": "old-approval", "revision": 2}
- studio.event_store.append("run_replay", "a2ui.action", {
- "interactionId": "old-approval", "revision": 2, "idempotencyKey": "old-key",
- "requestDigest": digest, "receipt": receipt,
- })
- studio.event_store.append("run_replay", "a2ui.interaction", {
- "interactionId": "new-form", "revision": 1, "kind": "form",
- })
- studio.run_service._waiting_modes["run_replay"] = "resume"
- try:
- result = await studio.run_service.submit_interaction(
- "run_replay", "old-approval", name="approve", data={},
- expected_revision=1, idempotency_key="old-key",
- )
- assert result == receipt
- assert studio.event_store.get("run_replay").status == RunStatus.WAITING_INPUT
- assert studio.run_service._waiting_modes["run_replay"] == "resume"
- history = await StudioSharedWebBridge(studio).list_messages("s")
- assert history["Messages"][-1]["Content"]["text"] == ""
- finally:
- await studio.aclose()
-
-
-@pytest.mark.parametrize("legacy_route", [False, True])
-def test_cold_chat_model_catalog_reports_provider_window(tmp_path, monkeypatch, legacy_route):
- from ksadk.studio.contracts import AgentSpec, Instructions, RuntimeRef
-
- async def catalog(**kwargs):
- return [{"id": "deepseek-v4-flash", "context_window_tokens": 1_024_000}]
-
- monkeypatch.setattr("ksadk.studio.resource_catalog.fetch_provider_model_catalog", catalog)
- studio = StudioService(
- tmp_path, codex_runtime_inspector=lambda runtime: ("0.8.4", "0.147.0", "codex-cli 0.147.0"),
- )
- studio.create_studio_agent(
- agent_id="cold-model", name="Cold Model",
- spec=AgentSpec(
- instructions=Instructions(system="Answer the user."),
- runtime=RuntimeRef(type="codex", version="0.147.0"),
- model=ModelSpec(
- model="deepseek-v4-flash",
- endpoint_url="https://model.example.com/v1/chat/completions",
- credential_ref="env://MODEL_API_KEY",
- ),
- ),
- )
- assert not studio.catalog._provider_models
- with TestClient(create_studio_app(tmp_path, service=studio, security_enabled=False)) as client:
- response = (client.get("/api/v1/agents/cold-model/models") if legacy_route else client.post(
- "/agentengine/api/v1/ListAgentModels", json={"AgentId": "cold-model"},
- ))
- assert response.status_code == 200
- data = response.json() if legacy_route else response.json()["Data"]
- assert data["Models"][0]["context_window_tokens"] == 1_024_000
-
-
-def test_cold_build_discovers_provider_model_before_submit(tmp_path, monkeypatch):
- from ksadk.studio.contracts import (
- AgentBindings,
- AgentSpec,
- Instructions,
- NetworkPolicy,
- RuntimeRef,
- SecuritySpec,
- )
-
- async def catalog(**kwargs):
- return [{"id": "deepseek-v4-flash", "context_window_tokens": 1_024_000}]
-
- monkeypatch.setattr("ksadk.studio.resource_catalog.fetch_provider_model_catalog", catalog)
- studio = StudioService(
- tmp_path,
- codex_runtime_inspector=lambda runtime: (
- "0.8.4",
- "0.147.0",
- "codex-cli 0.147.0",
- ),
- )
- asyncio.run(
- studio.catalog.discover_provider_models(
- api_base="https://model.example.com/v1",
- api_key=None,
- current_model="deepseek-v4-flash",
- )
- )
- studio.create_studio_agent(
- agent_id="cold-build",
- name="Cold Build",
- spec=AgentSpec(
- instructions=Instructions(system="Answer the user."),
- runtime=RuntimeRef(type="codex", version="0.147.0"),
- bindings=AgentBindings(
- model_profile_id="model:provider:deepseek-v4-flash:live",
- model_profile_ids=["model:provider:deepseek-v4-flash:live"],
- ),
- security=SecuritySpec(
- allowed_permissions=["process:host-user"],
- network=NetworkPolicy(allowed_hosts=["model.example.com"])
- ),
- ),
- )
- studio.catalog._provider_models.clear()
- assert not studio.catalog._provider_models
-
- with TestClient(create_studio_app(tmp_path, service=studio, security_enabled=False)) as client:
- provider_manifest = _codex_provider_manifest()
- provider_manifests = {CODEX_PROVIDER_REF: provider_manifest}
- studio._active_provider_manifests.update(provider_manifests)
- studio.plugin_compositions.replace_provider_registrations(provider_manifests)
- submitted = client.post(
- "/api/v1/agents/cold-build/builds",
- headers={"Idempotency-Key": "cold-build-r1"},
- json={"revision": 1},
- )
- assert submitted.status_code == 202
- operation_id = submitted.json()["id"]
- for _ in range(200):
- operation = client.get(f"/api/v1/operations/{operation_id}").json()
- if operation["status"] in {"SUCCEEDED", "FAILED"}:
- break
- assert operation["status"] == "SUCCEEDED", operation
diff --git a/tests/studio/test_shared_web_final_snapshot.py b/tests/studio/test_shared_web_final_snapshot.py
deleted file mode 100644
index 46c659aef..000000000
--- a/tests/studio/test_shared_web_final_snapshot.py
+++ /dev/null
@@ -1,167 +0,0 @@
-"""Responses delivery must replace streamed previews with the committed answer."""
-
-import asyncio
-import json
-from types import SimpleNamespace
-from unittest.mock import AsyncMock
-
-import pytest
-
-from ksadk.studio.contracts import RunRecord, RunStatus
-from ksadk.studio.errors import StudioError
-from ksadk.studio.service import StudioService
-from ksadk.studio.shared_web import StudioSharedWebBridge
-
-
-def _frame(frame):
- return json.loads(next(line[6:] for line in frame.splitlines() if line.startswith("data: ")))
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize("preview", ["ACK", "unverified preview", ""])
-async def test_committed_answer_has_explicit_done_after_any_preview(tmp_path, monkeypatch, preview):
- studio = StudioService(tmp_path)
- bridge = StudioSharedWebBridge(studio)
- release = asyncio.Event()
- record = RunRecord(
- id="canonical-run", build_id="b", agent_id="a", session_id="s",
- trace_id="t", input="ask", status=RunStatus.COMPLETED, output="ACK",
- )
- monkeypatch.setattr(bridge, "resolve_agent_id", lambda _: "a")
- monkeypatch.setattr(bridge, "_ensure_build", AsyncMock(return_value=SimpleNamespace(
- id="b", runtime_lock={"model": "test-model", "models": ["test-model"]},
- )))
- monkeypatch.setattr(bridge, "_validate_conversation_turn", lambda **_: None)
- # A document-linked answer must match response.completed exactly.
- monkeypatch.setattr(
- "ksadk.studio.shared_web.link_run_documents", lambda *_: "ACK [artifact](artifact:one)"
- )
- executions = []
-
- async def execute(**kwargs):
- executions.append(kwargs["invocation_id"])
- bridge._run_ids_by_invocation[kwargs["invocation_id"]] = record.id
- await release.wait()
- return record
-
- sent = False
-
- async def project(**_):
- nonlocal sent
- if sent:
- return []
- sent = True
- if not preview:
- return []
- return [("response.output_text.delta", bridge._response_delta_payload(
- "response.output_text.delta", invocation_id="invocation", delta=preview,
- ))]
-
- monkeypatch.setattr(bridge, "_execute_run", execute)
- monkeypatch.setattr(bridge, "_project_response_events", project)
- stream = bridge.stream_run({
- "AgentId": "a", "SessionId": "s", "InvocationId": "invocation",
- "Messages": [{"role": "user", "content": "ask"}],
- }, shared_ui=True)
- try:
- assert _frame(await anext(stream))["type"] == "response.created"
- assert _frame(await anext(stream))["type"] == "response.in_progress"
- if preview:
- assert _frame(await anext(stream))["delta"] == preview
- release.set()
- frames = [_frame(frame) async for frame in stream if frame.startswith("event:")]
- done = [frame for frame in frames if frame["type"] == "response.output_text.done"]
- assert len(done) == 1
- completed = frames[-1]
- assert completed["type"] == "response.completed"
- assert done[0] == {
- "type": "response.output_text.done", "item_id": "msg_invocation",
- "output_index": 0, "content_index": 0,
- "text": completed["response"]["output"][0]["content"][0]["text"],
- }
- assert done[0]["text"] == "ACK [artifact](artifact:one)"
- assert executions == ["invocation"]
- finally:
- release.set()
- await stream.aclose()
- await studio.aclose()
-
-
-@pytest.mark.asyncio
-@pytest.mark.parametrize("code", ["RUN_CANCELLED", "RUN_FAILED"])
-async def test_unsuccessful_execution_does_not_publish_final_text(tmp_path, monkeypatch, code):
- studio = StudioService(tmp_path)
- bridge = StudioSharedWebBridge(studio)
- monkeypatch.setattr(bridge, "resolve_agent_id", lambda _: "a")
- monkeypatch.setattr(bridge, "_ensure_build", AsyncMock(return_value=SimpleNamespace(
- id="b", runtime_lock={"model": "test-model", "models": ["test-model"]},
- )))
- monkeypatch.setattr(bridge, "_validate_conversation_turn", lambda **_: None)
-
- async def execute(**kwargs):
- bridge._run_ids_by_invocation[kwargs["invocation_id"]] = "canonical-run"
- raise StudioError(code, "execution was not completed")
-
- monkeypatch.setattr(bridge, "_execute_run", execute)
- try:
- frames = [_frame(frame) async for frame in bridge.stream_run({
- "AgentId": "a", "SessionId": "s", "InvocationId": "invocation",
- "Messages": [{"role": "user", "content": "ask"}],
- }, shared_ui=True) if frame.startswith("event:")]
- assert frames[-1]["type"] == (
- "response.cancelled" if code == "RUN_CANCELLED" else "response.failed"
- )
- assert all(frame["type"] != "response.output_text.done" for frame in frames)
- finally:
- await studio.aclose()
-
-
-@pytest.mark.asyncio
-async def test_native_provisional_draft_is_not_promoted_to_responses_answer(tmp_path):
- from tests.studio.response_projection_fixtures import replay_responses
-
- def native(kind, **flags):
- return {"source": {"metadata": {"engine_kind": "native",
- "native_event_kind": kind, **flags}}}
-
- entries = [
- ("message.delta", {"text": "unfinished draft with code",
- "runtimeEvent": native("text.delta", provisional=True)}),
- ("message.completed", {"text": "", "runtimeEvent": native(
- "effect.received", provisional=True, provisional_retired=True)}),
- ("message.delta", {"text": "FINAL_DELIVERY",
- "runtimeEvent": native("text.completed")}),
- ]
- responses = await replay_responses(tmp_path, entries)
- output = [p["delta"] for k, p in responses if k == "response.output_text.delta"]
- assert output == ["FINAL_DELIVERY"]
- assert all("unfinished draft" not in str(p) for k, p in responses)
-
-
-@pytest.mark.asyncio
-async def test_native_progress_uses_process_channel_without_reclassifying_answer(tmp_path):
- from tests.studio.response_projection_fixtures import replay_responses
-
- responses = await replay_responses(tmp_path, [("message.delta", {
- "text": "Running workspace verification", "runtimeEvent": {"source": {
- "metadata": {"engine_kind": "native", "native_event_kind": "run.progress"}
- }}
- })])
- assert [k for k, p in responses] == ["response.reasoning_summary_text.delta"]
-
-
-@pytest.mark.asyncio
-async def test_sealed_tool_commentary_remains_visible_once(tmp_path):
- from tests.studio.response_projection_fixtures import replay_responses
-
- metadata = {"engine_kind": "native", "native_event_kind": "text.delta",
- "provisional": True}
- responses = await replay_responses(tmp_path, [
- ("message.delta", {"text": "Now running tests.", "runtimeEvent": {
- "source": {"metadata": metadata}}}),
- ("message.completed", {"text": "Now running tests.", "runtimeEvent": {
- "source": {"metadata": {**metadata, "native_event_kind": "effect.received"}}}}),
- ])
- assert [p["delta"] for k, p in responses if k == "response.output_text.delta"] == [
- "Now running tests."
- ]
diff --git a/tests/studio/test_style_system.py b/tests/studio/test_style_system.py
deleted file mode 100644
index f4690d7b1..000000000
--- a/tests/studio/test_style_system.py
+++ /dev/null
@@ -1,514 +0,0 @@
-from __future__ import annotations
-
-import hashlib
-import json
-import re
-from pathlib import Path
-
-import pytest
-
-REPOSITORY_ROOT = Path(__file__).resolve().parents[2]
-pytestmark = pytest.mark.skipif(
- not (REPOSITORY_ROOT / "ksadk/studio/react-ui/src").is_dir(),
- reason="editable Studio source is intentionally absent from the public candidate",
-)
-STYLESHEET = REPOSITORY_ROOT / "ksadk" / "studio" / "react-ui" / "src" / "studio.css"
-REACT_STYLESHEET = REPOSITORY_ROOT / "ksadk" / "studio" / "react-ui" / "src" / "index.css"
-APP_SOURCE = REPOSITORY_ROOT / "ksadk" / "studio" / "react-ui" / "src" / "App.tsx"
-RESPONSIVE_STYLESHEET = REPOSITORY_ROOT / "ksadk" / "studio" / "react-ui" / "src" / "responsive.css"
-THEME_STYLESHEET = REPOSITORY_ROOT / "ksadk" / "studio" / "react-ui" / "src" / "theme.css"
-CHAT_SOURCE = (
- REPOSITORY_ROOT / "ksadk" / "studio" / "react-ui" / "src" / "components" / "ChatWorkspace.tsx"
-)
-ORCHESTRATION_SOURCE = (
- REPOSITORY_ROOT / "ksadk" / "studio" / "react-ui" / "src" / "pages" / "OrchestrationPage.tsx"
-)
-OBSERVABILITY_SOURCE = (
- REPOSITORY_ROOT / "ksadk" / "studio" / "react-ui" / "src" / "pages" / "ObservabilityPage.tsx"
-)
-RUNTIME_RESOURCES_SOURCE = (
- REPOSITORY_ROOT / "ksadk" / "studio" / "react-ui" / "src" / "pages" / "RuntimeResourcesPage.tsx"
-)
-PACKAGE = REPOSITORY_ROOT / "ksadk" / "studio" / "react-ui" / "package.json"
-MAKEFILE = REPOSITORY_ROOT / "Makefile"
-
-
-TOKEN_STYLESHEET = STYLESHEET.with_name("studio-tokens.css")
-
-def _stylesheet_without_root() -> tuple[str, str]:
- stylesheet = STYLESHEET.read_text(encoding="utf-8")
- return TOKEN_STYLESHEET.read_text(encoding="utf-8") + stylesheet, stylesheet
-
-
-def _block(stylesheet: str, selector: str) -> str:
- start = stylesheet.find(selector)
- assert start >= 0, f"missing selector {selector}"
- return stylesheet[start : stylesheet.find("}", start)]
-
-
-def test_react_ci_gate_runs_protocol_and_component_suites() -> None:
- makefile = MAKEFILE.read_text(encoding="utf-8")
- target = makefile.split("studio-react-test: build-studio-static\n", 1)[1].split("\n\n", 1)[0]
-
- assert "npm --prefix ksadk/studio/react-ui test" in target
- assert "npm --prefix ksadk/studio/react-ui run test:ui" in target
-
-
-def test_typography_tokens_form_the_complete_product_scale() -> None:
- stylesheet, _ = _stylesheet_without_root()
- required_tokens = {
- "--font-sans",
- "--font-mono",
- "--font-size-caption",
- "--font-size-meta",
- "--font-size-control",
- "--font-size-body",
- "--font-size-subtitle",
- "--font-size-card-metric",
- "--font-size-section-title",
- "--font-size-page-title",
- "--font-size-metric",
- "--font-weight-regular",
- "--font-weight-medium",
- "--font-weight-semibold",
- "--line-height-caption",
- "--line-height-control",
- "--line-height-body",
- "--line-height-editor",
- "--line-height-title",
- }
-
- for token in required_tokens:
- assert re.search(rf"{re.escape(token)}\s*:", stylesheet), f"missing {token}"
-
-
-def test_component_surface_and_code_tokens_exist_in_both_themes() -> None:
- stylesheet = TOKEN_STYLESHEET.read_text(encoding="utf-8")
- common_root = _block(stylesheet, ":root {")
- light_root = common_root + _block(stylesheet, ":root:not(.dark) {")
- dark_root = common_root + _block(stylesheet, ":root.dark {")
- required = {
- "--surface-raised",
- "--surface-sunken",
- "--surface-hover",
- "--text-primary",
- "--text-label",
- "--text-faint",
- "--accent-strong",
- "--button-primary-bg",
- "--button-primary-bg-hover",
- "--button-primary-bg-active",
- "--button-primary-text",
- "--border-card",
- "--warning-text",
- "--code-token-keyword",
- "--code-token-string",
- "--code-token-function",
- }
- for token in required:
- assert f"{token}:" in light_root, f"missing light token {token}"
- assert f"{token}:" in dark_root, f"missing dark token {token}"
- assert "--code-bg: #202631" not in light_root
- assert "--code-bg: #090f19" not in dark_root
-
-
-def test_shared_component_css_uses_semantic_typography_tokens() -> None:
- _, component_css = _stylesheet_without_root()
- forbidden_declarations = {
- "font-size": r"font-size\s*:\s*\d",
- "font-weight": r"font-weight\s*:\s*\d",
- "line-height": r"line-height\s*:\s*(?:\d|\.\d)",
- }
-
- for name, pattern in forbidden_declarations.items():
- match = re.search(pattern, component_css)
- assert match is None, f"{name} must use a semantic token: {match.group(0)!r}"
-
- font_shorthands = re.findall(r"(? None:
- stylesheet, _ = _stylesheet_without_root()
- expected_contracts = {
- ".page-header h1": "--font-size-page-title",
- ".button,\n.icon-button": "--button-height",
- ".field label": "--font-size-control",
- ".status-badge": "--status-height",
- (
- 'input:not([type="checkbox"]):not([type="radio"]):not([type="range"])'
- ':not([type="file"]),\nselect {'
- ): "--control-height",
- }
-
- for selector, token in expected_contracts.items():
- assert token in _block(stylesheet, selector)
-
-
-def test_trace_explorer_keeps_nested_scroll_and_waterfall_layouts() -> None:
- stylesheet = STYLESHEET.read_text(encoding="utf-8")
- for selector, declarations in {
- ".trace-workbench {": ["grid-template-columns", "min-height: 0", "overflow: hidden"],
- ".trace-list {": ["overflow-y: auto", "min-height: 0"],
- ".trace-span-tree {": ["overflow: auto", "min-width: 0"],
- ".trace-detail-body {": ["overflow: auto", "min-height: 0"],
- ".trace-raw {": ["overflow: hidden", "background: var(--studio-surface)"],
- ".trace-raw-tree {": ["overflow: auto", "min-height: 0"],
- }.items():
- block = _block(stylesheet, selector)
- for declaration in declarations:
- assert declaration in block
-
-
-def test_react_chat_and_batch_surfaces_keep_bounded_layouts() -> None:
- stylesheet = REACT_STYLESHEET.read_text(encoding="utf-8")
- for selector, declarations in {
- ".chat-wrap {": ["min-height: 0", "overflow: hidden"],
- ".chat-host {": ["min-height: 0", "overflow: hidden"],
- ".chat-run-timeline {": ["overflow-y: auto"],
- ".skill-selection-toolbar {": ["display: flex", "justify-content: space-between"],
- }.items():
- block = _block(stylesheet, selector)
- for declaration in declarations:
- assert declaration in block
-
-
-def test_responsive_layer_is_the_final_layout_owner() -> None:
- entrypoint = REACT_STYLESHEET.read_text(encoding="utf-8")
- responsive = RESPONSIVE_STYLESHEET.read_text(encoding="utf-8")
-
- assert entrypoint.index('@import "./studio.css"') < entrypoint.index(
- '@import "./responsive.css"'
- )
- assert "@media (max-width: 1023px)" in responsive
- assert "@media (min-width: 1024px) and (max-width: 1439px)" in responsive
- assert "--studio-page-max: 1760px" in responsive
-
- for selector, declarations in {
- ".app-shell .data-scroll-region {": ["overflow-x: auto", "max-width: 100%"],
- '.create-shell[data-scroll-mode="workbench"] {': [
- "height: calc(100dvh - var(--studio-header-height))",
- "overflow: hidden",
- ],
- '.app-shell[data-view="conversations"] {\n height: 100dvh;': ["overflow: hidden"],
- '.app-shell[data-view="conversations"] #mainContent,': ["height: 100%"],
- ".overlay .drawer {": [
- "calc(100vw - 32px)",
- "calc(100dvh - 32px)",
- ],
- }.items():
- block = _block(responsive, selector)
- for declaration in declarations:
- assert declaration in block
-
-
-def test_theme_layer_supports_persisted_light_dark_and_system_modes() -> None:
- entrypoint = REACT_STYLESHEET.read_text(encoding="utf-8")
- theme = THEME_STYLESHEET.read_text(encoding="utf-8")
- app = APP_SOURCE.read_text(encoding="utf-8")
-
- assert (
- entrypoint.index('@import "./studio.css"')
- < entrypoint.index('@import "./theme.css"')
- < entrypoint.index('@import "./responsive.css"')
- )
- assert ":root.dark {" in TOKEN_STYLESHEET.read_text(encoding="utf-8")
- assert "color-scheme: dark" in TOKEN_STYLESHEET.read_text(encoding="utf-8")
- assert ".appearance-options {" in theme
- assert "useStudioTheme" in app
-
-
-def test_react_chat_composer_has_one_focus_boundary() -> None:
- stylesheet = REACT_STYLESHEET.read_text(encoding="utf-8")
- textarea_block = _block(stylesheet, ".chat-composer textarea {")
- assert "border: 0" in textarea_block
- assert "background: transparent" in textarea_block
- assert "box-shadow: none" in textarea_block
- assert ".chat-composer:focus-within {" in stylesheet
-
-
-def test_react_chat_uses_shared_protocol_and_asymmetric_messages() -> None:
- stylesheet = REACT_STYLESHEET.read_text(encoding="utf-8")
- source = CHAT_SOURCE.read_text(encoding="utf-8")
- package = PACKAGE.read_text(encoding="utf-8")
- vite_config = (REPOSITORY_ROOT / "ksadk" / "studio" / "react-ui" / "vite.config.ts").read_text(
- encoding="utf-8"
- )
-
- user_bubble = _block(stylesheet, ".chat-message-list .message.user .message-content {")
- assistant = _block(stylesheet, ".chat-message-list .message.assistant .message-content {")
- assert "margin-left: auto" in user_bubble
- assert "width: fit-content" in user_bubble
- assert "padding: 0" in assistant
- assert "ChatWorkspace" in source
- assert "AgentConversationTimeline" in source
- assert "AgentConversationComposer" in source
- assert "useAgentChat" in source
- # Facade ownership and lifecycle cancellation are exercised by the real
- # StudioChatApiFacade and ChatWorkspace behavior suites, not import text.
- reviewed = json.loads((PACKAGE.parent / "vendor/ksadk-web-source.json").read_text())
- metadata = json.loads(package)
- dependencies = metadata["dependencies"]
- if reviewed["registry_release"]:
- assert dependencies[reviewed["package_name"]] == reviewed["package_version"]
- lock = json.loads((PACKAGE.parent / "package-lock.json").read_text())
- installed = lock["packages"][f"node_modules/{reviewed['package_name']}"]
- assert installed["version"] == reviewed["package_version"]
- assert installed["resolved"] == reviewed["artifact_url"]
- assert installed["integrity"] == reviewed["artifact_integrity"]
- else:
- assert dependencies[reviewed["package_name"]] == f"file:vendor/{reviewed['artifact']}"
- artifact = PACKAGE.parent / "vendor" / reviewed["artifact"]
- assert artifact.is_file()
- assert hashlib.sha256(artifact.read_bytes()).hexdigest() == reviewed["artifact_sha256"]
- assert metadata["scripts"]["prebuild"] == "node scripts/verify-reviewed-web.mjs"
- verifier = (PACKAGE.parent / "scripts/verify-reviewed-web.mjs").read_text()
- assert 'manifest.registry_release ? "RELEASE_PROVENANCE.json" : "SOURCE_CANDIDATE.json"' in verifier
- assert "source.source_commit !== manifest.source_commit" in verifier
- assert "@kingsoftcloud/ksadk-web" not in vite_config
- # 没有本地 Agent 时仍可从账号目录选择云端 Agent,不再把会话入口
- # 强制重定向到创建页。
- assert "先创建 Agent 才能开始会话" not in APP_SOURCE.read_text(encoding="utf-8")
-
-
-def test_react_chat_keeps_compact_sessions_and_streaming_controls() -> None:
- stylesheet = REACT_STYLESHEET.read_text(encoding="utf-8")
- source = CHAT_SOURCE.read_text(encoding="utf-8")
-
- session = _block(stylesheet, ".chat-session-item {")
- assert "min-height: 34px" in session
- assert ".sr-only {" in stylesheet
- assert "@keyframes chat-message-enter" in stylesheet
- assert "@keyframes chat-stream-caret" in stylesheet
- assert "@media (prefers-reduced-motion: reduce)" in stylesheet
- assert "