aiui-code 0.1.2__tar.gz → 0.1.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. {aiui_code-0.1.2 → aiui_code-0.1.3}/PKG-INFO +1 -1
  2. {aiui_code-0.1.2 → aiui_code-0.1.3}/pyproject.toml +1 -1
  3. {aiui_code-0.1.2 → aiui_code-0.1.3}/src/aiui_code/__init__.py +1 -1
  4. {aiui_code-0.1.2 → aiui_code-0.1.3}/src/aiui_code/git_diff.py +56 -20
  5. {aiui_code-0.1.2 → aiui_code-0.1.3}/src/aiui_code/mcp_server.py +11 -2
  6. {aiui_code-0.1.2 → aiui_code-0.1.3}/src/aiui_code/pty_service.py +35 -8
  7. {aiui_code-0.1.2 → aiui_code-0.1.3}/src/aiui_code/routes.py +6 -1
  8. {aiui_code-0.1.2 → aiui_code-0.1.3}/src/aiui_code/runner.py +11 -7
  9. {aiui_code-0.1.2 → aiui_code-0.1.3}/src/aiui_code/security.py +2 -2
  10. {aiui_code-0.1.2 → aiui_code-0.1.3}/src/aiui_code/static/code.js +480 -452
  11. {aiui_code-0.1.2 → aiui_code-0.1.3}/src/aiui_code/workspaces.py +5 -1
  12. {aiui_code-0.1.2 → aiui_code-0.1.3}/tests/test_cli_and_mcp.py +8 -3
  13. {aiui_code-0.1.2 → aiui_code-0.1.3}/tests/test_security.py +6 -1
  14. {aiui_code-0.1.2 → aiui_code-0.1.3}/tests/test_workspaces_and_diff.py +30 -0
  15. {aiui_code-0.1.2 → aiui_code-0.1.3}/.gitignore +0 -0
  16. {aiui_code-0.1.2 → aiui_code-0.1.3}/LICENSE +0 -0
  17. {aiui_code-0.1.2 → aiui_code-0.1.3}/README.md +0 -0
  18. {aiui_code-0.1.2 → aiui_code-0.1.3}/src/aiui_code/approvals.py +0 -0
  19. {aiui_code-0.1.2 → aiui_code-0.1.3}/src/aiui_code/checkpoints.py +0 -0
  20. {aiui_code-0.1.2 → aiui_code-0.1.3}/src/aiui_code/cli_control.py +0 -0
  21. {aiui_code-0.1.2 → aiui_code-0.1.3}/src/aiui_code/client.py +0 -0
  22. {aiui_code-0.1.2 → aiui_code-0.1.3}/src/aiui_code/events.py +0 -0
  23. {aiui_code-0.1.2 → aiui_code-0.1.3}/src/aiui_code/plugin.py +0 -0
  24. {aiui_code-0.1.2 → aiui_code-0.1.3}/src/aiui_code/server.py +0 -0
  25. {aiui_code-0.1.2 → aiui_code-0.1.3}/src/aiui_code/static/code.css +0 -0
  26. {aiui_code-0.1.2 → aiui_code-0.1.3}/src/aiui_code/worktrees.py +0 -0
  27. {aiui_code-0.1.2 → aiui_code-0.1.3}/tests/conftest.py +0 -0
  28. {aiui_code-0.1.2 → aiui_code-0.1.3}/tests/test_browser_e2e.py +0 -0
  29. {aiui_code-0.1.2 → aiui_code-0.1.3}/tests/test_plugin_contract.py +0 -0
  30. {aiui_code-0.1.2 → aiui_code-0.1.3}/tests/test_runner_and_approvals.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aiui-code
3
- Version: 0.1.2
3
+ Version: 0.1.3
4
4
  Summary: Multi-agent coding workspace Web UI plugin for PraisonAIUI (aiui)
5
5
  Project-URL: Homepage, https://github.com/MervinPraison/aiui-code
6
6
  Project-URL: Repository, https://github.com/MervinPraison/aiui-code
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "aiui-code"
7
- version = "0.1.2"
7
+ version = "0.1.3"
8
8
  description = "Multi-agent coding workspace Web UI plugin for PraisonAIUI (aiui)"
