Compare commits
44 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c051929f8c | |||
| 4814ec2363 | |||
| 98b9d612fa | |||
| 874873541d | |||
| ef9ac76f06 | |||
| ca9db195de | |||
| c1e16f2163 | |||
| 61d32fa00f | |||
| cddb3f8ccf | |||
| 87a938fe58 | |||
| 9157694412 | |||
| aa34314175 | |||
| c7fc386d0f | |||
| 6bd814e346 | |||
| aa25852091 | |||
| c2740cd282 | |||
| 23875bb3cc | |||
| ee1eab8408 | |||
| 2254ba7496 | |||
| 4866ad08b1 | |||
| 97ebc19313 | |||
| 946ac6f66a | |||
| 90ddee14c2 | |||
| f17f8ae8c8 | |||
| d713bfc5f9 | |||
| 27fe8c24ec | |||
| eef1e4e8c6 | |||
| a7a5905874 | |||
| 021537de56 | |||
| fdfd75790d | |||
| 3d1f8d9cf7 | |||
| eec37ab710 | |||
| 5f499ec1b0 | |||
| 2b5223097f | |||
| 1efbc289ba | |||
| 3c57c8b78b | |||
| 9c4500f9cb | |||
| 1e2c5a68cf | |||
| dc6991e6ef | |||
| cdf233378c | |||
| 23769e6ad4 | |||
| 9f8058223a | |||
| b483a34517 | |||
| de8c47c81c |
@@ -4,6 +4,10 @@
|
||||
|
||||
OpenSpec is the source of truth. Superpowers is the default workflow. Keep changes small, scoped, and verified.
|
||||
|
||||
## Communication
|
||||
|
||||
All agent output, code comments, commit messages, documentation, and artifacts must be in **English** unless the user explicitly requests another language.
|
||||
|
||||
## Priority order
|
||||
|
||||
1. Current user instruction
|
||||
|
||||
@@ -232,14 +232,6 @@ def upgrade() -> None:
|
||||
"writable": True,
|
||||
"owner": "user",
|
||||
},
|
||||
{
|
||||
"name": "ssh_keys",
|
||||
"target": "/home/user/.ssh",
|
||||
"source_type": "ssh_key",
|
||||
"mode": "0700",
|
||||
"file_mode": "0600",
|
||||
"readonly": True,
|
||||
},
|
||||
{
|
||||
"name": "pi_state",
|
||||
"target": "/tmp/.pi/agents",
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
"""fix code-server bind-addr to host in DB template
|
||||
|
||||
Revision ID: 2026_05_29_fix_code_server_bind_addr
|
||||
Revises: 2026_05_29_fix_web_tool_bind_address
|
||||
Create Date: 2026-05-29 15:00:00.000000
|
||||
|
||||
"""
|
||||
|
||||
from typing import Sequence
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = "2026_05_29_fix_code_server_bind_addr"
|
||||
down_revision: str | None = "2026_05_29_fix_web_tool_bind_address"
|
||||
branch_labels: Sequence[str] | None = None
|
||||
depends_on: Sequence[str] | None = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
conn = op.get_bind()
|
||||
|
||||
# Find code-server tool types with broken --bind-addr in compose template
|
||||
result = conn.execute(
|
||||
sa.text("""
|
||||
SELECT id, compose_template
|
||||
FROM tool_types
|
||||
WHERE name = 'code-server'
|
||||
AND compose_template LIKE '%--bind-addr%'
|
||||
""")
|
||||
).fetchall()
|
||||
|
||||
for tool_id, compose_template in result:
|
||||
updated = compose_template.replace(
|
||||
"--bind-addr 0.0.0.0:8443", "--host 0.0.0.0"
|
||||
).replace("--bind-addr", "--host 0.0.0.0")
|
||||
|
||||
conn.execute(
|
||||
sa.text("""
|
||||
UPDATE tool_types
|
||||
SET compose_template = :compose_template
|
||||
WHERE id = :id
|
||||
"""),
|
||||
{"compose_template": updated, "id": tool_id},
|
||||
)
|
||||
|
||||
print(
|
||||
f"Fixed code-server template ({tool_id}): replaced --bind-addr with --host"
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
pass
|
||||
@@ -0,0 +1,148 @@
|
||||
"""Fix code-server bind address to include port
|
||||
|
||||
Revision ID: 2026_05_29_fix_code_server_bind_addr_port
|
||||
Revises: 2026_05_29_remove_lsio_command_override
|
||||
Create Date: 2026-05-29 18:00:00.000000
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
import yaml
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = "2026_05_29_fix_code_server_bind_addr_port"
|
||||
down_revision: Union[str, None] = "2026_05_29_remove_lsio_command_override"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def _fix_tool_type_templates(conn) -> None:
|
||||
"""Fix code-server tool type templates with broken --host override."""
|
||||
result = conn.execute(
|
||||
sa.text("""
|
||||
SELECT id, compose_template, default_port
|
||||
FROM tool_types
|
||||
WHERE name = 'code-server'
|
||||
AND compose_template LIKE '%--host%'
|
||||
""")
|
||||
).fetchall()
|
||||
|
||||
for tool_id, compose_template, default_port in result:
|
||||
port = default_port or 8443
|
||||
expected = f"--bind-addr 0.0.0.0:{port}"
|
||||
|
||||
# Replace any line containing --host with the correct bind-addr
|
||||
lines = compose_template.split("\n")
|
||||
new_lines = []
|
||||
modified = False
|
||||
for line in lines:
|
||||
if "command:" in line and "--host" in line:
|
||||
indent = line[: len(line) - len(line.lstrip())]
|
||||
new_lines.append(f"{indent}command: {expected}")
|
||||
modified = True
|
||||
else:
|
||||
new_lines.append(line)
|
||||
|
||||
if not modified:
|
||||
continue
|
||||
|
||||
updated = "\n".join(new_lines)
|
||||
conn.execute(
|
||||
sa.text("""
|
||||
UPDATE tool_types
|
||||
SET compose_template = :compose_template
|
||||
WHERE id = :id
|
||||
"""),
|
||||
{"compose_template": updated, "id": tool_id},
|
||||
)
|
||||
print(f"Fixed code-server template ({tool_id}): replaced --host with {expected}")
|
||||
|
||||
|
||||
def _fix_instance_compose_files(conn) -> None:
|
||||
"""Fix existing instance compose files on disk with broken --host override."""
|
||||
from pathlib import Path
|
||||
|
||||
# Use information_schema to check if compose_path column exists
|
||||
col_result = conn.execute(
|
||||
sa.text("""
|
||||
SELECT column_name
|
||||
FROM information_schema.columns
|
||||
WHERE table_name = 'tool_instances'
|
||||
AND column_name = 'compose_path'
|
||||
""")
|
||||
).fetchone()
|
||||
|
||||
if not col_result:
|
||||
print("compose_path column not found, skipping instance file fixes")
|
||||
return
|
||||
|
||||
result = conn.execute(
|
||||
sa.text("""
|
||||
SELECT id, compose_path, tool_type_id
|
||||
FROM tool_instances
|
||||
WHERE compose_path IS NOT NULL
|
||||
""")
|
||||
).fetchall()
|
||||
|
||||
for instance_id, compose_path, tool_type_id in result:
|
||||
path = Path(compose_path)
|
||||
if not path.exists():
|
||||
continue
|
||||
|
||||
try:
|
||||
content = path.read_text()
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
if "--host" not in content:
|
||||
continue
|
||||
|
||||
# Get default_port from tool_type
|
||||
port_result = conn.execute(
|
||||
sa.text("""
|
||||
SELECT default_port FROM tool_types WHERE id = :id
|
||||
"""),
|
||||
{"id": tool_type_id},
|
||||
).fetchone()
|
||||
port = port_result[0] if port_result and port_result[0] else 8443
|
||||
expected = f"--bind-addr 0.0.0.0:{port}"
|
||||
|
||||
try:
|
||||
data = yaml.safe_load(content)
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
if not data or "services" not in data:
|
||||
continue
|
||||
|
||||
modified = False
|
||||
for svc in data["services"].values():
|
||||
if "command" in svc:
|
||||
cmd = svc["command"]
|
||||
if "--host" in cmd:
|
||||
svc["command"] = expected
|
||||
modified = True
|
||||
|
||||
if not modified:
|
||||
continue
|
||||
|
||||
try:
|
||||
path.write_text(yaml.dump(data, default_flow_style=False))
|
||||
print(
|
||||
f"Fixed code-server instance compose ({instance_id}): "
|
||||
f"replaced --host with {expected}"
|
||||
)
|
||||
except Exception as exc:
|
||||
print(f"Failed to fix instance {instance_id}: {exc}")
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
conn = op.get_bind()
|
||||
_fix_tool_type_templates(conn)
|
||||
_fix_instance_compose_files(conn)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
pass
|
||||
@@ -0,0 +1,140 @@
|
||||
"""fix web tool bind address to 0.0.0.0
|
||||
|
||||
Revision ID: 2026_05_29_fix_web_tool_bind_address
|
||||
Revises: 2026_05_29_remove_ssh_keys_mount_from_manifest
|
||||
Create Date: 2026-05-29 14:00:00.000000
|
||||
|
||||
"""
|
||||
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = "2026_05_29_fix_web_tool_bind_address"
|
||||
down_revision: Union[str, None] = "2026_05_29_remove_ssh_keys_mount_from_manifest"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def _fix_code_server_compose(conn) -> None:
|
||||
"""Update code-server compose template to bind to 0.0.0.0."""
|
||||
result = conn.execute(
|
||||
sa.text("""
|
||||
SELECT id, compose_template, definition_type
|
||||
FROM tool_types
|
||||
WHERE name = 'code-server'
|
||||
""")
|
||||
).fetchone()
|
||||
|
||||
if result is None:
|
||||
return
|
||||
|
||||
tool_id, compose_template, definition_type = result
|
||||
|
||||
if definition_type != "compose" or not compose_template:
|
||||
return
|
||||
|
||||
# Fix or add command to bind to 0.0.0.0
|
||||
lines = compose_template.split("\n")
|
||||
new_lines = []
|
||||
image_line_idx = -1
|
||||
command_fixed = False
|
||||
for i, line in enumerate(lines):
|
||||
# Replace broken --bind-addr with correct --host
|
||||
if "command:" in line and "--bind-addr" in line:
|
||||
indent = line[: len(line) - len(line.lstrip())]
|
||||
new_lines.append(f"{indent}command: --host 0.0.0.0")
|
||||
command_fixed = True
|
||||
continue
|
||||
new_lines.append(line)
|
||||
if "image:" in line and image_line_idx == -1:
|
||||
image_line_idx = i
|
||||
|
||||
# If no command line exists, insert one after image
|
||||
if not command_fixed and image_line_idx != -1:
|
||||
image_line = lines[image_line_idx]
|
||||
indent = image_line[: len(image_line) - len(image_line.lstrip())]
|
||||
# Insert after the image line in new_lines
|
||||
insert_idx = new_lines.index(image_line) + 1
|
||||
new_lines.insert(insert_idx, f"{indent}command: --host 0.0.0.0")
|
||||
command_fixed = True
|
||||
|
||||
if not command_fixed:
|
||||
return
|
||||
|
||||
updated_compose = "\n".join(new_lines)
|
||||
|
||||
conn.execute(
|
||||
sa.text("""
|
||||
UPDATE tool_types
|
||||
SET compose_template = :compose_template
|
||||
WHERE id = :id
|
||||
"""),
|
||||
{"compose_template": updated_compose, "id": tool_id},
|
||||
)
|
||||
|
||||
print(f"Updated code-server tool type ({tool_id}) to bind to 0.0.0.0")
|
||||
|
||||
|
||||
def _fix_jupyter_compose(conn) -> None:
|
||||
"""Update jupyter-notebook compose template to bind to 0.0.0.0."""
|
||||
result = conn.execute(
|
||||
sa.text("""
|
||||
SELECT id, compose_template, definition_type
|
||||
FROM tool_types
|
||||
WHERE name = 'jupyter-notebook'
|
||||
""")
|
||||
).fetchone()
|
||||
|
||||
if result is None:
|
||||
return
|
||||
|
||||
tool_id, compose_template, definition_type = result
|
||||
|
||||
if definition_type != "compose" or not compose_template:
|
||||
return
|
||||
|
||||
if "command:" in compose_template:
|
||||
return
|
||||
|
||||
lines = compose_template.split("\n")
|
||||
new_lines = []
|
||||
image_line_idx = -1
|
||||
for i, line in enumerate(lines):
|
||||
new_lines.append(line)
|
||||
if "image:" in line and image_line_idx == -1:
|
||||
image_line_idx = i
|
||||
indent = line[: len(line) - len(line.lstrip())]
|
||||
# Jupyter needs --ip=0.0.0.0 to bind to all interfaces
|
||||
new_lines.append(
|
||||
f"{indent}command: start-notebook.sh --ip=0.0.0.0 --port=8888 --no-browser"
|
||||
)
|
||||
|
||||
if image_line_idx == -1:
|
||||
return
|
||||
|
||||
updated_compose = "\n".join(new_lines)
|
||||
|
||||
conn.execute(
|
||||
sa.text("""
|
||||
UPDATE tool_types
|
||||
SET compose_template = :compose_template
|
||||
WHERE id = :id
|
||||
"""),
|
||||
{"compose_template": updated_compose, "id": tool_id},
|
||||
)
|
||||
|
||||
print(f"Updated jupyter-notebook tool type ({tool_id}) to bind to 0.0.0.0:8888")
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
conn = op.get_bind()
|
||||
_fix_code_server_compose(conn)
|
||||
_fix_jupyter_compose(conn)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# Cannot safely downgrade without knowing the original compose_template
|
||||
pass
|
||||
@@ -0,0 +1,121 @@
|
||||
"""Remove broken command override from LSIO code-server templates
|
||||
|
||||
Revision ID: 2026_05_29_remove_lsio_command_override
|
||||
Revises: 2026_05_29_fix_code_server_bind_addr
|
||||
Create Date: 2026-05-29 15:05:00.000000
|
||||
|
||||
"""
|
||||
|
||||
from collections.abc import Sequence
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = "2026_05_29_remove_lsio_command_override"
|
||||
down_revision: str | None = "2026_05_29_fix_code_server_bind_addr"
|
||||
branch_labels: Sequence[str] | None = None
|
||||
depends_on: Sequence[str] | None = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
conn = op.get_bind()
|
||||
|
||||
# Fix tool_types templates in DB
|
||||
result = conn.execute(
|
||||
sa.text("""
|
||||
SELECT id, compose_template
|
||||
FROM tool_types
|
||||
WHERE name = 'code-server'
|
||||
""")
|
||||
).fetchall()
|
||||
|
||||
import yaml
|
||||
from pathlib import Path
|
||||
|
||||
for tool_id, compose_template in result:
|
||||
try:
|
||||
data = yaml.safe_load(compose_template)
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
if not data or "services" not in data:
|
||||
continue
|
||||
|
||||
modified = False
|
||||
for svc in data["services"].values():
|
||||
image = svc.get("image", "")
|
||||
if not image or "linuxserver" not in image:
|
||||
continue
|
||||
if "command" in svc:
|
||||
cmd = svc["command"]
|
||||
if "--bind-addr" in cmd or "--host" in cmd:
|
||||
del svc["command"]
|
||||
modified = True
|
||||
|
||||
if modified:
|
||||
updated = yaml.dump(data, default_flow_style=False)
|
||||
conn.execute(
|
||||
sa.text("""
|
||||
UPDATE tool_types
|
||||
SET compose_template = :compose_template
|
||||
WHERE id = :id
|
||||
"""),
|
||||
{"compose_template": updated, "id": tool_id},
|
||||
)
|
||||
print(f"Removed broken command override from LSIO template ({tool_id})")
|
||||
|
||||
# Fix existing instance compose files on disk
|
||||
# Use information_schema to check if compose_path column exists
|
||||
col_result = conn.execute(
|
||||
sa.text("""
|
||||
SELECT column_name
|
||||
FROM information_schema.columns
|
||||
WHERE table_name = 'tool_instances'
|
||||
AND column_name = 'compose_path'
|
||||
""")
|
||||
).fetchone()
|
||||
|
||||
if col_result:
|
||||
result = conn.execute(
|
||||
sa.text("""
|
||||
SELECT id, compose_path
|
||||
FROM tool_instances
|
||||
WHERE compose_path IS NOT NULL
|
||||
""")
|
||||
).fetchall()
|
||||
|
||||
for instance_id, compose_path in result:
|
||||
path = Path(compose_path)
|
||||
if not path.exists():
|
||||
continue
|
||||
try:
|
||||
content = path.read_text()
|
||||
data = yaml.safe_load(content)
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
if not data or "services" not in data:
|
||||
continue
|
||||
|
||||
modified = False
|
||||
for svc in data["services"].values():
|
||||
image = svc.get("image", "")
|
||||
if not image or "linuxserver" not in image:
|
||||
continue
|
||||
if "command" in svc:
|
||||
cmd = svc["command"]
|
||||
if "--bind-addr" in cmd or "--host" in cmd:
|
||||
del svc["command"]
|
||||
modified = True
|
||||
|
||||
if modified:
|
||||
path.write_text(yaml.dump(data, default_flow_style=False))
|
||||
print(
|
||||
f"Removed broken command override from instance compose "
|
||||
f"({instance_id})"
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
pass
|
||||
@@ -0,0 +1,105 @@
|
||||
"""remove ssh_keys mount from pi-agent manifest
|
||||
|
||||
Revision ID: 2026_05_29_remove_ssh_keys_mount_from_manifest
|
||||
Revises: 2026_05_29_add_ssh_key_ids_to_tool_instances
|
||||
Create Date: 2026-05-29 14:00:00.000000
|
||||
|
||||
"""
|
||||
|
||||
import json
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = "2026_05_29_remove_ssh_keys_mount_from_manifest"
|
||||
down_revision: Union[str, None] = "2026_05_29_add_ssh_key_ids_to_tool_instances"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""Remove the ssh_keys mount from the pi-agent manifest."""
|
||||
conn = op.get_bind()
|
||||
|
||||
# Get the pi-agent manifest
|
||||
result = conn.execute(
|
||||
sa.text(
|
||||
"SELECT id, manifest FROM tool_definition_manifests WHERE name = 'pi-agent'"
|
||||
)
|
||||
)
|
||||
row = result.fetchone()
|
||||
if not row:
|
||||
return
|
||||
|
||||
manifest_id, manifest_json = row
|
||||
manifest = (
|
||||
manifest_json if isinstance(manifest_json, dict) else json.loads(manifest_json)
|
||||
)
|
||||
|
||||
mounts = manifest.get("mounts", [])
|
||||
original_count = len(mounts)
|
||||
|
||||
# Remove any mount named "ssh_keys"
|
||||
filtered_mounts = [m for m in mounts if m.get("name") != "ssh_keys"]
|
||||
|
||||
if len(filtered_mounts) < original_count:
|
||||
manifest["mounts"] = filtered_mounts
|
||||
conn.execute(
|
||||
sa.text(
|
||||
"UPDATE tool_definition_manifests SET manifest = :manifest WHERE id = :id"
|
||||
),
|
||||
{
|
||||
"manifest": json.dumps(manifest),
|
||||
"id": manifest_id,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""Restore the ssh_keys mount to the pi-agent manifest."""
|
||||
conn = op.get_bind()
|
||||
|
||||
result = conn.execute(
|
||||
sa.text(
|
||||
"SELECT id, manifest FROM tool_definition_manifests WHERE name = 'pi-agent'"
|
||||
)
|
||||
)
|
||||
row = result.fetchone()
|
||||
if not row:
|
||||
return
|
||||
|
||||
manifest_id, manifest_json = row
|
||||
manifest = (
|
||||
manifest_json if isinstance(manifest_json, dict) else json.loads(manifest_json)
|
||||
)
|
||||
|
||||
mounts = manifest.get("mounts", [])
|
||||
|
||||
# Check if ssh_keys mount already exists
|
||||
if any(m.get("name") == "ssh_keys" for m in mounts):
|
||||
return
|
||||
|
||||
# Add the ssh_keys mount back
|
||||
mounts.append(
|
||||
{
|
||||
"name": "ssh_keys",
|
||||
"target": "/home/user/.ssh",
|
||||
"source_type": "ssh_key",
|
||||
"mode": "0700",
|
||||
"file_mode": "0600",
|
||||
"readonly": True,
|
||||
}
|
||||
)
|
||||
manifest["mounts"] = mounts
|
||||
|
||||
conn.execute(
|
||||
sa.text(
|
||||
"UPDATE tool_definition_manifests SET manifest = :manifest WHERE id = :id"
|
||||
),
|
||||
{
|
||||
"manifest": json.dumps(manifest),
|
||||
"id": manifest_id,
|
||||
},
|
||||
)
|
||||
@@ -47,6 +47,10 @@ class MarkAllReadResponse(BaseModel):
|
||||
marked_count: int
|
||||
|
||||
|
||||
class ClearAllResponse(BaseModel):
|
||||
cleared_count: int
|
||||
|
||||
|
||||
async def _get_mute_categories(
|
||||
session: AsyncSession,
|
||||
user_id: uuid.UUID,
|
||||
@@ -131,13 +135,23 @@ async def mark_all_read(
|
||||
return MarkAllReadResponse(marked_count=marked)
|
||||
|
||||
|
||||
@router.delete("", status_code=status.HTTP_200_OK)
|
||||
async def clear_all_notifications(
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_db_session),
|
||||
) -> ClearAllResponse:
|
||||
"""Dismiss all notifications for the authenticated user."""
|
||||
cleared = await notification_service.dismiss_all(session, user.id)
|
||||
return ClearAllResponse(cleared_count=cleared)
|
||||
|
||||
|
||||
@router.delete("/{notification_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
async def dismiss_notification(
|
||||
notification_id: uuid.UUID,
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_db_session),
|
||||
) -> None:
|
||||
"""Soft-delete (dismiss) a notification."""
|
||||
"""Soft-delete (dismiss) a single notification."""
|
||||
try:
|
||||
await notification_service.dismiss(session, notification_id, user.id)
|
||||
except ValueError as exc:
|
||||
|
||||
@@ -52,7 +52,6 @@ from src.services.docker import (
|
||||
find_free_port,
|
||||
get_container_id,
|
||||
get_container_logs,
|
||||
get_container_name,
|
||||
get_container_status,
|
||||
recreate_tunnel,
|
||||
render_compose_template,
|
||||
@@ -475,7 +474,7 @@ async def _validate_config_profile(
|
||||
Raises:
|
||||
HTTPException: If profile is not found, not owned, or incompatible.
|
||||
"""
|
||||
if profile_id is None:
|
||||
if not profile_id:
|
||||
return None
|
||||
|
||||
try:
|
||||
@@ -618,6 +617,137 @@ def _modify_compose_file(
|
||||
compose_file.write_text(yaml.dump(compose_data, default_flow_style=False))
|
||||
|
||||
|
||||
def _ensure_container_name_in_compose(compose_path: str, container_name: str) -> None:
|
||||
"""Ensure compose file has explicit container_name for predictable naming.
|
||||
|
||||
Docker Compose auto-generates container names from the project directory
|
||||
when container_name is absent. This breaks tunnel connectivity because
|
||||
get_container_name(instance.name) cannot find the container. We inject
|
||||
container_name into every service so the container has a predictable name.
|
||||
"""
|
||||
import yaml
|
||||
from pathlib import Path
|
||||
|
||||
compose_file = Path(compose_path)
|
||||
if not compose_file.exists():
|
||||
return
|
||||
|
||||
content = compose_file.read_text()
|
||||
compose_data = yaml.safe_load(content)
|
||||
|
||||
if not compose_data or "services" not in compose_data:
|
||||
return
|
||||
|
||||
modified = False
|
||||
for svc_name, svc_config in compose_data["services"].items():
|
||||
if "container_name" not in svc_config:
|
||||
svc_config["container_name"] = container_name.lower()
|
||||
modified = True
|
||||
|
||||
if modified:
|
||||
compose_file.write_text(yaml.dump(compose_data, default_flow_style=False))
|
||||
logger.info(
|
||||
"Injected container_name '%s' into compose file",
|
||||
container_name.lower(),
|
||||
)
|
||||
|
||||
|
||||
def _ensure_web_bind_address(
|
||||
compose_path: str, tool_type_name: str, default_port: int
|
||||
) -> None:
|
||||
"""Auto-inject bind address for known web tools that default to 127.0.0.1.
|
||||
|
||||
Many web tools (code-server, jupyter) bind to localhost by default,
|
||||
making them inaccessible from the Docker network. This function detects
|
||||
known tool images and injects the correct --bind-addr or --ip flag.
|
||||
"""
|
||||
import yaml
|
||||
from pathlib import Path
|
||||
|
||||
if default_port <= 0:
|
||||
return
|
||||
|
||||
KNOWN_BIND_FIXES: dict[str, str] = {
|
||||
"code-server": f"--bind-addr 0.0.0.0:{default_port}",
|
||||
"jupyter-notebook": f"start-notebook.sh --ip=0.0.0.0 --port={default_port} --no-browser",
|
||||
}
|
||||
|
||||
bind_command = KNOWN_BIND_FIXES.get(tool_type_name)
|
||||
if not bind_command:
|
||||
return
|
||||
|
||||
compose_file = Path(compose_path)
|
||||
if not compose_file.exists():
|
||||
return
|
||||
|
||||
content = compose_file.read_text()
|
||||
compose_data = yaml.safe_load(content)
|
||||
|
||||
if not compose_data or "services" not in compose_data:
|
||||
return
|
||||
|
||||
for service_config in compose_data["services"].values():
|
||||
image = service_config.get("image", "")
|
||||
if not image:
|
||||
continue
|
||||
|
||||
# LSIO images already bind to 0.0.0.0 — command override breaks s6 init
|
||||
if "linuxserver" in image:
|
||||
existing_command = service_config.get("command", "")
|
||||
if "--bind-addr" in existing_command or "--host" in existing_command:
|
||||
del service_config["command"]
|
||||
compose_file.write_text(
|
||||
yaml.dump(compose_data, default_flow_style=False)
|
||||
)
|
||||
logger.warning(
|
||||
"Removed broken command override from LSIO image: %s",
|
||||
existing_command,
|
||||
)
|
||||
return
|
||||
return
|
||||
|
||||
# Check if the image matches a known tool
|
||||
is_code_server = tool_type_name == "code-server" and (
|
||||
"code-server" in image or "coder" in image
|
||||
)
|
||||
is_jupyter = tool_type_name == "jupyter-notebook" and (
|
||||
"jupyter" in image or "notebook" in image
|
||||
)
|
||||
if not is_code_server and not is_jupyter:
|
||||
continue
|
||||
|
||||
existing_command = service_config.get("command", "")
|
||||
if existing_command:
|
||||
# Already correct — nothing to do
|
||||
if bind_command in existing_command:
|
||||
return
|
||||
# Fix broken or outdated bind flags
|
||||
if (
|
||||
"--bind-addr" in existing_command
|
||||
or "--host" in existing_command
|
||||
or "--ip=" in existing_command
|
||||
):
|
||||
service_config["command"] = bind_command
|
||||
compose_file.write_text(
|
||||
yaml.dump(compose_data, default_flow_style=False)
|
||||
)
|
||||
logger.warning(
|
||||
"Replaced broken bind address for %s: %s → %s",
|
||||
tool_type_name,
|
||||
existing_command,
|
||||
bind_command,
|
||||
)
|
||||
return
|
||||
# Some other command override exists — don't touch it
|
||||
return
|
||||
|
||||
# No command yet — inject the correct bind address
|
||||
service_config["command"] = bind_command
|
||||
compose_file.write_text(yaml.dump(compose_data, default_flow_style=False))
|
||||
logger.info("Injected bind address for %s: %s", tool_type_name, bind_command)
|
||||
return
|
||||
|
||||
|
||||
@router.post(
|
||||
"/{project_id}/repositories/{repo_id}/instances",
|
||||
summary="Create tool instance",
|
||||
@@ -854,7 +984,7 @@ services:
|
||||
)
|
||||
|
||||
# Determine home directory for path expansion
|
||||
home_dir = get_manifest_home_dir(manifest)
|
||||
_home_dir = get_manifest_home_dir(manifest)
|
||||
|
||||
image_tag = compute_image_tag(tool_type.name, manifest)
|
||||
|
||||
@@ -1341,11 +1471,27 @@ async def start_instance(
|
||||
manifest_def = await session.get(ToolDefinitionManifest, tool_type.manifest_id)
|
||||
if manifest_def:
|
||||
manifest = dict(manifest_def.manifest)
|
||||
# Merge with base definition if referenced (user config is often in base)
|
||||
if manifest_def.base_definition_id:
|
||||
base_def = await session.get(
|
||||
ToolDefinitionManifest, manifest_def.base_definition_id
|
||||
)
|
||||
if base_def:
|
||||
manifest = resolve_base(
|
||||
deep_merge(dict(base_def.manifest), manifest)
|
||||
)
|
||||
home_dir = get_manifest_home_dir(manifest)
|
||||
user_cfg = manifest.get("user")
|
||||
if user_cfg:
|
||||
container_uid = user_cfg.get("uid", 0)
|
||||
container_gid = user_cfg.get("gid", 0)
|
||||
logger.debug(
|
||||
"Manifest user resolved for instance %s: uid=%s, gid=%s, home=%s",
|
||||
instance.id,
|
||||
container_uid,
|
||||
container_gid,
|
||||
home_dir,
|
||||
)
|
||||
|
||||
# Apply selected config profile if any
|
||||
instance_dir = os.path.dirname(instance.compose_path)
|
||||
@@ -1534,6 +1680,15 @@ async def start_instance(
|
||||
# Sanitize compose file to remove invalid port mappings from old instances
|
||||
_sanitize_compose_file(instance.compose_path)
|
||||
|
||||
# Auto-fix bind address for known web tools that default to localhost
|
||||
if tool_type and tool_type.interface_type == "web":
|
||||
_ensure_web_bind_address(
|
||||
instance.compose_path, tool_type.name, tool_type.default_port
|
||||
)
|
||||
|
||||
# Ensure predictable container name for tunnel connectivity
|
||||
_ensure_container_name_in_compose(instance.compose_path, instance.name)
|
||||
|
||||
# Execute docker compose up with env file
|
||||
logger.debug(
|
||||
"Running docker compose up for instance %s (compose_path=%s)",
|
||||
@@ -1560,24 +1715,23 @@ async def start_instance(
|
||||
detail=f"failed to start instance: {stderr}",
|
||||
)
|
||||
|
||||
# Get container ID and name
|
||||
container_id = get_container_id(instance.name)
|
||||
# Get container ID and name (use predictable name from compose)
|
||||
expected_container_name = instance.name.lower()
|
||||
container_id = get_container_id(expected_container_name)
|
||||
if container_id:
|
||||
instance.container_id = container_id
|
||||
logger.debug("Container ID for instance %s: %s", instance.id, container_id)
|
||||
|
||||
container_name = get_container_name(instance.name)
|
||||
if container_name:
|
||||
instance.container_name = container_name
|
||||
logger.debug("Container name for instance %s: %s", instance.id, container_name)
|
||||
instance.container_name = expected_container_name
|
||||
logger.debug("Container name for instance %s: %s", instance.id, expected_container_name)
|
||||
|
||||
# Connect container to backend network so API can reach it
|
||||
logger.debug("Connecting container %s to backend network...", container_name)
|
||||
connected = connect_container_to_network(container_name, "backend")
|
||||
if connected:
|
||||
logger.debug("Successfully connected %s to backend network", container_name)
|
||||
else:
|
||||
logger.warning("Failed to connect %s to backend network", container_name)
|
||||
# Connect container to backend network so API can reach it
|
||||
logger.debug("Connecting container %s to backend network...", expected_container_name)
|
||||
connected = connect_container_to_network(expected_container_name, "backend")
|
||||
if connected:
|
||||
logger.debug("Successfully connected %s to backend network", expected_container_name)
|
||||
else:
|
||||
logger.warning("Failed to connect %s to backend network", expected_container_name)
|
||||
|
||||
# Verify container reached running state
|
||||
if instance.container_id:
|
||||
@@ -1818,7 +1972,8 @@ async def start_instance(
|
||||
instance_port,
|
||||
)
|
||||
tunnel_info = start_cloudflared_tunnel(
|
||||
host_port=instance.port,
|
||||
container_name=instance.container_name or instance.name,
|
||||
port=instance_port,
|
||||
)
|
||||
instance.tunnel_id = tunnel_info["pid"]
|
||||
instance.public_url = tunnel_info["url"]
|
||||
@@ -2003,6 +2158,15 @@ async def restart_instance(
|
||||
exc,
|
||||
)
|
||||
|
||||
# Re-apply compose fixes in case they were updated since last start
|
||||
_sanitize_compose_file(instance.compose_path)
|
||||
tool_type = await session.get(ToolType, instance.tool_type_id)
|
||||
if tool_type and tool_type.interface_type == "web":
|
||||
_ensure_web_bind_address(
|
||||
instance.compose_path, tool_type.name, tool_type.default_port
|
||||
)
|
||||
_ensure_container_name_in_compose(instance.compose_path, instance.name)
|
||||
|
||||
returncode, stdout, stderr = execute_compose_command(
|
||||
instance.compose_path, "restart"
|
||||
)
|
||||
@@ -2025,12 +2189,15 @@ async def restart_instance(
|
||||
"error": f"Tool type '{tool_type.name if tool_type else 'unknown'}' has no port configured",
|
||||
}
|
||||
|
||||
instance_port = tool_type.default_port
|
||||
|
||||
# Only create tunnel for web-enabled tools
|
||||
if tool_type.interface_type == "web":
|
||||
# Create new temporary tunnel
|
||||
try:
|
||||
tunnel_info = start_cloudflared_tunnel(
|
||||
host_port=instance.port or 0,
|
||||
container_name=instance.name.lower(),
|
||||
port=instance_port,
|
||||
)
|
||||
instance.tunnel_id = tunnel_info["pid"]
|
||||
instance.public_url = tunnel_info["url"]
|
||||
@@ -2263,9 +2430,16 @@ async def recreate_tunnel_endpoint(
|
||||
"message": "Tunnel is already healthy",
|
||||
}
|
||||
|
||||
# Get tool type for default port
|
||||
tool_type = await session.get(ToolType, instance.tool_type_id)
|
||||
instance_port = (
|
||||
tool_type.default_port if tool_type and tool_type.default_port else 8080
|
||||
)
|
||||
|
||||
try:
|
||||
tunnel_info = recreate_tunnel(
|
||||
host_port=instance.port or 0,
|
||||
container_name=instance.container_name or instance.name,
|
||||
port=instance_port,
|
||||
old_pid=instance.tunnel_id,
|
||||
)
|
||||
instance.tunnel_id = tunnel_info["pid"]
|
||||
|
||||
+139
-18
@@ -159,7 +159,7 @@ def execute_compose_command(
|
||||
cmd.extend(["--env-file", env_file])
|
||||
|
||||
if action == "up":
|
||||
cmd.extend(["up", "-d"])
|
||||
cmd.extend(["up", "-d", "--force-recreate"])
|
||||
elif action == "down":
|
||||
cmd.extend(["down", "-v"])
|
||||
elif action in ("start", "stop", "restart"):
|
||||
@@ -384,16 +384,96 @@ def find_free_port(start: int = 10000, end: int = 20000) -> int:
|
||||
raise RuntimeError(f"No free port found in range {start}-{end}")
|
||||
|
||||
|
||||
def _check_app_binding(container_name: str, port: int) -> dict[str, str | bool]:
|
||||
"""Diagnose whether the app is bound to 127.0.0.1 or 0.0.0.0.
|
||||
|
||||
Checks from both inside the container (localhost) and outside
|
||||
(via Docker network) to detect binding issues.
|
||||
|
||||
Returns:
|
||||
Dict with 'internal_ok', 'external_ok', 'internal_status',
|
||||
'external_status', and 'diagnosis'.
|
||||
"""
|
||||
import subprocess
|
||||
|
||||
result: dict[str, Any] = {
|
||||
"internal_ok": False,
|
||||
"external_ok": False,
|
||||
"internal_status": None,
|
||||
"external_status": None,
|
||||
"diagnosis": "unknown",
|
||||
}
|
||||
|
||||
# Check from inside the container (loopback)
|
||||
internal = subprocess.run(
|
||||
[
|
||||
"docker",
|
||||
"exec",
|
||||
container_name,
|
||||
"sh",
|
||||
"-c",
|
||||
f"curl -s -o /dev/null -w '%{{http_code}}' http://localhost:{port}",
|
||||
],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=5,
|
||||
)
|
||||
if internal.returncode == 0:
|
||||
try:
|
||||
result["internal_status"] = int(internal.stdout.strip())
|
||||
result["internal_ok"] = result["internal_status"] > 0
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
# Check from outside the container (Docker network)
|
||||
external = subprocess.run(
|
||||
[
|
||||
"curl",
|
||||
"-s",
|
||||
"-o",
|
||||
"/dev/null",
|
||||
"-w",
|
||||
"%{http_code}",
|
||||
f"http://{container_name}:{port}",
|
||||
],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=5,
|
||||
)
|
||||
if external.returncode == 0:
|
||||
try:
|
||||
result["external_status"] = int(external.stdout.strip())
|
||||
result["external_ok"] = result["external_status"] > 0
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
# Diagnose binding issue
|
||||
if result["internal_ok"] and not result["external_ok"]:
|
||||
result["diagnosis"] = (
|
||||
f"App appears to be bound to 127.0.0.1:{port} inside the container. "
|
||||
f"It must bind to 0.0.0.0:{port} to be accessible from the tunnel."
|
||||
)
|
||||
elif result["internal_ok"] and result["external_ok"]:
|
||||
result["diagnosis"] = "App is accessible on both interfaces."
|
||||
elif not result["internal_ok"] and not result["external_ok"]:
|
||||
result["diagnosis"] = f"App is not responding on port {port} at all."
|
||||
else:
|
||||
result["diagnosis"] = "Unexpected binding state."
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def start_cloudflared_tunnel(
|
||||
host_port: int, timeout: int = 30
|
||||
container_name: str, port: int, timeout: int = 30
|
||||
) -> dict[str, str]:
|
||||
"""Start a temporary Cloudflare tunnel to localhost.
|
||||
"""Start a temporary Cloudflare tunnel for a container.
|
||||
|
||||
Uses 'cloudflared tunnel --url' to create a temporary tunnel
|
||||
with a random trycloudflare.com URL.
|
||||
|
||||
Args:
|
||||
host_port: Host-mapped port number (e.g. from find_free_port)
|
||||
container_name: Name of the Docker container to tunnel to
|
||||
port: Port number the container listens on
|
||||
timeout: Maximum seconds to wait for tunnel URL
|
||||
|
||||
Returns:
|
||||
@@ -404,9 +484,11 @@ def start_cloudflared_tunnel(
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# First verify the container is accessible via the host-mapped port
|
||||
logger.info("Checking connectivity to localhost:%d...", host_port)
|
||||
for attempt in range(10):
|
||||
# First verify the container is accessible from the Docker network
|
||||
logger.info("Checking connectivity to %s:%d...", container_name, port)
|
||||
accessible = False
|
||||
last_status = None
|
||||
for attempt in range(30): # 30 attempts × 1s = 30s max wait for app startup
|
||||
check = subprocess.run(
|
||||
[
|
||||
"curl",
|
||||
@@ -415,27 +497,65 @@ def start_cloudflared_tunnel(
|
||||
"/dev/null",
|
||||
"-w",
|
||||
"%{http_code}",
|
||||
f"http://localhost:{host_port}",
|
||||
"--max-time",
|
||||
"3",
|
||||
f"http://{container_name}:{port}",
|
||||
],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=5,
|
||||
)
|
||||
status_str = check.stdout.strip()
|
||||
logger.info(
|
||||
"Connectivity check %d: http_code=%s", attempt + 1, check.stdout.strip()
|
||||
"Connectivity check %d/%d: http_code=%s (rc=%d)",
|
||||
attempt + 1,
|
||||
30,
|
||||
status_str,
|
||||
check.returncode,
|
||||
)
|
||||
if check.returncode == 0:
|
||||
break
|
||||
try:
|
||||
last_status = int(status_str)
|
||||
# Accept 2xx, 3xx, 401, 403 as "app is listening"
|
||||
if last_status in (401, 403) or 200 <= last_status < 400:
|
||||
accessible = True
|
||||
logger.info(
|
||||
"App on %s:%d is ready (HTTP %d)",
|
||||
container_name,
|
||||
port,
|
||||
last_status,
|
||||
)
|
||||
break
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
if check.returncode != 0:
|
||||
logger.debug(
|
||||
"curl failed: stderr=%s", check.stderr.strip() if check.stderr else ""
|
||||
)
|
||||
time.sleep(1)
|
||||
else:
|
||||
|
||||
if not accessible:
|
||||
logger.warning(
|
||||
"localhost:%d not responding to curl checks", host_port
|
||||
"Container %s:%d not responding after 30s (last status: %s). "
|
||||
"Running binding diagnostics...",
|
||||
container_name,
|
||||
port,
|
||||
last_status,
|
||||
)
|
||||
diagnosis = _check_app_binding(container_name, port)
|
||||
logger.warning(
|
||||
"Binding diagnosis: internal=%s (HTTP %s), external=%s (HTTP %s). %s",
|
||||
diagnosis["internal_ok"],
|
||||
diagnosis["internal_status"],
|
||||
diagnosis["external_ok"],
|
||||
diagnosis["external_status"],
|
||||
diagnosis["diagnosis"],
|
||||
)
|
||||
|
||||
# Run cloudflared in background, capture output
|
||||
logger.info("Starting cloudflared tunnel to http://localhost:%d", host_port)
|
||||
logger.info("Starting cloudflared tunnel to http://%s:%d", container_name, port)
|
||||
proc = subprocess.Popen(
|
||||
["cloudflared", "tunnel", "--url", f"http://localhost:{host_port}"],
|
||||
["cloudflared", "tunnel", "--url", f"http://{container_name}:{port}"],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT,
|
||||
text=True,
|
||||
@@ -490,14 +610,15 @@ def stop_cloudflared_tunnel(pid: str) -> None:
|
||||
|
||||
|
||||
def recreate_tunnel(
|
||||
host_port: int, old_pid: str | None = None
|
||||
container_name: str, port: int, old_pid: str | None = None
|
||||
) -> dict[str, str]:
|
||||
"""Recreate a temporary Cloudflare tunnel.
|
||||
|
||||
Stops the old tunnel (if pid provided) and starts a new one.
|
||||
|
||||
Args:
|
||||
host_port: Host-mapped port number (e.g. from find_free_port)
|
||||
container_name: Name of the Docker container to tunnel to
|
||||
port: Port number the container listens on
|
||||
old_pid: Optional PID of the old tunnel process to stop
|
||||
|
||||
Returns:
|
||||
@@ -506,7 +627,7 @@ def recreate_tunnel(
|
||||
if old_pid:
|
||||
stop_cloudflared_tunnel(old_pid)
|
||||
|
||||
return start_cloudflared_tunnel(host_port)
|
||||
return start_cloudflared_tunnel(container_name, port)
|
||||
|
||||
|
||||
def check_tunnel_health(url: str, timeout: int = 10) -> dict[str, Any]:
|
||||
|
||||
@@ -220,18 +220,18 @@ class HealthMonitor:
|
||||
await self._event_bus.publish(event_type, payload)
|
||||
|
||||
# Create notification for instance owner (fire-and-forget)
|
||||
# Only send warnings and errors; skip "recovered" info notifications.
|
||||
if new_status == "error":
|
||||
category = "instance"
|
||||
severity = "error"
|
||||
title = "Container failed"
|
||||
else:
|
||||
elif new_status == "unhealthy":
|
||||
category = "health"
|
||||
if new_status == "unhealthy":
|
||||
severity = "warning"
|
||||
title = "Container unhealthy"
|
||||
else:
|
||||
severity = "info"
|
||||
title = "Container recovered"
|
||||
severity = "warning"
|
||||
title = "Container unhealthy"
|
||||
else:
|
||||
# Running/recovered — do not notify
|
||||
return
|
||||
|
||||
try:
|
||||
await notification_service.create_notification(
|
||||
|
||||
@@ -24,6 +24,7 @@ def _derive_title(event_type: str) -> str:
|
||||
"instance.restarted": "Container restarted",
|
||||
"instance.deleted": "Container deleted",
|
||||
"instance.error": "Container error",
|
||||
"instance.health_changed": "Container ready",
|
||||
}
|
||||
return mapping.get(
|
||||
event_type,
|
||||
@@ -31,6 +32,21 @@ def _derive_title(event_type: str) -> str:
|
||||
)
|
||||
|
||||
|
||||
def _should_notify(event_type: str, status: str | None) -> bool:
|
||||
"""Determine whether a lifecycle event should generate a notification.
|
||||
|
||||
Only warnings, errors, and "container is ready" (health_changed running)
|
||||
are sent to users.
|
||||
"""
|
||||
if event_type == "instance.error":
|
||||
return True
|
||||
if event_type == "instance.health_changed" and status == "running":
|
||||
return True
|
||||
# Filter out: created, started, stopped, restarted, deleted, and any
|
||||
# health_changed that is not "running" (unhealthy is handled by health_monitor)
|
||||
return False
|
||||
|
||||
|
||||
def _build_payload(
|
||||
event_type: str,
|
||||
instance: ToolInstance,
|
||||
@@ -118,15 +134,12 @@ async def publish_lifecycle_event(
|
||||
await event_bus.publish(event_type, payload)
|
||||
|
||||
# Create notification for instance owner (fire-and-forget)
|
||||
# Skip intermediate "starting" notifications — only notify on terminal states
|
||||
# (failed or successful attempts)
|
||||
_is_starting_intermediate = (
|
||||
event_type == "instance.started" and (status or instance.status) == "starting"
|
||||
)
|
||||
if _is_starting_intermediate:
|
||||
# Only send warnings, errors, and "container is ready" notifications.
|
||||
effective_status = status or instance.status
|
||||
if not _should_notify(event_type, effective_status):
|
||||
return
|
||||
|
||||
severity = "error" if event_type == "instance.error" else "info"
|
||||
severity = "error" if event_type == "instance.error" else "success"
|
||||
title = _derive_title(event_type)
|
||||
|
||||
try:
|
||||
|
||||
@@ -195,6 +195,32 @@ class NotificationService:
|
||||
await session.commit()
|
||||
return result.rowcount or 0
|
||||
|
||||
async def dismiss_all(
|
||||
self,
|
||||
session: AsyncSession,
|
||||
user_id: uuid.UUID,
|
||||
) -> int:
|
||||
"""Soft-delete all non-dismissed notifications for a user.
|
||||
|
||||
Args:
|
||||
session: Database session.
|
||||
user_id: Owner of the notifications.
|
||||
|
||||
Returns:
|
||||
Number of rows updated.
|
||||
"""
|
||||
stmt = (
|
||||
update(Notification)
|
||||
.where(
|
||||
Notification.user_id == user_id,
|
||||
Notification.dismissed_at.is_(None),
|
||||
)
|
||||
.values(dismissed_at=datetime.now(timezone.utc))
|
||||
)
|
||||
result: CursorResult[Any] = await session.execute(stmt) # type: ignore[assignment]
|
||||
await session.commit()
|
||||
return result.rowcount or 0
|
||||
|
||||
async def dismiss(
|
||||
self,
|
||||
session: AsyncSession,
|
||||
|
||||
@@ -40,6 +40,17 @@ def apply_mount_permissions(
|
||||
"error": None,
|
||||
}
|
||||
|
||||
# Skip read-only mounts — their permissions cannot be changed
|
||||
# post-start because the bind mount is locked.
|
||||
if mount.get("readonly", False):
|
||||
logger.debug(
|
||||
"Skipping permission fix for read-only mount %s (target=%s)",
|
||||
name,
|
||||
target,
|
||||
)
|
||||
results.append(result)
|
||||
continue
|
||||
|
||||
# Skip if no permission policy defined
|
||||
if not owner and not mode and not file_mode:
|
||||
results.append(result)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"""SSH key service utilities for preparing keys for container use."""
|
||||
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
@@ -7,6 +8,8 @@ from cryptography.fernet import Fernet
|
||||
|
||||
from src.config import Settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _get_fernet() -> Fernet:
|
||||
"""Generate a valid Fernet key from the session secret."""
|
||||
@@ -75,10 +78,20 @@ def prepare_ssh_key_files(
|
||||
os.chown(private_key_path, effective_uid, effective_gid)
|
||||
os.chown(public_key_path, effective_uid, effective_gid)
|
||||
os.chown(config_path, effective_uid, effective_gid)
|
||||
except PermissionError:
|
||||
# API process may not be running as root; permission fixer will
|
||||
# handle this post-start if the mount is read-write
|
||||
pass
|
||||
logger.debug(
|
||||
"Set SSH key ownership to uid=%s gid=%s for %s",
|
||||
effective_uid,
|
||||
effective_gid,
|
||||
ssh_dir,
|
||||
)
|
||||
except PermissionError as exc:
|
||||
logger.warning(
|
||||
"Cannot chown SSH keys to uid=%s gid=%s (running as uid=%s): %s",
|
||||
effective_uid,
|
||||
effective_gid,
|
||||
os.getuid(),
|
||||
exc,
|
||||
)
|
||||
|
||||
return str(ssh_dir)
|
||||
|
||||
|
||||
@@ -149,8 +149,8 @@ async def test_lifecycle_running_creates_notification(
|
||||
assert len(notifications) == 1
|
||||
n = notifications[0]
|
||||
assert n.category == "instance"
|
||||
assert n.severity == "info"
|
||||
assert n.title == "Health Changed"
|
||||
assert n.severity == "success"
|
||||
assert n.title == "Container ready"
|
||||
assert n.source_type == "tool_instances"
|
||||
assert n.source_id == test_instance.id
|
||||
|
||||
@@ -315,9 +315,9 @@ async def test_notification_ownership_matches_instance_owner(
|
||||
event_bus=event_bus,
|
||||
session=db_session,
|
||||
instance=instance,
|
||||
event_type="instance.created",
|
||||
status="pending",
|
||||
message="Instance created",
|
||||
event_type="instance.health_changed",
|
||||
status="running",
|
||||
message="Container running",
|
||||
)
|
||||
|
||||
result = await db_session.execute(
|
||||
|
||||
@@ -6,7 +6,9 @@ from fastapi.testclient import TestClient
|
||||
class TestToolTypesAPIExtended:
|
||||
"""Integration tests for tool types API with new fields."""
|
||||
|
||||
def test_create_tool_type_with_dockerfile(self, authenticated_client: TestClient) -> None:
|
||||
def test_create_tool_type_with_dockerfile(
|
||||
self, authenticated_client: TestClient
|
||||
) -> None:
|
||||
"""Test creating a tool type with dockerfile definition."""
|
||||
response = authenticated_client.post(
|
||||
"/tool-types",
|
||||
@@ -27,7 +29,9 @@ class TestToolTypesAPIExtended:
|
||||
assert data["definition_type"] == "dockerfile"
|
||||
assert data["dockerfile_template"] == "FROM python:3.11\nRUN pip install flask"
|
||||
|
||||
def test_create_tool_type_with_readiness_probe(self, authenticated_client: TestClient) -> None:
|
||||
def test_create_tool_type_with_readiness_probe(
|
||||
self, authenticated_client: TestClient
|
||||
) -> None:
|
||||
"""Test creating a tool type with readiness probe."""
|
||||
response = authenticated_client.post(
|
||||
"/tool-types",
|
||||
@@ -52,7 +56,9 @@ class TestToolTypesAPIExtended:
|
||||
assert data["readiness_probe"]["command"] == "curl -f http://localhost:8080"
|
||||
assert data["readiness_probe"]["timeout"] == 30
|
||||
|
||||
def test_create_tool_type_invalid_definition_type(self, authenticated_client: TestClient) -> None:
|
||||
def test_create_tool_type_invalid_definition_type(
|
||||
self, authenticated_client: TestClient
|
||||
) -> None:
|
||||
"""Test that invalid definition types are rejected."""
|
||||
response = authenticated_client.post(
|
||||
"/tool-types",
|
||||
@@ -67,7 +73,9 @@ class TestToolTypesAPIExtended:
|
||||
)
|
||||
assert response.status_code == 422
|
||||
|
||||
def test_create_tool_type_dockerfile_without_template(self, authenticated_client: TestClient) -> None:
|
||||
def test_create_tool_type_dockerfile_without_template(
|
||||
self, authenticated_client: TestClient
|
||||
) -> None:
|
||||
"""Test that dockerfile type requires dockerfile_template."""
|
||||
response = authenticated_client.post(
|
||||
"/tool-types",
|
||||
@@ -81,7 +89,9 @@ class TestToolTypesAPIExtended:
|
||||
)
|
||||
assert response.status_code == 422
|
||||
|
||||
def test_update_tool_type_with_new_fields(self, authenticated_client: TestClient) -> None:
|
||||
def test_update_tool_type_with_new_fields(
|
||||
self, authenticated_client: TestClient
|
||||
) -> None:
|
||||
"""Test updating a tool type with new fields."""
|
||||
# Create tool type first
|
||||
create_response = authenticated_client.post(
|
||||
@@ -112,7 +122,9 @@ class TestToolTypesAPIExtended:
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["display_name"] == "Updated Name"
|
||||
assert data["readiness_probe"]["command"] == "curl -f http://localhost:8080/health"
|
||||
assert (
|
||||
data["readiness_probe"]["command"] == "curl -f http://localhost:8080/health"
|
||||
)
|
||||
|
||||
def test_validate_tool_type_compose(self, authenticated_client: TestClient) -> None:
|
||||
"""Test validating compose template."""
|
||||
@@ -127,7 +139,9 @@ class TestToolTypesAPIExtended:
|
||||
data = response.json()
|
||||
assert data["valid"] is True
|
||||
|
||||
def test_validate_tool_type_invalid_compose(self, authenticated_client: TestClient) -> None:
|
||||
def test_validate_tool_type_invalid_compose(
|
||||
self, authenticated_client: TestClient
|
||||
) -> None:
|
||||
"""Test validating invalid compose template."""
|
||||
response = authenticated_client.post(
|
||||
"/tool-types/validate",
|
||||
@@ -141,7 +155,9 @@ class TestToolTypesAPIExtended:
|
||||
assert data["valid"] is False
|
||||
assert "errors" in data
|
||||
|
||||
def test_validate_tool_type_dockerfile(self, authenticated_client: TestClient) -> None:
|
||||
def test_validate_tool_type_dockerfile(
|
||||
self, authenticated_client: TestClient
|
||||
) -> None:
|
||||
"""Test validating dockerfile template."""
|
||||
response = authenticated_client.post(
|
||||
"/tool-types/validate",
|
||||
@@ -154,7 +170,9 @@ class TestToolTypesAPIExtended:
|
||||
data = response.json()
|
||||
assert data["valid"] is True
|
||||
|
||||
def test_get_tool_type_returns_new_fields(self, authenticated_client: TestClient) -> None:
|
||||
def test_get_tool_type_returns_new_fields(
|
||||
self, authenticated_client: TestClient
|
||||
) -> None:
|
||||
"""Test that GET returns new fields."""
|
||||
# Create tool type with all fields
|
||||
create_response = authenticated_client.post(
|
||||
@@ -166,7 +184,7 @@ class TestToolTypesAPIExtended:
|
||||
"interfaces": ["web", "terminal"],
|
||||
"default_port": 8443,
|
||||
"definition_type": "compose",
|
||||
"compose_template": "version: '3.8'\nservices:\n app:\n image: code-server\n ports:\n - '8443:8443'\n volumes:\n - \"{{REPO_PATH}}:/workspace\"",
|
||||
"compose_template": "version: '3.8'\nservices:\n app:\n image: code-server\n command: --bind-addr 0.0.0.0:8443\n ports:\n - '8443:8443'\n volumes:\n - \"{{REPO_PATH}}:/workspace\"",
|
||||
"readiness_probe": {
|
||||
"command": "curl -f http://localhost:8443",
|
||||
"timeout": 30,
|
||||
@@ -186,7 +204,9 @@ class TestToolTypesAPIExtended:
|
||||
assert data["interfaces"] == ["web", "terminal"]
|
||||
assert "readiness_probe" in data
|
||||
|
||||
def test_create_tool_type_without_port_fails(self, authenticated_client: TestClient) -> None:
|
||||
def test_create_tool_type_without_port_fails(
|
||||
self, authenticated_client: TestClient
|
||||
) -> None:
|
||||
"""Test that creating a tool type without default_port fails validation."""
|
||||
response = authenticated_client.post(
|
||||
"/tool-types",
|
||||
@@ -204,7 +224,9 @@ class TestToolTypesAPIExtended:
|
||||
data = response.json()
|
||||
assert "default_port" in str(data)
|
||||
|
||||
def test_create_tool_type_with_port_mismatch_fails(self, authenticated_client: TestClient) -> None:
|
||||
def test_create_tool_type_with_port_mismatch_fails(
|
||||
self, authenticated_client: TestClient
|
||||
) -> None:
|
||||
"""Test that port mismatch between default_port and compose template fails."""
|
||||
response = authenticated_client.post(
|
||||
"/tool-types",
|
||||
@@ -222,7 +244,9 @@ class TestToolTypesAPIExtended:
|
||||
assert response.status_code == 422
|
||||
_ = response.json()
|
||||
|
||||
def test_create_tool_type_with_startup_command(self, authenticated_client: TestClient) -> None:
|
||||
def test_create_tool_type_with_startup_command(
|
||||
self, authenticated_client: TestClient
|
||||
) -> None:
|
||||
"""Test creating a tool type with startup_command."""
|
||||
response = authenticated_client.post(
|
||||
"/tool-types",
|
||||
@@ -244,7 +268,9 @@ class TestToolTypesAPIExtended:
|
||||
assert data["startup_command"] == "cd /workspace && ls"
|
||||
assert data["interface_type"] == "terminal"
|
||||
|
||||
def test_update_tool_type_startup_command(self, authenticated_client: TestClient) -> None:
|
||||
def test_update_tool_type_startup_command(
|
||||
self, authenticated_client: TestClient
|
||||
) -> None:
|
||||
"""Test updating a tool type's startup_command."""
|
||||
# Create tool type first
|
||||
create_response = authenticated_client.post(
|
||||
@@ -273,7 +299,9 @@ class TestToolTypesAPIExtended:
|
||||
data = response.json()
|
||||
assert data["startup_command"] == "source /etc/profile"
|
||||
|
||||
def test_get_tool_type_returns_startup_command(self, authenticated_client: TestClient) -> None:
|
||||
def test_get_tool_type_returns_startup_command(
|
||||
self, authenticated_client: TestClient
|
||||
) -> None:
|
||||
"""Test that GET returns startup_command."""
|
||||
create_response = authenticated_client.post(
|
||||
"/tool-types",
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Unit tests for lifecycle hook helpers."""
|
||||
|
||||
import pytest
|
||||
|
||||
from src.services.lifecycle_hooks import _derive_title, _should_notify
|
||||
|
||||
|
||||
class TestDeriveTitle:
|
||||
"""Tests for _derive_title."""
|
||||
|
||||
def test_known_event_types(self) -> None:
|
||||
assert _derive_title("instance.created") == "Container created"
|
||||
assert _derive_title("instance.started") == "Container started"
|
||||
assert _derive_title("instance.stopped") == "Container stopped"
|
||||
assert _derive_title("instance.restarted") == "Container restarted"
|
||||
assert _derive_title("instance.deleted") == "Container deleted"
|
||||
assert _derive_title("instance.error") == "Container error"
|
||||
assert _derive_title("instance.health_changed") == "Container ready"
|
||||
|
||||
def test_unknown_event_type(self) -> None:
|
||||
assert _derive_title("instance.custom_event") == "Custom Event"
|
||||
|
||||
|
||||
class TestShouldNotify:
|
||||
"""Tests for _should_notify filtering."""
|
||||
|
||||
def test_error_events_are_notified(self) -> None:
|
||||
assert _should_notify("instance.error", "error") is True
|
||||
assert _should_notify("instance.error", None) is True
|
||||
|
||||
def test_health_changed_running_is_notified(self) -> None:
|
||||
assert _should_notify("instance.health_changed", "running") is True
|
||||
|
||||
def test_created_started_stopped_restarted_deleted_filtered(self) -> None:
|
||||
for event in [
|
||||
"instance.created",
|
||||
"instance.started",
|
||||
"instance.stopped",
|
||||
"instance.restarted",
|
||||
"instance.deleted",
|
||||
]:
|
||||
assert _should_notify(event, "pending") is False
|
||||
assert _should_notify(event, "running") is False
|
||||
assert _should_notify(event, None) is False
|
||||
|
||||
def test_health_changed_non_running_filtered(self) -> None:
|
||||
assert _should_notify("instance.health_changed", "unhealthy") is False
|
||||
assert _should_notify("instance.health_changed", "starting") is False
|
||||
assert _should_notify("instance.health_changed", None) is False
|
||||
@@ -308,6 +308,59 @@ async def test_get_unread_count_excludes_dismissed(
|
||||
assert count == 0
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.asyncio
|
||||
async def test_dismiss_all_affects_all_non_dismissed(
|
||||
db_session: AsyncSession,
|
||||
notification_service: NotificationService,
|
||||
user_a: User,
|
||||
) -> None:
|
||||
for i in range(4):
|
||||
await notification_service.create_notification(
|
||||
db_session,
|
||||
user_a.id,
|
||||
category="instance",
|
||||
severity="info",
|
||||
title=f"Notification {i}",
|
||||
)
|
||||
|
||||
cleared = await notification_service.dismiss_all(db_session, user_a.id)
|
||||
|
||||
assert cleared == 4
|
||||
items, total = await notification_service.list_notifications(db_session, user_a.id)
|
||||
assert total == 0
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.asyncio
|
||||
async def test_dismiss_all_affects_only_caller(
|
||||
db_session: AsyncSession,
|
||||
notification_service: NotificationService,
|
||||
user_a: User,
|
||||
user_b: User,
|
||||
) -> None:
|
||||
for i in range(3):
|
||||
await notification_service.create_notification(
|
||||
db_session, user_a.id, category="instance", severity="info", title=f"A-{i}"
|
||||
)
|
||||
for i in range(2):
|
||||
await notification_service.create_notification(
|
||||
db_session, user_b.id, category="instance", severity="info", title=f"B-{i}"
|
||||
)
|
||||
|
||||
cleared = await notification_service.dismiss_all(db_session, user_a.id)
|
||||
|
||||
assert cleared == 3
|
||||
items_a, total_a = await notification_service.list_notifications(
|
||||
db_session, user_a.id
|
||||
)
|
||||
items_b, total_b = await notification_service.list_notifications(
|
||||
db_session, user_b.id
|
||||
)
|
||||
assert total_a == 0
|
||||
assert total_b == 2
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.asyncio
|
||||
async def test_mark_all_read_affects_only_caller(
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
"""Unit tests for notification API route ordering."""
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from src.api.notifications import router as notifications_router
|
||||
|
||||
|
||||
def test_delete_notifications_route_order() -> None:
|
||||
"""DELETE /notifications must match before DELETE /notifications/{id}.
|
||||
|
||||
FastAPI matches routes in declaration order. The bulk clear endpoint
|
||||
(DELETE /notifications) must be registered before the single dismiss
|
||||
endpoint (DELETE /notifications/{notification_id}) or the path
|
||||
parameter route will intercept the bulk route.
|
||||
"""
|
||||
app = FastAPI()
|
||||
app.include_router(notifications_router)
|
||||
client = TestClient(app)
|
||||
|
||||
# Verify the bulk delete route exists and returns the expected schema
|
||||
# (it will 401 without auth, but that's fine — we just need to confirm
|
||||
# routing doesn't hit the UUID-parameter route first)
|
||||
response = client.delete("/notifications")
|
||||
# Should get 401 (unauthenticated), NOT 422 (UUID parse error)
|
||||
assert response.status_code == 401, (
|
||||
f"Expected 401 (auth required), got {response.status_code}. "
|
||||
f"Route order may be wrong — DELETE /notifications matched "
|
||||
f"DELETE /notifications/{{notification_id}} instead."
|
||||
)
|
||||
|
||||
# Verify the single dismiss route still works (also 401 without auth)
|
||||
response = client.delete("/notifications/12345678-1234-1234-1234-123456789abc")
|
||||
assert response.status_code == 401
|
||||
@@ -64,6 +64,24 @@ class TestApplyMountPermissions:
|
||||
"find /home/user/.ssh -type f -exec chmod 0600" in file_mode_call[0][1][2]
|
||||
)
|
||||
|
||||
@patch("src.services.permission_fixer._run_in_container")
|
||||
def test_skips_readonly_mount(self, mock_run) -> None:
|
||||
mounts = [
|
||||
{
|
||||
"name": "ssh_keys",
|
||||
"target": "/home/user/.ssh",
|
||||
"readonly": True,
|
||||
"mode": "0700",
|
||||
"file_mode": "0600",
|
||||
},
|
||||
]
|
||||
results = apply_mount_permissions("abc123", mounts)
|
||||
|
||||
assert len(results) == 1
|
||||
assert results[0]["mount_name"] == "ssh_keys"
|
||||
assert results[0]["success"] is True
|
||||
mock_run.assert_not_called()
|
||||
|
||||
@patch("src.services.permission_fixer._run_in_container")
|
||||
def test_skips_mount_with_no_policy(self, mock_run) -> None:
|
||||
mounts = [
|
||||
|
||||
@@ -13,7 +13,9 @@ class TestPrepareSshKeyFiles:
|
||||
"""Tests for prepare_ssh_key_files."""
|
||||
|
||||
@patch("src.services.ssh_keys._get_fernet")
|
||||
def test_creates_files_with_default_permissions(self, mock_fernet, tmp_path) -> None:
|
||||
def test_creates_files_with_default_permissions(
|
||||
self, mock_fernet, tmp_path
|
||||
) -> None:
|
||||
mock_fernet.return_value.decrypt.return_value = b"private-key-content"
|
||||
ssh_key = MagicMock()
|
||||
ssh_key.private_key_encrypted = "enc"
|
||||
@@ -35,9 +37,7 @@ class TestPrepareSshKeyFiles:
|
||||
ssh_key.public_key = "ssh-ed25519 AAA test@test"
|
||||
|
||||
with patch("os.chown") as mock_chown:
|
||||
ssh_dir = prepare_ssh_key_files(
|
||||
str(tmp_path), ssh_key, uid=1001, gid=1001
|
||||
)
|
||||
ssh_dir = prepare_ssh_key_files(str(tmp_path), ssh_key, uid=1001, gid=1001)
|
||||
|
||||
# os.chown is called for the directory and each of the 3 files
|
||||
assert mock_chown.call_count == 4
|
||||
@@ -56,8 +56,6 @@ class TestPrepareSshKeyFiles:
|
||||
|
||||
with patch("os.chown", side_effect=PermissionError("not allowed")):
|
||||
# Should not raise
|
||||
ssh_dir = prepare_ssh_key_files(
|
||||
str(tmp_path), ssh_key, uid=1001, gid=1001
|
||||
)
|
||||
ssh_dir = prepare_ssh_key_files(str(tmp_path), ssh_key, uid=1001, gid=1001)
|
||||
|
||||
assert Path(ssh_dir).exists()
|
||||
|
||||
@@ -411,8 +411,9 @@ class TestStartInstanceLegacyFallback:
|
||||
@patch("src.api.tool_instances.wait_for_container_running")
|
||||
@patch("src.api.tool_instances.execute_compose_command")
|
||||
@patch("src.api.tool_instances.get_container_id")
|
||||
@patch("src.api.tool_instances.get_container_name")
|
||||
@patch("src.api.tool_instances.connect_container_to_network")
|
||||
@patch("src.api.tool_instances._ensure_container_name_in_compose")
|
||||
@patch("src.api.tool_instances._ensure_web_bind_address")
|
||||
@patch("src.api.tool_instances._sanitize_compose_file")
|
||||
@patch("src.api.tool_instances._prepare_manifest_instance")
|
||||
@patch("src.api.tool_instances._get_user")
|
||||
@@ -423,8 +424,9 @@ class TestStartInstanceLegacyFallback:
|
||||
mock_get_user,
|
||||
mock_prepare_manifest,
|
||||
mock_sanitize,
|
||||
mock_ensure_web_bind,
|
||||
mock_ensure_container_name,
|
||||
mock_connect_network,
|
||||
mock_get_container_name,
|
||||
mock_get_container_id,
|
||||
mock_execute_compose,
|
||||
mock_wait_container,
|
||||
@@ -440,7 +442,6 @@ class TestStartInstanceLegacyFallback:
|
||||
mock_get_project.return_value = AsyncMock()
|
||||
mock_execute_compose.return_value = (0, "started", "")
|
||||
mock_get_container_id.return_value = "abc123"
|
||||
mock_get_container_name.return_value = "test-container"
|
||||
mock_connect_network.return_value = True
|
||||
mock_wait_container.return_value = {
|
||||
"success": True,
|
||||
@@ -509,8 +510,9 @@ class TestStartInstanceLegacyFallback:
|
||||
@patch("src.api.tool_instances.wait_for_container_running")
|
||||
@patch("src.api.tool_instances.execute_compose_command")
|
||||
@patch("src.api.tool_instances.get_container_id")
|
||||
@patch("src.api.tool_instances.get_container_name")
|
||||
@patch("src.api.tool_instances.connect_container_to_network")
|
||||
@patch("src.api.tool_instances._ensure_container_name_in_compose")
|
||||
@patch("src.api.tool_instances._ensure_web_bind_address")
|
||||
@patch("src.api.tool_instances._sanitize_compose_file")
|
||||
@patch("src.api.tool_instances._prepare_manifest_instance")
|
||||
@patch("src.api.tool_instances._get_user")
|
||||
@@ -521,8 +523,9 @@ class TestStartInstanceLegacyFallback:
|
||||
mock_get_user,
|
||||
mock_prepare_manifest,
|
||||
mock_sanitize,
|
||||
mock_ensure_web_bind,
|
||||
mock_ensure_container_name,
|
||||
mock_connect_network,
|
||||
mock_get_container_name,
|
||||
mock_get_container_id,
|
||||
mock_execute_compose,
|
||||
mock_wait_container,
|
||||
@@ -538,7 +541,6 @@ class TestStartInstanceLegacyFallback:
|
||||
mock_get_project.return_value = AsyncMock()
|
||||
mock_execute_compose.return_value = (0, "started", "")
|
||||
mock_get_container_id.return_value = "abc123"
|
||||
mock_get_container_name.return_value = "test-container"
|
||||
mock_connect_network.return_value = True
|
||||
mock_wait_container.return_value = {
|
||||
"success": True,
|
||||
@@ -606,8 +608,9 @@ class TestStartInstanceLegacyFallback:
|
||||
@patch("src.api.tool_instances.wait_for_container_running")
|
||||
@patch("src.api.tool_instances.execute_compose_command")
|
||||
@patch("src.api.tool_instances.get_container_id")
|
||||
@patch("src.api.tool_instances.get_container_name")
|
||||
@patch("src.api.tool_instances.connect_container_to_network")
|
||||
@patch("src.api.tool_instances._ensure_container_name_in_compose")
|
||||
@patch("src.api.tool_instances._ensure_web_bind_address")
|
||||
@patch("src.api.tool_instances._sanitize_compose_file")
|
||||
@patch("src.api.tool_instances._prepare_manifest_instance")
|
||||
@patch("src.api.tool_instances._get_user")
|
||||
@@ -618,8 +621,9 @@ class TestStartInstanceLegacyFallback:
|
||||
mock_get_user,
|
||||
mock_prepare_manifest,
|
||||
mock_sanitize,
|
||||
mock_ensure_web_bind,
|
||||
mock_ensure_container_name,
|
||||
mock_connect_network,
|
||||
mock_get_container_name,
|
||||
mock_get_container_id,
|
||||
mock_execute_compose,
|
||||
mock_wait_container,
|
||||
@@ -635,7 +639,6 @@ class TestStartInstanceLegacyFallback:
|
||||
mock_get_project.return_value = AsyncMock()
|
||||
mock_execute_compose.return_value = (0, "started", "")
|
||||
mock_get_container_id.return_value = "abc123"
|
||||
mock_get_container_name.return_value = "test-container"
|
||||
mock_connect_network.return_value = True
|
||||
mock_wait_container.return_value = {
|
||||
"success": True,
|
||||
@@ -705,12 +708,14 @@ class TestStartInstanceSshPermissions:
|
||||
"""SSH key mounts trigger permission fixes after container starts."""
|
||||
|
||||
@patch("src.api.tool_instances.write_compose_file")
|
||||
@patch("src.api.tool_instances.prepare_ssh_key_files")
|
||||
@patch("src.api.tool_instances.apply_ssh_permissions")
|
||||
@patch("src.api.tool_instances.wait_for_container_running")
|
||||
@patch("src.api.tool_instances.execute_compose_command")
|
||||
@patch("src.api.tool_instances.get_container_id")
|
||||
@patch("src.api.tool_instances.get_container_name")
|
||||
@patch("src.api.tool_instances.connect_container_to_network")
|
||||
@patch("src.api.tool_instances._ensure_container_name_in_compose")
|
||||
@patch("src.api.tool_instances._ensure_web_bind_address")
|
||||
@patch("src.api.tool_instances._sanitize_compose_file")
|
||||
@patch("src.api.tool_instances._get_user")
|
||||
@patch("src.api.tool_instances._get_owned_project")
|
||||
@@ -719,12 +724,14 @@ class TestStartInstanceSshPermissions:
|
||||
mock_get_project,
|
||||
mock_get_user,
|
||||
mock_sanitize,
|
||||
mock_ensure_web_bind,
|
||||
mock_ensure_container_name,
|
||||
mock_connect_network,
|
||||
mock_get_container_name,
|
||||
mock_get_container_id,
|
||||
mock_execute_compose,
|
||||
mock_wait_container,
|
||||
mock_apply_ssh,
|
||||
mock_prepare_ssh,
|
||||
mock_write_compose,
|
||||
mock_session,
|
||||
fake_user_id,
|
||||
@@ -743,7 +750,6 @@ class TestStartInstanceSshPermissions:
|
||||
mock_get_project.return_value = AsyncMock()
|
||||
mock_execute_compose.return_value = (0, "started", "")
|
||||
mock_get_container_id.return_value = "abc123"
|
||||
mock_get_container_name.return_value = "test-container"
|
||||
mock_connect_network.return_value = True
|
||||
mock_wait_container.return_value = {
|
||||
"success": True,
|
||||
@@ -836,12 +842,14 @@ class TestStartInstanceSshPermissions:
|
||||
assert result["status"] == "running"
|
||||
mock_apply_ssh.assert_called_once_with("abc123", "/home/user/.ssh", "user")
|
||||
|
||||
@patch("src.api.tool_instances.prepare_ssh_key_files")
|
||||
@patch("src.api.tool_instances.apply_ssh_permissions")
|
||||
@patch("src.api.tool_instances.wait_for_container_running")
|
||||
@patch("src.api.tool_instances.execute_compose_command")
|
||||
@patch("src.api.tool_instances.get_container_id")
|
||||
@patch("src.api.tool_instances.get_container_name")
|
||||
@patch("src.api.tool_instances.connect_container_to_network")
|
||||
@patch("src.api.tool_instances._ensure_container_name_in_compose")
|
||||
@patch("src.api.tool_instances._ensure_web_bind_address")
|
||||
@patch("src.api.tool_instances._sanitize_compose_file")
|
||||
@patch("src.api.tool_instances._get_user")
|
||||
@patch("src.api.tool_instances._get_owned_project")
|
||||
@@ -850,12 +858,14 @@ class TestStartInstanceSshPermissions:
|
||||
mock_get_project,
|
||||
mock_get_user,
|
||||
mock_sanitize,
|
||||
mock_ensure_web_bind,
|
||||
mock_ensure_container_name,
|
||||
mock_connect_network,
|
||||
mock_get_container_name,
|
||||
mock_get_container_id,
|
||||
mock_execute_compose,
|
||||
mock_wait_container,
|
||||
mock_apply_ssh,
|
||||
mock_prepare_ssh,
|
||||
mock_session,
|
||||
fake_user_id,
|
||||
fake_project_id,
|
||||
@@ -870,7 +880,6 @@ class TestStartInstanceSshPermissions:
|
||||
mock_get_project.return_value = AsyncMock()
|
||||
mock_execute_compose.return_value = (0, "started", "")
|
||||
mock_get_container_id.return_value = "abc123"
|
||||
mock_get_container_name.return_value = "test-container"
|
||||
mock_connect_network.return_value = True
|
||||
mock_wait_container.return_value = {
|
||||
"success": True,
|
||||
@@ -933,14 +942,15 @@ class TestStartInstanceSshPermissions:
|
||||
mock_session.get.side_effect = _get
|
||||
|
||||
with patch("os.path.exists", return_value=True):
|
||||
result = await start_instance(
|
||||
project_id=fake_project_id,
|
||||
repo_id=fake_repo_id,
|
||||
instance_id=fake_instance_id,
|
||||
data=None,
|
||||
user_id=fake_user_id,
|
||||
session=mock_session,
|
||||
)
|
||||
with patch("src.api.tool_instances._modify_compose_file"):
|
||||
result = await start_instance(
|
||||
project_id=fake_project_id,
|
||||
repo_id=fake_repo_id,
|
||||
instance_id=fake_instance_id,
|
||||
data=None,
|
||||
user_id=fake_user_id,
|
||||
session=mock_session,
|
||||
)
|
||||
|
||||
assert result["status"] == "running"
|
||||
mock_apply_ssh.assert_called_once_with("abc123", "/root/.ssh", "root")
|
||||
@@ -952,8 +962,9 @@ class TestStartInstanceManifestBranch:
|
||||
@patch("src.api.tool_instances.wait_for_container_running")
|
||||
@patch("src.api.tool_instances.execute_compose_command")
|
||||
@patch("src.api.tool_instances.get_container_id")
|
||||
@patch("src.api.tool_instances.get_container_name")
|
||||
@patch("src.api.tool_instances.connect_container_to_network")
|
||||
@patch("src.api.tool_instances._ensure_container_name_in_compose")
|
||||
@patch("src.api.tool_instances._ensure_web_bind_address")
|
||||
@patch("src.api.tool_instances._sanitize_compose_file")
|
||||
@patch("src.api.tool_instances._prepare_manifest_instance")
|
||||
@patch("src.api.tool_instances.write_compose_file")
|
||||
@@ -966,8 +977,9 @@ class TestStartInstanceManifestBranch:
|
||||
mock_write_compose,
|
||||
mock_prepare_manifest,
|
||||
mock_sanitize,
|
||||
mock_ensure_web_bind,
|
||||
mock_ensure_container_name,
|
||||
mock_connect_network,
|
||||
mock_get_container_name,
|
||||
mock_get_container_id,
|
||||
mock_execute_compose,
|
||||
mock_wait_container,
|
||||
@@ -987,7 +999,6 @@ class TestStartInstanceManifestBranch:
|
||||
mock_get_project.return_value = AsyncMock()
|
||||
mock_execute_compose.return_value = (0, "started", "")
|
||||
mock_get_container_id.return_value = "abc123"
|
||||
mock_get_container_name.return_value = "test-container"
|
||||
mock_connect_network.return_value = True
|
||||
mock_wait_container.return_value = {
|
||||
"success": True,
|
||||
|
||||
@@ -30,6 +30,10 @@ export interface MarkAllReadResponse {
|
||||
marked_count: number;
|
||||
}
|
||||
|
||||
export interface ClearAllResponse {
|
||||
cleared_count: number;
|
||||
}
|
||||
|
||||
export const getNotifications = async (): Promise<NotificationListResponse> => {
|
||||
const response =
|
||||
await apiClient.get<NotificationListResponse>("/notifications");
|
||||
@@ -62,3 +66,8 @@ export const markAllNotificationsRead = async (): Promise<number> => {
|
||||
export const dismissNotification = async (id: string): Promise<void> => {
|
||||
await apiClient.delete(`/notifications/${id}`);
|
||||
};
|
||||
|
||||
export const clearAllNotifications = async (): Promise<number> => {
|
||||
const response = await apiClient.delete<ClearAllResponse>("/notifications");
|
||||
return response.data.cleared_count;
|
||||
};
|
||||
|
||||
@@ -171,7 +171,13 @@ export const CreateSessionForm = ({
|
||||
);
|
||||
|
||||
setProgress("Starting container...");
|
||||
await startInstance(projectId, repoId, instance.id);
|
||||
await startInstance(
|
||||
projectId,
|
||||
repoId,
|
||||
instance.id,
|
||||
selectedConfigProfile || undefined,
|
||||
selectedSshKeyIds.length > 0 ? selectedSshKeyIds : undefined
|
||||
);
|
||||
|
||||
// Reset form
|
||||
if (!fixedProjectId) setSelectedProject("");
|
||||
|
||||
@@ -9,6 +9,7 @@ vi.mock("../api/notifications", () => ({
|
||||
markNotificationRead: vi.fn(),
|
||||
markAllNotificationsRead: vi.fn(),
|
||||
dismissNotification: vi.fn(),
|
||||
clearAllNotifications: vi.fn(),
|
||||
}));
|
||||
|
||||
import { getNotifications, getUnreadCount } from "../api/notifications";
|
||||
@@ -146,6 +147,26 @@ describe("NotificationCenter", () => {
|
||||
expect(vi.mocked(mockMarkAll)).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("calls clearAll on clear-all button click", async () => {
|
||||
mockedGetNotifications.mockResolvedValue({
|
||||
items: [makeNotification("1")],
|
||||
total: 1,
|
||||
limit: 20,
|
||||
offset: 0,
|
||||
});
|
||||
|
||||
render(<NotificationCenter />, { wrapper });
|
||||
fireEvent.click(screen.getByRole("button", { name: /notifications/i }));
|
||||
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
fireEvent.click(screen.getByRole("button", { name: /clear all/i }));
|
||||
|
||||
const { clearAllNotifications: mockClearAll } = await import(
|
||||
"../api/notifications"
|
||||
);
|
||||
expect(vi.mocked(mockClearAll)).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("refreshes list immediately on open", async () => {
|
||||
render(<NotificationCenter />, { wrapper });
|
||||
fireEvent.click(screen.getByRole("button", { name: /notifications/i }));
|
||||
|
||||
@@ -15,6 +15,7 @@ export function NotificationCenter({
|
||||
unreadCount,
|
||||
markRead,
|
||||
markAllRead,
|
||||
clearAll,
|
||||
dismiss,
|
||||
refreshList,
|
||||
isDropdownOpen,
|
||||
@@ -115,6 +116,15 @@ export function NotificationCenter({
|
||||
>
|
||||
Mark all as read
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="notification-clear-all"
|
||||
onClick={() => {
|
||||
void clearAll();
|
||||
}}
|
||||
>
|
||||
Clear all
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -313,6 +313,96 @@ export const TerminalComponent = React.forwardRef<TerminalRef, TerminalProps>(
|
||||
term.focus();
|
||||
const ws = connectWebSocket();
|
||||
|
||||
// Mobile touch scroll.
|
||||
// In normal mode xterm.js has a scrollable viewport; in alternate
|
||||
// screen (tmux/vim) there is no scrollback and the only way to
|
||||
// scroll is to send mouse-wheel protocol sequences to the
|
||||
// application. We detect which situation we're in by checking
|
||||
// whether the viewport has scrollable height.
|
||||
let touchCleanup: (() => void) | undefined;
|
||||
if (isMobile) {
|
||||
let startY = 0;
|
||||
let startX = 0;
|
||||
let isScrolling = false;
|
||||
|
||||
const onTouchStart = (e: TouchEvent) => {
|
||||
if (e.touches.length === 1) {
|
||||
startY = e.touches[0].clientY;
|
||||
startX = e.touches[0].clientX;
|
||||
isScrolling = false;
|
||||
}
|
||||
};
|
||||
const onTouchMove = (e: TouchEvent) => {
|
||||
if (e.touches.length !== 1) return;
|
||||
const touch = e.touches[0];
|
||||
const deltaY = startY - touch.clientY;
|
||||
const deltaX = Math.abs(startX - touch.clientX);
|
||||
if (!isScrolling) {
|
||||
if (Math.abs(deltaY) > deltaX && Math.abs(deltaY) > 4) {
|
||||
isScrolling = true;
|
||||
}
|
||||
}
|
||||
if (isScrolling) {
|
||||
e.preventDefault();
|
||||
const viewport = container.querySelector(
|
||||
".xterm-viewport",
|
||||
) as HTMLElement | null;
|
||||
if (!viewport) return;
|
||||
|
||||
// If the viewport is scrollable, scroll it directly.
|
||||
// Otherwise we are in alternate screen (tmux/vim) and must
|
||||
// send SGR 1006 mouse-wheel protocol data.
|
||||
const hasScrollback =
|
||||
viewport.scrollHeight > viewport.clientHeight;
|
||||
if (hasScrollback) {
|
||||
viewport.scrollTop += deltaY;
|
||||
} else {
|
||||
const ws = wsRef.current;
|
||||
if (
|
||||
ws?.readyState === WebSocket.OPEN &&
|
||||
termRef.current
|
||||
) {
|
||||
// Use the cursor position as the wheel location so
|
||||
// tmux knows which pane to scroll.
|
||||
const buf = termRef.current.buffer.active;
|
||||
const col = buf.cursorX + 1;
|
||||
const row = buf.cursorY + 1;
|
||||
// SGR 1006: 64 = wheel-up, 65 = wheel-down
|
||||
const btn = deltaY > 0 ? 64 : 65;
|
||||
ws.send(`\x1b[<${btn};${col};${row}M`);
|
||||
}
|
||||
}
|
||||
startY = touch.clientY;
|
||||
}
|
||||
};
|
||||
const onTouchEnd = () => {
|
||||
isScrolling = false;
|
||||
};
|
||||
|
||||
container.addEventListener("touchstart", onTouchStart, {
|
||||
passive: true,
|
||||
capture: true,
|
||||
});
|
||||
container.addEventListener("touchmove", onTouchMove, {
|
||||
passive: false,
|
||||
capture: true,
|
||||
});
|
||||
container.addEventListener("touchend", onTouchEnd, {
|
||||
capture: true,
|
||||
});
|
||||
touchCleanup = () => {
|
||||
container.removeEventListener("touchstart", onTouchStart, {
|
||||
capture: true,
|
||||
});
|
||||
container.removeEventListener("touchmove", onTouchMove, {
|
||||
capture: true,
|
||||
});
|
||||
container.removeEventListener("touchend", onTouchEnd, {
|
||||
capture: true,
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
// Initial fit after layout settles (terminal must be opened first)
|
||||
let fitAttempts = 0;
|
||||
const doInitialFit = () => {
|
||||
@@ -440,6 +530,7 @@ export const TerminalComponent = React.forwardRef<TerminalRef, TerminalProps>(
|
||||
"visibilitychange",
|
||||
handleVisibilityChange,
|
||||
);
|
||||
if (touchCleanup) touchCleanup();
|
||||
if (ws) {
|
||||
ws.close(1000, "Component unmounting");
|
||||
}
|
||||
@@ -568,7 +659,9 @@ export const TerminalComponent = React.forwardRef<TerminalRef, TerminalProps>(
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={`terminal-wrapper ${isMobile ? "mobile" : ""} ${!showControls ? "no-controls" : ""}`}>
|
||||
<div
|
||||
className={`terminal-wrapper ${isMobile ? "mobile" : ""} ${!showControls ? "no-controls" : ""}`}
|
||||
>
|
||||
{showControls && (
|
||||
<div className="terminal-header">
|
||||
<div className="terminal-header-left">
|
||||
|
||||
+153
-32
@@ -5,10 +5,15 @@ import {
|
||||
TerminalSessionTabs,
|
||||
type TerminalSessionInfo,
|
||||
} from "../components/terminal-session-tabs";
|
||||
import { Icon } from "../components/icon";
|
||||
import { SpecialKeysStrip } from "../components/special-keys-strip";
|
||||
import { SpecialKeysPanel } from "../components/special-keys-panel";
|
||||
import { useMobileViewport } from "../hooks/use-mobile-viewport";
|
||||
import { useAutoHide } from "../hooks/use-auto-hide";
|
||||
import { useVirtualKeyboard } from "../hooks/use-virtual-keyboard";
|
||||
import { useTerminalSessions } from "../hooks/use-terminal-sessions";
|
||||
import type { TerminalSession } from "../api/terminal";
|
||||
import type { ModifierKey } from "../hooks/use-special-keys";
|
||||
|
||||
const SESSIONS_TO_INFO = (sessions: TerminalSession[]): TerminalSessionInfo[] =>
|
||||
sessions.map((s) => ({
|
||||
@@ -39,7 +44,15 @@ export const TerminalPage: React.FC = () => {
|
||||
Record<string, TerminalStatus>
|
||||
>({});
|
||||
const changeFontSizeRef = useRef<((delta: number) => void) | null>(null);
|
||||
const sendDataRef = useRef<((data: string) => void) | null>(null);
|
||||
const focusInputRef = useRef<(() => void) | null>(null);
|
||||
const [showResetConfirm, setShowResetConfirm] = useState(false);
|
||||
const [showSpecialKeysPanel, setShowSpecialKeysPanel] = useState(false);
|
||||
const [activeModifier, setActiveModifier] = useState<ModifierKey | null>(
|
||||
null,
|
||||
);
|
||||
const { isOpen: isKeyboardOpen, height: keyboardHeight } =
|
||||
useVirtualKeyboard();
|
||||
|
||||
const {
|
||||
sessions,
|
||||
@@ -162,6 +175,47 @@ export const TerminalPage: React.FC = () => {
|
||||
setActiveSessionId,
|
||||
]);
|
||||
|
||||
// Keep screen awake while terminal is open
|
||||
useEffect(() => {
|
||||
let wakeLock: WakeLockSentinel | null = null;
|
||||
|
||||
const requestWakeLock = async () => {
|
||||
try {
|
||||
if ("wakeLock" in navigator) {
|
||||
wakeLock = await navigator.wakeLock.request("screen");
|
||||
}
|
||||
} catch {
|
||||
// Wake lock may be denied; silently ignore
|
||||
}
|
||||
};
|
||||
|
||||
void requestWakeLock();
|
||||
|
||||
const handleVisibilityChange = () => {
|
||||
if (document.visibilityState === "visible") {
|
||||
void requestWakeLock();
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener("visibilitychange", handleVisibilityChange);
|
||||
return () => {
|
||||
document.removeEventListener("visibilitychange", handleVisibilityChange);
|
||||
wakeLock?.release().catch(() => {});
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Lock page scroll on mobile terminal so swipes scroll the terminal buffer,
|
||||
// not the page.
|
||||
useEffect(() => {
|
||||
if (!isMobile) return;
|
||||
document.documentElement.classList.add("terminal-page-open");
|
||||
document.body.classList.add("terminal-page-open");
|
||||
return () => {
|
||||
document.documentElement.classList.remove("terminal-page-open");
|
||||
document.body.classList.remove("terminal-page-open");
|
||||
};
|
||||
}, [isMobile]);
|
||||
|
||||
// Click outside terminal content/header to exit fullscreen
|
||||
const handleFullscreenClick = useCallback(
|
||||
(e: React.MouseEvent<HTMLElement>) => {
|
||||
@@ -205,15 +259,17 @@ export const TerminalPage: React.FC = () => {
|
||||
|
||||
const handleTerminalReady = useCallback(
|
||||
(
|
||||
_sendData: (data: string) => void,
|
||||
sendData: (data: string) => void,
|
||||
status: TerminalStatus,
|
||||
_focusInput: () => void,
|
||||
focusInput: () => void,
|
||||
changeFontSize: (delta: number) => void,
|
||||
) => {
|
||||
setTerminalStatuses((prev) => ({
|
||||
...prev,
|
||||
[activeSessionId ?? "default"]: status,
|
||||
}));
|
||||
sendDataRef.current = sendData;
|
||||
focusInputRef.current = focusInput;
|
||||
changeFontSizeRef.current = changeFontSize;
|
||||
},
|
||||
[activeSessionId],
|
||||
@@ -223,6 +279,10 @@ export const TerminalPage: React.FC = () => {
|
||||
changeFontSizeRef.current?.(delta);
|
||||
}, []);
|
||||
|
||||
const handleSendKey = useCallback((data: string) => {
|
||||
sendDataRef.current?.(data);
|
||||
}, []);
|
||||
|
||||
const handleReset = useCallback(() => {
|
||||
if (activeSessionId && terminalRefs.current[activeSessionId]) {
|
||||
terminalRefs.current[activeSessionId].current?.reset();
|
||||
@@ -241,45 +301,85 @@ export const TerminalPage: React.FC = () => {
|
||||
const sessionInfos = SESSIONS_TO_INFO(sessions);
|
||||
|
||||
if (isMobile) {
|
||||
const activeSession = sessions.find((s) => s.id === activeSessionId);
|
||||
const status =
|
||||
terminalStatuses[activeSessionId ?? "default"] ?? "connecting";
|
||||
|
||||
return (
|
||||
<section
|
||||
className={`terminal-page mobile ${isFullscreen ? "fullscreen" : ""}`}
|
||||
>
|
||||
{/* Overlay status bar — floats over terminal, never resizes it */}
|
||||
<div
|
||||
className={`terminal-page-header mobile-header ${headerAutoHide.isVisible ? "visible" : "hidden"}`}
|
||||
onClick={() => headerAutoHide.show()}
|
||||
className={`mobile-terminal-overlay ${headerAutoHide.isVisible ? "visible" : "hidden"}`}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<button
|
||||
className="secondary-button"
|
||||
onClick={() => navigate(-1)}
|
||||
type="button"
|
||||
>
|
||||
Back
|
||||
</button>
|
||||
<h1>Terminal</h1>
|
||||
<button
|
||||
className="secondary-button"
|
||||
onClick={() => setIsFullscreen((p) => !p)}
|
||||
type="button"
|
||||
>
|
||||
{isFullscreen ? "Exit" : "Fullscreen"}
|
||||
</button>
|
||||
<div className="mobile-terminal-toolbar">
|
||||
<div className="mobile-terminal-toolbar-left">
|
||||
<button
|
||||
className="mobile-terminal-toolbtn"
|
||||
onClick={() => navigate(-1)}
|
||||
type="button"
|
||||
aria-label="Back"
|
||||
>
|
||||
<Icon name="arrow-left" size="sm" />
|
||||
</button>
|
||||
</div>
|
||||
<div className="mobile-terminal-toolbar-center">
|
||||
<span className="mobile-terminal-title">
|
||||
{activeSession?.name || "Terminal"}
|
||||
</span>
|
||||
<span
|
||||
className={`mobile-terminal-status status-dot ${status}`}
|
||||
aria-label={`Connection status: ${status}`}
|
||||
/>
|
||||
</div>
|
||||
<div className="mobile-terminal-toolbar-right">
|
||||
<button
|
||||
className="mobile-terminal-toolbtn"
|
||||
onClick={() => handleFontSizeChange(-1)}
|
||||
type="button"
|
||||
aria-label="Decrease font size"
|
||||
>
|
||||
<span style={{ fontSize: "0.75rem" }}>A-</span>
|
||||
</button>
|
||||
<button
|
||||
className="mobile-terminal-toolbtn"
|
||||
onClick={() => handleFontSizeChange(1)}
|
||||
type="button"
|
||||
aria-label="Increase font size"
|
||||
>
|
||||
<span style={{ fontSize: "1rem" }}>A+</span>
|
||||
</button>
|
||||
<button
|
||||
className="mobile-terminal-toolbtn"
|
||||
onClick={() => navigate(-1)}
|
||||
type="button"
|
||||
aria-label="Exit terminal"
|
||||
>
|
||||
<Icon name="close" size="sm" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mobile-terminal-overlay-tabs">
|
||||
<TerminalSessionTabs
|
||||
sessions={sessionInfos}
|
||||
activeSessionId={activeSessionId ?? ""}
|
||||
onSelect={handleSelect}
|
||||
onClose={handleClose}
|
||||
onCreate={handleCreate}
|
||||
onRename={handleRename}
|
||||
isMobile={true}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Terminal content — always fills full viewport */}
|
||||
<div
|
||||
className={`mobile-tabs-container ${headerAutoHide.isVisible ? "visible" : "hidden"}`}
|
||||
onClick={() => headerAutoHide.show()}
|
||||
className="terminal-page-content mobile-full"
|
||||
style={{ paddingBottom: isKeyboardOpen ? keyboardHeight : 0 }}
|
||||
onClick={() => headerAutoHide.toggle()}
|
||||
>
|
||||
<TerminalSessionTabs
|
||||
sessions={sessionInfos}
|
||||
activeSessionId={activeSessionId ?? ""}
|
||||
onSelect={handleSelect}
|
||||
onClose={handleClose}
|
||||
onCreate={handleCreate}
|
||||
onRename={handleRename}
|
||||
isMobile={true}
|
||||
/>
|
||||
</div>
|
||||
<div className="terminal-page-content">
|
||||
{error && <div className="terminal-error-banner">{error}</div>}
|
||||
{sessions
|
||||
.filter((session) => session.id === activeSessionId)
|
||||
@@ -291,6 +391,9 @@ export const TerminalPage: React.FC = () => {
|
||||
sessionId={session.id}
|
||||
onClose={() => handleClose(session.id)}
|
||||
isMobile={true}
|
||||
showControls={false}
|
||||
activeModifier={activeModifier}
|
||||
onModifierChange={setActiveModifier}
|
||||
onTerminalReady={handleTerminalReady}
|
||||
/>
|
||||
</div>
|
||||
@@ -301,6 +404,24 @@ export const TerminalPage: React.FC = () => {
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<SpecialKeysStrip
|
||||
onSend={handleSendKey}
|
||||
isVisible={!showSpecialKeysPanel}
|
||||
onMoreClick={() => setShowSpecialKeysPanel(true)}
|
||||
onKeepFocus={() => focusInputRef.current?.()}
|
||||
activeModifier={activeModifier}
|
||||
onModifierChange={setActiveModifier}
|
||||
/>
|
||||
|
||||
<SpecialKeysPanel
|
||||
onSend={handleSendKey}
|
||||
isOpen={showSpecialKeysPanel}
|
||||
onClose={() => setShowSpecialKeysPanel(false)}
|
||||
onKeepFocus={() => focusInputRef.current?.()}
|
||||
activeModifier={activeModifier}
|
||||
onModifierChange={setActiveModifier}
|
||||
/>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
markNotificationRead,
|
||||
markAllNotificationsRead,
|
||||
dismissNotification,
|
||||
clearAllNotifications,
|
||||
} from "../api/notifications";
|
||||
import type { NotificationItem } from "../api/notifications";
|
||||
|
||||
@@ -21,6 +22,7 @@ export interface NotificationContextValue {
|
||||
error: Error | null;
|
||||
markRead: (id: string) => Promise<void>;
|
||||
markAllRead: () => Promise<void>;
|
||||
clearAll: () => Promise<void>;
|
||||
dismiss: (id: string) => Promise<void>;
|
||||
refreshList: () => Promise<void>;
|
||||
isDropdownOpen: boolean;
|
||||
@@ -265,6 +267,24 @@ export function NotificationProvider({
|
||||
await fetchList();
|
||||
}, [fetchList]);
|
||||
|
||||
const clearAll = useCallback(async () => {
|
||||
const { notifications: currentNotifications } = stateRef.current;
|
||||
const unreadInList = currentNotifications.filter(
|
||||
(n) => n.read_at === null,
|
||||
).length;
|
||||
|
||||
setNotifications([]);
|
||||
setUnreadCount((c) => Math.max(0, c - unreadInList));
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
await clearAllNotifications();
|
||||
} catch (err) {
|
||||
setNotifications(currentNotifications);
|
||||
setError(err as Error);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const value: NotificationContextValue = {
|
||||
notifications,
|
||||
unreadCount,
|
||||
@@ -272,6 +292,7 @@ export function NotificationProvider({
|
||||
error,
|
||||
markRead,
|
||||
markAllRead,
|
||||
clearAll,
|
||||
dismiss,
|
||||
refreshList,
|
||||
isDropdownOpen,
|
||||
|
||||
+150
-17
@@ -77,6 +77,11 @@ body {
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
html.terminal-page-open,
|
||||
body.terminal-page-open {
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
[data-theme="dark"] body {
|
||||
background: radial-gradient(circle at top right, #2a2520, var(--bg));
|
||||
}
|
||||
@@ -2950,42 +2955,148 @@ a.nav-item,
|
||||
background: #cd3131;
|
||||
}
|
||||
|
||||
/* Mobile auto-hide header and tabs */
|
||||
.terminal-page.mobile .terminal-page-header,
|
||||
.mobile-tabs-container {
|
||||
/* ============================================
|
||||
Mobile Terminal Overlay
|
||||
============================================ */
|
||||
|
||||
/* Mobile terminal page — no padding, terminal fills viewport */
|
||||
.terminal-page.mobile {
|
||||
padding: 0;
|
||||
gap: 0;
|
||||
height: 100vh;
|
||||
height: 100dvh;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* Overlay status bar — floats over terminal, never resizes it */
|
||||
.mobile-terminal-overlay {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
z-index: 100;
|
||||
background: #2d2d2d;
|
||||
border-bottom: 1px solid #3e3e3e;
|
||||
transition:
|
||||
transform 0.3s ease,
|
||||
opacity 0.3s ease;
|
||||
}
|
||||
|
||||
.terminal-page.mobile .terminal-page-header.hidden,
|
||||
.mobile-tabs-container.hidden {
|
||||
.mobile-terminal-overlay.hidden {
|
||||
transform: translateY(-100%);
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.terminal-page.mobile .terminal-page-header.visible,
|
||||
.mobile-tabs-container.visible {
|
||||
.mobile-terminal-overlay.visible {
|
||||
transform: translateY(0);
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
/* Toolbar row */
|
||||
.mobile-terminal-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: var(--space-2) var(--space-3);
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.mobile-terminal-toolbar-left,
|
||||
.mobile-terminal-toolbar-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.mobile-terminal-toolbar-center {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
flex: 1;
|
||||
justify-content: center;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.mobile-terminal-title {
|
||||
font-size: 0.875rem;
|
||||
font-weight: 500;
|
||||
color: #d4d4d4;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.mobile-terminal-status {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
background: #666;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.mobile-terminal-status.connecting {
|
||||
background: #f5f543;
|
||||
animation: pulse 1.5s infinite;
|
||||
}
|
||||
|
||||
.mobile-terminal-status.connected {
|
||||
background: #0dbc79;
|
||||
}
|
||||
|
||||
.mobile-terminal-status.disconnected,
|
||||
.mobile-terminal-status.error {
|
||||
background: #cd3131;
|
||||
}
|
||||
|
||||
.mobile-terminal-toolbtn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
padding: 0;
|
||||
background: transparent;
|
||||
border: 1px solid #3e3e3e;
|
||||
border-radius: 6px;
|
||||
color: #d4d4d4;
|
||||
cursor: pointer;
|
||||
font-size: 0.875rem;
|
||||
transition: background 0.2s ease;
|
||||
}
|
||||
|
||||
.mobile-terminal-toolbtn:hover {
|
||||
background: #3e3e3e;
|
||||
}
|
||||
|
||||
/* Session tabs inside overlay */
|
||||
.mobile-terminal-overlay-tabs {
|
||||
background: #1e1e1e;
|
||||
border-top: 1px solid #3e3e3e;
|
||||
}
|
||||
|
||||
.mobile-terminal-overlay-tabs .terminal-session-tabs {
|
||||
background: #1e1e1e;
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
/* Terminal content — always fills full viewport on mobile */
|
||||
.terminal-page-content.mobile-full {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
border: none;
|
||||
border-radius: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* Mobile fullscreen */
|
||||
@media (max-width: 767px) {
|
||||
.terminal-page.fullscreen {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.terminal-page.mobile .terminal-page-header {
|
||||
padding: var(--space-2);
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.terminal-page.mobile .terminal-page-header h1 {
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.terminal-session-tab-name {
|
||||
max-width: 80px;
|
||||
}
|
||||
@@ -3597,6 +3708,7 @@ a.nav-item,
|
||||
padding: 0;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
touch-action: none;
|
||||
}
|
||||
|
||||
/* xterm.js manages its own sizing */
|
||||
@@ -4602,10 +4714,12 @@ a:active,
|
||||
padding: 0.75rem 1rem;
|
||||
border-top: 1px solid var(--border);
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.notification-mark-all {
|
||||
width: 100%;
|
||||
flex: 1;
|
||||
padding: 0.5rem 0.75rem;
|
||||
background: transparent;
|
||||
border: 1px solid var(--border);
|
||||
@@ -4623,6 +4737,25 @@ a:active,
|
||||
border-color: var(--brand);
|
||||
}
|
||||
|
||||
.notification-clear-all {
|
||||
flex: 1;
|
||||
padding: 0.5rem 0.75rem;
|
||||
background: transparent;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
color: var(--muted);
|
||||
font: inherit;
|
||||
font-size: 0.85rem;
|
||||
cursor: pointer;
|
||||
transition: all 0.15s ease;
|
||||
}
|
||||
|
||||
.notification-clear-all:hover {
|
||||
background: var(--bg);
|
||||
color: var(--danger);
|
||||
border-color: var(--danger);
|
||||
}
|
||||
|
||||
/* Notification Item */
|
||||
.notification-item {
|
||||
display: flex;
|
||||
|
||||
@@ -13,7 +13,11 @@ services:
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-headquarter} -d ${POSTGRES_DB:-headquarter}"]
|
||||
test:
|
||||
[
|
||||
"CMD-SHELL",
|
||||
"pg_isready -U ${POSTGRES_USER:-headquarter} -d ${POSTGRES_DB:-headquarter}",
|
||||
]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
@@ -92,7 +96,7 @@ services:
|
||||
AUTHENTIK_AUTHORIZE_URL: ${AUTHENTIK_AUTHORIZE_URL:-}
|
||||
AUTHENTIK_TOKEN_URL: ${AUTHENTIK_TOKEN_URL:-}
|
||||
volumes:
|
||||
- repo_data:/data/repos
|
||||
- /data/repos:/data/repos
|
||||
- /data/instances:/data/instances
|
||||
- avatar_uploads:/app/uploads
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
@@ -116,7 +120,6 @@ services:
|
||||
volumes:
|
||||
postgres_data:
|
||||
redis_data:
|
||||
repo_data:
|
||||
avatar_uploads:
|
||||
|
||||
networks:
|
||||
|
||||
+7
-4
@@ -1,4 +1,4 @@
|
||||
version: '3.8'
|
||||
version: "3.8"
|
||||
|
||||
services:
|
||||
# PostgreSQL Database
|
||||
@@ -14,7 +14,11 @@ services:
|
||||
ports:
|
||||
- "5432:5432"
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-headquarter} -d ${POSTGRES_DB:-headquarter}"]
|
||||
test:
|
||||
[
|
||||
"CMD-SHELL",
|
||||
"pg_isready -U ${POSTGRES_USER:-headquarter} -d ${POSTGRES_DB:-headquarter}",
|
||||
]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
@@ -57,7 +61,7 @@ services:
|
||||
REPO_BASE_PATH: /data/repos
|
||||
INSTANCE_BASE_PATH: /data/instances
|
||||
volumes:
|
||||
- repo_data:/data/repos
|
||||
- /data/repos:/data/repos
|
||||
- /data/instances:/data/instances
|
||||
ports:
|
||||
- "8000:8000"
|
||||
@@ -91,7 +95,6 @@ services:
|
||||
volumes:
|
||||
postgres_data:
|
||||
redis_data:
|
||||
repo_data:
|
||||
|
||||
networks:
|
||||
backend:
|
||||
|
||||
Reference in New Issue
Block a user