9
9
  readme = "README.md"
10
10
  license = { text = "MIT" }
@@ -2,7 +2,7 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- __version__ = "0.1.2"
5
+ __version__ = "0.1.3"
6
6
  __all__ = ["CodePlugin", "__version__", "plugin"]
7
7
 
8
8
 
@@ -23,22 +23,42 @@ class DiffFileSummary:
23
23
 
24
24
 
25
25
  def _split_patches(unified: str) -> dict[str, str]:
26
- """Split a multi-file `git diff` string into `{relative_path: file_patch}`."""
26
+ """Split a multi-file `git diff` string into `{relative_path: file_patch}` (handles spaces)."""
27
27
  patches: dict[str, str] = {}
28
28
  current_path = ""
29
29
  buf: list[str] = []
30
+
31
+ def _flush() -> None:
32
+ if current_path and buf:
33
+ patches[current_path] = "".join(buf)
34
+
30
35
  for line in unified.splitlines(keepends=True):
31
36
  if line.startswith("diff --git "):
32
- if current_path and buf:
33
- patches[current_path] = "".join(buf)
37
+ _flush()
34
38
  buf = [line]
35
- parts = line.strip().split(" ")
36
- b_part = parts[-1] if len(parts) >= 4 else ""
37
- current_path = b_part[2:] if b_part.startswith("b/") else b_part
39
+ # Fallback path extraction; refined below when +++ b/ or --- a/ is seen.
40
+ raw = line[len("diff --git ") :].strip()
41
+ if " b/" in raw:
42
+ current_path = raw.rsplit(" b/", 1)[1].strip('"')
43
+ else:
44
+ parts = raw.split(" ")
45
+ b_part = parts[-1] if parts else ""
46
+ current_path = b_part[2:] if b_part.startswith("b/") else b_part
38
47
  else:
48
+ if line.startswith("+++ "):
49
+ raw_target = line[4:].rstrip("\r\n\t ")
50
+ if raw_target.startswith('"') and raw_target.endswith('"'):
51
+ raw_target = raw_target[1:-1]
52
+ if raw_target.startswith("b/"):
53
+ current_path = raw_target[2:]
54
+ elif line.startswith("--- ") and not current_path:
55
+ raw_src = line[4:].rstrip("\r\n\t ")
56
+ if raw_src.startswith('"') and raw_src.endswith('"'):
57
+ raw_src = raw_src[1:-1]
58
+ if raw_src.startswith("a/"):
59
+ current_path = raw_src[2:]
39
60
  buf.append(line)
40
- if current_path and buf:
41
- patches[current_path] = "".join(buf)
61
+ _flush()
42
62
  return patches
43
63
 
44
64
 
@@ -74,14 +94,14 @@ class GitDiffService:
74
94
  return {"is_git": False, "branch": "", "files": [], "additions": 0, "deletions": 0}
75
95
 
76
96
  _, br_out, _ = await run_argv(["git", "rev-parse", "--abbrev-ref", "HEAD"], cwd=root)
77
- _, status_out, _ = await run_argv(["git", "status", "--porcelain=v1"], cwd=root)
78
- _, numstat_out, _ = await run_argv(["git", "diff", "HEAD", "--numstat"], cwd=root)
79
- _, patch_out, _ = await run_argv(["git", "diff", "HEAD", "-U3"], cwd=root)
97
+ _, status_out, _ = await run_argv(["git", "-c", "core.quotePath=false", "status", "--porcelain=v1", "-uall"], cwd=root)
98
+ _, numstat_out, _ = await run_argv(["git", "-c", "core.quotePath=false", "diff", "HEAD", "--numstat"], cwd=root)
99
+ _, patch_out, _ = await run_argv(["git", "-c", "core.quotePath=false", "diff", "HEAD", "-U3"], cwd=root)
80
100
 
81
101
  # Fallback if repo has no HEAD commit yet.
82
102
  if not numstat_out and not patch_out:
83
- _, numstat_out, _ = await run_argv(["git", "diff", "--numstat"], cwd=root)
84
- _, patch_out, _ = await run_argv(["git", "diff", "-U3"], cwd=root)
103
+ _, numstat_out, _ = await run_argv(["git", "-c", "core.quotePath=false", "diff", "--numstat"], cwd=root)
104
+ _, patch_out, _ = await run_argv(["git", "-c", "core.quotePath=false", "diff", "-U3"], cwd=root)
85
105
 
86
106
  stats: dict[str, tuple[int, int]] = {}
87
107
  for line in numstat_out.splitlines():
@@ -142,7 +162,7 @@ class GitDiffService:
142
162
  return {"committed": True, "sha": sha_out.strip(), "output": out.strip()}
143
163
 
144
164
  async def openship_review(self, cwd: Path | str) -> dict[str, Any]:
145
- """Lazily invoke praisonai_code.ship.ui_service self-review when available."""
165
+ """Lazily invoke praisonai_code.ship.ui_service status + diff bundle review."""
146
166
  root = Path(cwd).expanduser().resolve()
147
167
 
148
168
  def _run() -> dict[str, Any]:
@@ -150,30 +170,46 @@ class GitDiffService:
150
170
  from praisonai_code.ship import ui_service
151
171
  except Exception as exc:
152
172
  return {"available": False, "error": f"praisonai-code OpenShip unavailable: {exc}"}
153
- status = ui_service.get_repo_status(str(root))
154
- bundle = ui_service.get_diff_bundle(str(root))
173
+ status = ui_service.get_repo_status(root)
174
+ bundle = ui_service.get_diff_bundle(root)
175
+ if isinstance(bundle, tuple) and len(bundle) >= 2:
176
+ base_ref, file_diffs = str(bundle[0] or ""), list(bundle[1] or [])
177
+ elif isinstance(bundle, list):
178
+ base_ref, file_diffs = "", bundle
179
+ else:
180
+ base_ref, file_diffs = "", []
155
181
  return {
156
182
  "available": True,
157
183
  "branch": getattr(status, "branch", ""),
184
+ "base_ref": base_ref,
158
185
  "dirty": getattr(status, "dirty", False),
159
- "changed_files": len(bundle) if isinstance(bundle, list) else 0,
186
+ "changed_files": len(file_diffs),
187
+ "files": [getattr(f, "path", str(f)) for f in file_diffs[:50]],
160
188
  }
161
189
 
162
190
  return await asyncio.to_thread(_run)
163
191
 
164
- async def openship_draft_pr(self, cwd: Path | str, *, title: str, body: str = "") -> dict[str, Any]:
165
- """Lazily create a draft PR via praisonai_code.ship.ui_service (never auto-merges)."""
192
+ async def openship_draft_pr(
193
+ self,
194
+ cwd: Path | str,
195
+ *,
196
+ title: str,
197
+ body: str = "",
198
+ confirm: bool = False,
199
+ ) -> dict[str, Any]:
200
+ """Lazily preview or create a draft PR via praisonai_code.ship.ui_service (never auto-merges)."""
166
201
  root = Path(cwd).expanduser().resolve()
167
202
  clean_title = (title or "").strip()
168
203
  if not clean_title:
169
204
  raise ValueError("Draft PR title is required")
205
+ message = f"{clean_title}\n\n{body.strip()}" if body.strip() else clean_title
170
206
 
171
207
  def _run() -> dict[str, Any]:
172
208
  try:
173
209
  from praisonai_code.ship import ui_service
174
210
  except Exception as exc:
175
211
  return {"available": False, "error": f"praisonai-code OpenShip unavailable: {exc}"}
176
- res = ui_service.create_draft_pr(str(root), title=clean_title, body=body)
212
+ res = ui_service.create_draft_pr(root, message=message, confirm=confirm)
177
213
  return res if isinstance(res, dict) else {"result": str(res)}
178
214
 
179
215
  return await asyncio.to_thread(_run)
@@ -543,7 +543,7 @@ async def _dispatch_service_tool(svc: Any, name: str, args: dict[str, Any]) -> A
543
543
  return rec.to_dict()
544
544
  if name == "code_remove_workspace":
545
545
  ws_id = str(args["workspace_id"])
546
- if not svc.workspaces.remove(ws_id):
546
+ if not svc.workspaces.remove(ws_id, from_web=True):
547
547
  raise KeyError(f"Workspace not found: {ws_id!r}")
548
548
  return {"removed": True, "id": ws_id}
549
549
  if name == "code_list_files":
@@ -671,7 +671,7 @@ def run_stdio_server(client: CodeClient) -> None:
671
671
  stripped = line.strip()
672
672
  if not stripped:
673
673
  continue
674
- if stripped.startswith(b"{"):
674
+ if stripped.startswith((b"{", b"[")):
675
675
  return json.loads(stripped.decode("utf-8")), False
676
676
  # Content-Length header framing (LSP / legacy MCP clients)
677
677
  headers: dict[str, str] = {}
@@ -708,6 +708,15 @@ def run_stdio_server(client: CodeClient) -> None:
708
708
  continue
709
709
  if msg is None:
710
710
  break
711
+ if isinstance(msg, list):
712
+ replies = []
713
+ for item in msg:
714
+ r = await handler.handle_message(item)
715
+ if r is not None:
716
+ replies.append(r)
717
+ if replies:
718
+ _write_message(replies, framed) # type: ignore[arg-type]
719
+ continue
711
720
  reply = await handler.handle_message(msg)
712
721
  if reply is not None:
713
722
  _write_message(reply, framed)
@@ -1,18 +1,27 @@
1
- """Opt-in interactive PTY terminal WebSocket service (disabled by default)."""
1
+ """Opt-in interactive PTY terminal WebSocket service (disabled by default, POSIX-safe)."""
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
5
  import asyncio
6
- import fcntl
7
6
  import os
8
- import pty
9
7
  import signal
10
8
  import struct
11
- import termios
12
9
  from pathlib import Path
13
10
 
14
11
  from starlette.websockets import WebSocket, WebSocketDisconnect
15
12
 
13
+ try:
14
+ import fcntl
15
+ import pty
16
+ import termios
17
+
18
+ _POSIX_PTY_AVAILABLE = True
19
+ except ImportError: # Windows
20
+ fcntl = None # type: ignore[assignment]
21
+ pty = None # type: ignore[assignment]
22
+ termios = None # type: ignore[assignment]
23
+ _POSIX_PTY_AVAILABLE = False
24
+
16
25
 
17
26
  class PtySessionManager:
18
27
  """Spawns bounded workspace-scoped shells when `--enable-terminal` is enabled."""
@@ -25,6 +34,9 @@ class PtySessionManager:
25
34
  if not self.enabled:
26
35
  await ws.close(code=4403, reason="Interactive PTY terminal is disabled (start with --enable-terminal)")
27
36
  return
37
+ if not _POSIX_PTY_AVAILABLE:
38
+ await ws.close(code=4501, reason="Interactive PTY terminal requires a POSIX OS")
39
+ return
28
40
 
29
41
  await ws.accept()
30
42
  shell = os.environ.get("SHELL") or "/bin/sh"
@@ -76,22 +88,37 @@ class PtySessionManager:
76
88
  finally:
77
89
  loop.remove_reader(master_fd)
78
90
  pump_task.cancel()
91
+ try:
92
+ await pump_task
93
+ except (asyncio.CancelledError, Exception):
94
+ pass
79
95
  try:
80
96
  os.close(master_fd)
81
97
  except OSError:
82
98
  pass
83
99
  self._terminate_pid(proc.pid)
100
+ try:
101
+ await asyncio.wait_for(proc.wait(), timeout=2.0)
102
+ except (asyncio.TimeoutError, Exception):
103
+ try:
104
+ proc.kill()
105
+ await proc.wait()
106
+ except Exception:
107
+ pass
84
108
  self._pids.discard(proc.pid)
85
109
 
86
110
  @staticmethod
87
111
  def _terminate_pid(pid: int) -> None:
88
- try:
89
- os.killpg(pid, signal.SIGTERM)
90
- except OSError:
112
+ if hasattr(os, "killpg"):
91
113
  try:
92
- os.kill(pid, signal.SIGTERM)
114
+ os.killpg(pid, signal.SIGTERM)
115
+ return
93
116
  except OSError:
94
117
  pass
118
+ try:
119
+ os.kill(pid, signal.SIGTERM)
120
+ except OSError:
121
+ pass
95
122
 
96
123
  async def shutdown(self) -> None:
97
124
  for pid in list(self._pids):
@@ -102,7 +102,11 @@ def build_routes(svc: CodeServiceContainer) -> list[BaseRoute]:
102
102
 
103
103
  async def delete_workspace(request: Request) -> JSONResponse:
104
104
  ws_id = request.path_params["ws_id"]
105
- if not svc.workspaces.remove(ws_id):
105
+ try:
106
+ removed = svc.workspaces.remove(ws_id, from_web=True)
107
+ except SecurityError as exc:
108
+ return JSONResponse({"error": str(exc)}, status_code=403)
109
+ if not removed:
106
110
  return JSONResponse({"error": "Workspace not found"}, status_code=404)
107
111
  return JSONResponse({"removed": True, "id": ws_id})
108
112
 
@@ -255,6 +259,7 @@ def build_routes(svc: CodeServiceContainer) -> list[BaseRoute]:
255
259
  rec.cwd,
256
260
  title=str(body.get("title") or rec.title),
257
261
  body=str(body.get("body") or ""),
262
+ confirm=bool(body.get("confirm", False)),
258
263
  )
259
264
  except ValueError as exc:
260
265
  return JSONResponse({"error": str(exc)}, status_code=400)
@@ -267,11 +267,13 @@ class LocalCodeRunner:
267
267
  flag.set()
268
268
  self.approvals.cancel_for_run(run_id)
269
269
  task = self._tasks.get(run_id)
270
- if task is not None and not task.done():
270
+ was_running = task is not None and not task.done()
271
+ if was_running:
271
272
  task.cancel()
272
- rec.status = "interrupted"
273
- rec.updated_at = datetime.now(timezone.utc).isoformat()
274
- self.events.publish(run_id, "run.interrupted", rec.to_dict())
273
+ if rec.status != "interrupted":
274
+ rec.status = "interrupted"
275
+ rec.updated_at = datetime.now(timezone.utc).isoformat()
276
+ self.events.publish(run_id, "run.interrupted", rec.to_dict())
275
277
  return {"interrupted": True, "run_id": run_id}
276
278
 
277
279
  def _launch_turn(self, rec: RunRecord, prompt: str) -> None:
@@ -335,9 +337,11 @@ class LocalCodeRunner:
335
337
  rec.updated_at = datetime.now(timezone.utc).isoformat()
336
338
  self.events.publish(rec.id, "run.completed", rec.to_dict())
337
339
  except asyncio.CancelledError:
338
- rec.status = "interrupted"
339
- rec.updated_at = datetime.now(timezone.utc).isoformat()
340
- self.events.publish(rec.id, "run.interrupted", rec.to_dict())
340
+ if rec.status != "interrupted":
341
+ rec.status = "interrupted"
342
+ rec.updated_at = datetime.now(timezone.utc).isoformat()
343
+ self.events.publish(run_id := rec.id, "run.interrupted", rec.to_dict())
344
+ _ = run_id
341
345
  except Exception as exc:
342
346
  rec.status = "failed"
343
347
  rec.error = str(exc)
@@ -38,9 +38,9 @@ def enforce_bind_security(host: str, *, require_auth: bool = False) -> None:
38
38
  "true",
39
39
  "yes",
40
40
  }
41
- if not (require_auth or (token and token_required)):
41
+ if not token or not (require_auth or token_required):
42
42
  raise SecurityError(
43
- f"Refusing to bind aiui-code to non-loopback host {host!r} without auth. "
43
+ f"Refusing to bind aiui-code to non-loopback host {host!r} without GATEWAY_AUTH_TOKEN and auth enabled. "
44
44
  "Set GATEWAY_AUTH_TOKEN and AIUI_REQUIRE_TOKEN=1 (or pass --require-auth)."
45
45
  )
46
46