portacode 1.3.25__tar.gz → 1.3.27__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.

Potentially problematic release.


This version of portacode might be problematic. Click here for more details.

Files changed (94) hide show
  1. {portacode-1.3.25 → portacode-1.3.27}/.claude/settings.local.json +1 -2
  2. portacode-1.3.27/MANIFEST.in +3 -0
  3. {portacode-1.3.25 → portacode-1.3.27}/PKG-INFO +19 -41
  4. {portacode-1.3.25 → portacode-1.3.27}/README.md +17 -40
  5. {portacode-1.3.25 → portacode-1.3.27}/docker-compose.yaml +1 -3
  6. {portacode-1.3.25 → portacode-1.3.27}/portacode/_version.py +2 -2
  7. {portacode-1.3.25 → portacode-1.3.27}/portacode/connection/handlers/WEBSOCKET_PROTOCOL.md +131 -13
  8. {portacode-1.3.25 → portacode-1.3.27}/portacode/connection/handlers/base.py +70 -12
  9. {portacode-1.3.25 → portacode-1.3.27}/portacode/connection/handlers/file_handlers.py +5 -10
  10. {portacode-1.3.25 → portacode-1.3.27}/portacode/connection/handlers/project_state/handlers.py +9 -6
  11. {portacode-1.3.25 → portacode-1.3.27}/portacode/connection/handlers/registry.py +15 -4
  12. portacode-1.3.27/portacode/static/js/test-ntp-clock.html +63 -0
  13. portacode-1.3.27/portacode/static/js/utils/ntp-clock.js +141 -0
  14. portacode-1.3.27/portacode/utils/NTP_ARCHITECTURE.md +136 -0
  15. portacode-1.3.27/portacode/utils/__init__.py +1 -0
  16. portacode-1.3.27/portacode/utils/ntp_clock.py +151 -0
  17. {portacode-1.3.25 → portacode-1.3.27}/portacode.egg-info/PKG-INFO +19 -41
  18. {portacode-1.3.25 → portacode-1.3.27}/portacode.egg-info/SOURCES.txt +10 -1
  19. {portacode-1.3.25 → portacode-1.3.27}/portacode.egg-info/requires.txt +1 -0
  20. {portacode-1.3.25 → portacode-1.3.27}/setup.py +7 -0
  21. portacode-1.3.27/test_request_id.py +146 -0
  22. portacode-1.3.27/todo/issues/indefinite_resource_loading.md +5 -0
  23. portacode-1.3.27/todo/issues/premature_terminal_exit.md +66 -0
  24. portacode-1.3.27/tools/test_python_ntp_clock.py +39 -0
  25. portacode-1.3.25/MANIFEST.in +0 -2
  26. {portacode-1.3.25 → portacode-1.3.27}/.claude/agents/communication-manager.md +0 -0
  27. {portacode-1.3.25 → portacode-1.3.27}/.gitignore +0 -0
  28. {portacode-1.3.25 → portacode-1.3.27}/.gitmodules +0 -0
  29. {portacode-1.3.25 → portacode-1.3.27}/LICENSE +0 -0
  30. {portacode-1.3.25 → portacode-1.3.27}/Makefile +0 -0
  31. {portacode-1.3.25 → portacode-1.3.27}/backup.sh +0 -0
  32. {portacode-1.3.25 → portacode-1.3.27}/connect.py +0 -0
  33. {portacode-1.3.25 → portacode-1.3.27}/connect.sh +0 -0
  34. {portacode-1.3.25 → portacode-1.3.27}/portacode/README.md +0 -0
  35. {portacode-1.3.25 → portacode-1.3.27}/portacode/__init__.py +0 -0
  36. {portacode-1.3.25 → portacode-1.3.27}/portacode/__main__.py +0 -0
  37. {portacode-1.3.25 → portacode-1.3.27}/portacode/cli.py +0 -0
  38. {portacode-1.3.25 → portacode-1.3.27}/portacode/connection/README.md +0 -0
  39. {portacode-1.3.25 → portacode-1.3.27}/portacode/connection/__init__.py +0 -0
  40. {portacode-1.3.25 → portacode-1.3.27}/portacode/connection/client.py +0 -0
  41. {portacode-1.3.25 → portacode-1.3.27}/portacode/connection/handlers/README.md +0 -0
  42. {portacode-1.3.25 → portacode-1.3.27}/portacode/connection/handlers/__init__.py +0 -0
  43. {portacode-1.3.25 → portacode-1.3.27}/portacode/connection/handlers/chunked_content.py +0 -0
  44. {portacode-1.3.25 → portacode-1.3.27}/portacode/connection/handlers/project_aware_file_handlers.py +0 -0
  45. {portacode-1.3.25 → portacode-1.3.27}/portacode/connection/handlers/project_state/README.md +0 -0
  46. {portacode-1.3.25 → portacode-1.3.27}/portacode/connection/handlers/project_state/__init__.py +0 -0
  47. {portacode-1.3.25 → portacode-1.3.27}/portacode/connection/handlers/project_state/file_system_watcher.py +0 -0
  48. {portacode-1.3.25 → portacode-1.3.27}/portacode/connection/handlers/project_state/git_manager.py +0 -0
  49. {portacode-1.3.25 → portacode-1.3.27}/portacode/connection/handlers/project_state/manager.py +0 -0
  50. {portacode-1.3.25 → portacode-1.3.27}/portacode/connection/handlers/project_state/models.py +0 -0
  51. {portacode-1.3.25 → portacode-1.3.27}/portacode/connection/handlers/project_state/utils.py +0 -0
  52. {portacode-1.3.25 → portacode-1.3.27}/portacode/connection/handlers/project_state_handlers.py +0 -0
  53. {portacode-1.3.25 → portacode-1.3.27}/portacode/connection/handlers/session.py +0 -0
  54. {portacode-1.3.25 → portacode-1.3.27}/portacode/connection/handlers/system_handlers.py +0 -0
  55. {portacode-1.3.25 → portacode-1.3.27}/portacode/connection/handlers/tab_factory.py +0 -0
  56. {portacode-1.3.25 → portacode-1.3.27}/portacode/connection/handlers/terminal_handlers.py +0 -0
  57. {portacode-1.3.25 → portacode-1.3.27}/portacode/connection/multiplex.py +0 -0
  58. {portacode-1.3.25 → portacode-1.3.27}/portacode/connection/terminal.py +0 -0
  59. {portacode-1.3.25 → portacode-1.3.27}/portacode/data.py +0 -0
  60. {portacode-1.3.25 → portacode-1.3.27}/portacode/keypair.py +0 -0
  61. {portacode-1.3.25 → portacode-1.3.27}/portacode/logging_categories.py +0 -0
  62. {portacode-1.3.25 → portacode-1.3.27}/portacode/service.py +0 -0
  63. {portacode-1.3.25 → portacode-1.3.27}/portacode.egg-info/dependency_links.txt +0 -0
  64. {portacode-1.3.25 → portacode-1.3.27}/portacode.egg-info/entry_points.txt +0 -0
  65. {portacode-1.3.25 → portacode-1.3.27}/portacode.egg-info/top_level.txt +0 -0
  66. {portacode-1.3.25 → portacode-1.3.27}/pyproject.toml +0 -0
  67. {portacode-1.3.25 → portacode-1.3.27}/restore.sh +0 -0
  68. {portacode-1.3.25 → portacode-1.3.27}/run_tests.py +0 -0
  69. {portacode-1.3.25 → portacode-1.3.27}/setup.cfg +0 -0
  70. {portacode-1.3.25 → portacode-1.3.27}/test.sh +0 -0
  71. {portacode-1.3.25 → portacode-1.3.27}/test_modules/README.md +0 -0
  72. {portacode-1.3.25 → portacode-1.3.27}/test_modules/__init__.py +0 -0
  73. {portacode-1.3.25 → portacode-1.3.27}/test_modules/test_device_online.py +0 -0
  74. {portacode-1.3.25 → portacode-1.3.27}/test_modules/test_file_operations.py +0 -0
  75. {portacode-1.3.25 → portacode-1.3.27}/test_modules/test_git_status_ui.py +0 -0
  76. {portacode-1.3.25 → portacode-1.3.27}/test_modules/test_login_flow.py +0 -0
  77. {portacode-1.3.25 → portacode-1.3.27}/test_modules/test_navigate_testing_folder.py +0 -0
  78. {portacode-1.3.25 → portacode-1.3.27}/test_modules/test_terminal_buffer_performance.py +0 -0
  79. {portacode-1.3.25 → portacode-1.3.27}/test_modules/test_terminal_interaction.py +0 -0
  80. {portacode-1.3.25 → portacode-1.3.27}/test_modules/test_terminal_loading_race_condition.py +0 -0
  81. {portacode-1.3.25 → portacode-1.3.27}/test_modules/test_terminal_start.py +0 -0
  82. {portacode-1.3.25 → portacode-1.3.27}/testing_framework/.env.example +0 -0
  83. {portacode-1.3.25 → portacode-1.3.27}/testing_framework/README.md +0 -0
  84. {portacode-1.3.25 → portacode-1.3.27}/testing_framework/__init__.py +0 -0
  85. {portacode-1.3.25 → portacode-1.3.27}/testing_framework/cli.py +0 -0
  86. {portacode-1.3.25 → portacode-1.3.27}/testing_framework/core/__init__.py +0 -0
  87. {portacode-1.3.25 → portacode-1.3.27}/testing_framework/core/base_test.py +0 -0
  88. {portacode-1.3.25 → portacode-1.3.27}/testing_framework/core/cli_manager.py +0 -0
  89. {portacode-1.3.25 → portacode-1.3.27}/testing_framework/core/hierarchical_runner.py +0 -0
  90. {portacode-1.3.25 → portacode-1.3.27}/testing_framework/core/playwright_manager.py +0 -0
  91. {portacode-1.3.25 → portacode-1.3.27}/testing_framework/core/runner.py +0 -0
  92. {portacode-1.3.25 → portacode-1.3.27}/testing_framework/core/shared_cli_manager.py +0 -0
  93. {portacode-1.3.25 → portacode-1.3.27}/testing_framework/core/test_discovery.py +0 -0
  94. {portacode-1.3.25 → portacode-1.3.27}/testing_framework/requirements.txt +0 -0
@@ -17,7 +17,6 @@
17
17
  "Bash(git -C /home/menas/testing_folder status --porcelain)",
18
18
  "Bash(docker-compose restart:*)"
19
19
  ],
20
- "deny": [],
21
- "defaultMode": "acceptEdits"
20
+ "deny": []
22
21
  }
23
22
  }
@@ -0,0 +1,3 @@
1
+ prune server
2
+ exclude .pypirc
3
+ recursive-include portacode/static *.js *.html
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: portacode
3
- Version: 1.3.25
3
+ Version: 1.3.27
4
4
  Summary: Portacode CLI client and SDK
5
5
  Home-page: https://github.com/portacode/portacode
6
6
  Author: Meena Erian
@@ -23,6 +23,7 @@ Requires-Dist: GitPython>=3.1.45
23
23
  Requires-Dist: watchdog>=3.0
24
24
  Requires-Dist: diff-match-patch>=20230430
25
25
  Requires-Dist: Pygments>=2.14.0
26
+ Requires-Dist: ntplib>=0.4.0
26
27
  Provides-Extra: dev
27
28
  Requires-Dist: black; extra == "dev"
28
29
  Requires-Dist: flake8; extra == "dev"
@@ -43,7 +44,7 @@ Dynamic: summary
43
44
 
44
45
  **An AI-first, mobile-first IDE and admin tool, made with love and passion by software engineers, for software engineers.**
45
46
 
46
- Portacode transforms any computer into a remotely accessible development environment. Access your home lab from your phone, code on your desktop from anywhere, or help a colleague debug their server - all through a beautiful web interface designed for the modern developer.
47
+ Portacode transforms any device with python into a remotely accessible development environment. Access your home lab, server or even embedded system chip from your phone, code on your desktop or your smartphone from anywhere, or help a colleague debug their server - all through a beautiful web interface designed for the modern developer.
47
48
 
48
49
  ## ✨ Why Portacode?
49
50
 
@@ -86,40 +87,9 @@ Once connected, you can:
86
87
 
87
88
  ## 💡 Use Cases
88
89
 
89
- ### Remote Development
90
- ```bash
91
- # Connect your development machine
92
- portacode connect
93
-
94
- # Now code, build, and debug from anywhere - even your phone
95
- ```
96
-
97
- ### Server Administration
98
- ```bash
99
- # For a persistent connection, install system-wide first
100
- sudo pip install portacode --system
101
-
102
- # Then install as a service
103
- sudo portacode service install
104
-
105
- # Your server is now accessible 24/7 from the web dashboard
106
- ```
107
-
108
- ### Mobile Development
109
- ```bash
110
- # Connect your desktop/laptop
111
- portacode connect
112
-
113
- # Code on-the-go from your mobile device with a full IDE experience
114
- ```
115
-
116
- ### Team Collaboration
117
- ```bash
118
- # Connect shared development environments
119
- portacode connect
120
-
121
- # Enable team members to access shared resources securely
122
- ```
90
+ - **Remote Development**: Code, build, and debug from anywhere - even your phone
91
+ - **Server Administration**: 24/7 server access with persistent service installation
92
+ - **Mobile Development**: Full IDE experience on mobile devices
123
93
 
124
94
  ## 🔧 Essential Commands
125
95
 
@@ -140,19 +110,21 @@ portacode --help
140
110
 
141
111
  ### Service Management
142
112
  ```bash
143
- # For system services, install package system-wide first
113
+ # First, authenticate your device
114
+ portacode connect
115
+
116
+ # For system services, install package system-wide
144
117
  sudo pip install portacode --system
145
118
 
146
119
  # Install persistent service (auto-start on boot)
147
120
  sudo portacode service install
148
121
 
149
- # Check service status
122
+ # Check service status (use -v for verbose debugging)
150
123
  sudo portacode service status
124
+ sudo portacode service status -v
151
125
 
152
- # Stop the service
126
+ # Stop/remove the service
153
127
  sudo portacode service stop
154
-
155
- # Remove the service
156
128
  sudo portacode service uninstall
157
129
  ```
158
130
 
@@ -194,11 +166,17 @@ sudo portacode service status --verbose
194
166
 
195
167
  ### Service Installation Issues
196
168
  ```bash
169
+ # First authenticate your device
170
+ portacode connect
171
+
197
172
  # If service commands fail, ensure system-wide installation
198
173
  sudo pip install portacode --system
199
174
 
200
175
  # Then try service installation again
201
176
  sudo portacode service install
177
+
178
+ # Use verbose status to debug connection issues
179
+ sudo portacode service status -v
202
180
  ```
203
181
 
204
182
  ### Clipboard Issues (Linux)
@@ -2,7 +2,7 @@
2
2
 
3
3
  **An AI-first, mobile-first IDE and admin tool, made with love and passion by software engineers, for software engineers.**
4
4
 
5
- Portacode transforms any computer into a remotely accessible development environment. Access your home lab from your phone, code on your desktop from anywhere, or help a colleague debug their server - all through a beautiful web interface designed for the modern developer.
5
+ Portacode transforms any device with python into a remotely accessible development environment. Access your home lab, server or even embedded system chip from your phone, code on your desktop or your smartphone from anywhere, or help a colleague debug their server - all through a beautiful web interface designed for the modern developer.
6
6
 
7
7
  ## ✨ Why Portacode?
8
8
 
@@ -45,40 +45,9 @@ Once connected, you can:
45
45
 
46
46
  ## 💡 Use Cases
47
47
 
48
- ### Remote Development
49
- ```bash
50
- # Connect your development machine
51
- portacode connect
52
-
53
- # Now code, build, and debug from anywhere - even your phone
54
- ```
55
-
56
- ### Server Administration
57
- ```bash
58
- # For a persistent connection, install system-wide first
59
- sudo pip install portacode --system
60
-
61
- # Then install as a service
62
- sudo portacode service install
63
-
64
- # Your server is now accessible 24/7 from the web dashboard
65
- ```
66
-
67
- ### Mobile Development
68
- ```bash
69
- # Connect your desktop/laptop
70
- portacode connect
71
-
72
- # Code on-the-go from your mobile device with a full IDE experience
73
- ```
74
-
75
- ### Team Collaboration
76
- ```bash
77
- # Connect shared development environments
78
- portacode connect
79
-
80
- # Enable team members to access shared resources securely
81
- ```
48
+ - **Remote Development**: Code, build, and debug from anywhere - even your phone
49
+ - **Server Administration**: 24/7 server access with persistent service installation
50
+ - **Mobile Development**: Full IDE experience on mobile devices
82
51
 
83
52
  ## 🔧 Essential Commands
84
53
 
@@ -99,19 +68,21 @@ portacode --help
99
68
 
100
69
  ### Service Management
101
70
  ```bash
102
- # For system services, install package system-wide first
71
+ # First, authenticate your device
72
+ portacode connect
73
+
74
+ # For system services, install package system-wide
103
75
  sudo pip install portacode --system
104
76
 
105
77
  # Install persistent service (auto-start on boot)
106
78
  sudo portacode service install
107
79
 
108
- # Check service status
80
+ # Check service status (use -v for verbose debugging)
109
81
  sudo portacode service status
82
+ sudo portacode service status -v
110
83
 
111
- # Stop the service
84
+ # Stop/remove the service
112
85
  sudo portacode service stop
113
-
114
- # Remove the service
115
86
  sudo portacode service uninstall
116
87
  ```
117
88
 
@@ -153,11 +124,17 @@ sudo portacode service status --verbose
153
124
 
154
125
  ### Service Installation Issues
155
126
  ```bash
127
+ # First authenticate your device
128
+ portacode connect
129
+
156
130
  # If service commands fail, ensure system-wide installation
157
131
  sudo pip install portacode --system
158
132
 
159
133
  # Then try service installation again
160
134
  sudo portacode service install
135
+
136
+ # Use verbose status to debug connection issues
137
+ sudo portacode service status -v
161
138
  ```
162
139
 
163
140
  ### Clipboard Issues (Linux)
@@ -21,11 +21,9 @@ services:
21
21
  dockerfile: Dockerfile
22
22
  container_name: portacode-django
23
23
  restart: unless-stopped
24
- command: ["bash", "-c", "python manage.py migrate && python manage.py collectstatic --noinput && python manage.py runserver 0.0.0.0:8001"]
24
+ command: ["bash", "-c", "python manage.py migrate && python manage.py collectstatic --noinput && daphne portacode_django.asgi:application -b 0.0.0.0 -p 8001"]
25
25
  env_file:
26
26
  - main.env
27
- environment:
28
- - DJANGO_DEBUG=${DJANGO_DEBUG:-false}
29
27
  depends_on:
30
28
  db:
31
29
  condition: service_healthy
@@ -28,7 +28,7 @@ version_tuple: VERSION_TUPLE
28
28
  commit_id: COMMIT_ID
29
29
  __commit_id__: COMMIT_ID
30
30
 
31
- __version__ = version = '1.3.25'
32
- __version_tuple__ = version_tuple = (1, 3, 25)
31
+ __version__ = version = '1.3.27'
32
+ __version_tuple__ = version_tuple = (1, 3, 27)
33
33
 
34
34
  __commit_id__ = commit_id = None
@@ -1,10 +1,38 @@
1
1
  # WebSocket Communication Protocol
2
2
 
3
- This document outlines the WebSocket communication protocol between the Portacode server and the connected client devices.
3
+ This document outlines the WebSocket communication protocol used in Portacode. The protocol involves three main participants: client sessions, the Portacode server, and devices.
4
+
5
+ ## Architecture Overview
6
+
7
+ ```
8
+ ┌─────────────┐ ┌──────────────────┐ ┌─────────────────────────┐
9
+ │ Client │ │ Portacode │ │ Device │
10
+ │ Session │◄────────►│ Server │◄────────►│ (Portacode CLI or │
11
+ │ │ │ │ │ Python package) │
12
+ └─────────────┘ └──────────────────┘ └─────────────────────────┘
13
+ │ │ │
14
+ │ │ │
15
+ Client-Side Acts as middleman Device-Side
16
+ Protocol - Routes messages Protocol
17
+ - Manages sessions
18
+ ```
19
+
20
+ The Portacode server acts as a **routing middleman** between client sessions and devices. It manages routing fields that are included in messages to specify routing destinations but are removed or transformed before reaching the final recipient:
21
+
22
+ **Routing Fields Behavior:**
23
+
24
+ - **`device_id`** (Client → Server): Client includes this to specify which device to route to. Server uses it for routing, then **removes it** before forwarding to the device (the device knows the message is for them). Server **adds it** when routing device responses back to clients (so clients know which device the message came from).
25
+
26
+ - **`client_sessions`** (Device → Server): Device includes this to specify which client session(s) to route to. Server uses it for routing, then **removes it** before forwarding to clients (clients just receive the message without seeing routing metadata).
27
+
28
+ - **`source_client_session`** (Server → Device): Server **adds this** when forwarding client commands to devices (so device knows which client sent the command and can target responses back). Clients never include this field.
29
+
30
+ This document describes the complete protocol for communicating with devices through the server, guiding app developers on how to get their client sessions to communicate with devices.
4
31
 
5
32
  ## Table of Contents
6
33
 
7
- - [Raw Message Format](#raw-message-format)
34
+ - [Raw Message Format On Device Side](#raw-message-format-on-device-side)
35
+ - [Raw Message Format On Client Side](#raw-message-format-on-client-side)
8
36
  - [Actions](#actions)
9
37
  - [Terminal Actions](#terminal-actions)
10
38
  - [`terminal_start`](#terminal_start)
@@ -82,11 +110,11 @@ This document outlines the WebSocket communication protocol between the Portacod
82
110
  - [`device_status`](#device_status)
83
111
  - [`devices`](#devices)
84
112
 
85
- ## Raw Message Format
113
+ ## Raw Message Format On Device Side
86
114
 
87
- All communication over the WebSocket is managed by a [multiplexer](./multiplex.py) that wraps every message in a JSON object with a `channel` and a `payload`. This allows for multiple virtual communication channels over a single connection.
115
+ Communication between the server and devices uses a [multiplexer](./multiplex.py) that wraps every message in a JSON object with a `channel` and a `payload`. This allows for multiple virtual communication channels over a single WebSocket connection.
88
116
 
89
- **Raw Message Structure:**
117
+ **Device-Side Message Structure:**
90
118
 
91
119
  ```json
92
120
  {
@@ -97,9 +125,99 @@ All communication over the WebSocket is managed by a [multiplexer](./multiplex.p
97
125
  }
98
126
  ```
99
127
 
100
- * `channel` (string|integer, mandatory): Identifies the virtual channel the message is for. When sending control commands to the device, they should be sent to channel 0 and when the device responsed to such control commands or sends system events, they will also be send on the zero channel. When a terminal session is created in the device, it is assigned a uuid, the uuid becomes the channel for communicating to that specific terminal.
128
+ **Field Descriptions:**
129
+
130
+ * `channel` (string|integer, mandatory): Identifies the virtual channel the message is for. When sending control commands to the device, they should be sent to channel 0 and when the device responds to such control commands or sends system events, they will also be sent on the zero channel. When a terminal session is created in the device, it is assigned a uuid, the uuid becomes the channel for communicating to that specific terminal.
101
131
  * `payload` (object, mandatory): The content of the message, which will be either an [Action](#actions) or an [Event](#events) object.
102
132
 
133
+ **Channel Types:**
134
+ - **Channel 0** (control channel): Used for system commands, terminal management, file operations, and project state management
135
+ - **Channel UUID** (terminal channel): Used for terminal I/O to a specific terminal session
136
+
137
+ ---
138
+
139
+ ## Raw Message Format On Client Side
140
+
141
+ Client sessions communicate with the server using a unified message format with the same field names as the device protocol, plus routing information.
142
+
143
+ **Client-Side Message Structure (Client → Server):**
144
+
145
+ ```json
146
+ {
147
+ "device_id": <number>,
148
+ "channel": <number|string>,
149
+ "payload": {
150
+ "cmd": "<command_name>",
151
+ ...command-specific fields
152
+ }
153
+ }
154
+ ```
155
+
156
+ **Field Descriptions:**
157
+
158
+ * `device_id` (number, mandatory): Routing field - specifies which device to send the message to. The server validates that the client has access to this device before forwarding.
159
+ * `channel` (number|string, mandatory): Same as device protocol - the target channel (0 for control, UUID for terminal). Uses the same field name for consistency.
160
+ * `payload` (object, mandatory): Same as device protocol - the command payload. Uses the same field name for consistency.
161
+
162
+ **Server Transformation (Client → Device):**
163
+
164
+ When the server receives a client message, it:
165
+ 1. Validates client has access to the specified `device_id`
166
+ 2. **Removes** `device_id` from the message (device doesn't need to be told "this is for you")
167
+ 3. **Adds** `source_client_session` to the payload (so device knows which client to respond to)
168
+ 4. Forwards to device: `{channel, payload: {...payload, source_client_session}}`
169
+
170
+ **Server Transformation (Device → Client):**
171
+
172
+ When the server receives a device response, it:
173
+ 1. **Adds** `device_id` to the message (so client knows which device it came from, based on authenticated device connection)
174
+ 2. **Removes** `client_sessions` routing metadata (clients don't need to see routing info)
175
+ 3. Routes to appropriate client session(s)
176
+
177
+ **Server Response Format (Server → Client):**
178
+
179
+ ```json
180
+ {
181
+ "event": "<event_name>",
182
+ "device_id": <number>,
183
+ ...event-specific fields
184
+ }
185
+ ```
186
+
187
+ **Field Descriptions:**
188
+
189
+ * `event` (string, mandatory): The name of the event being sent.
190
+ * `device_id` (number, mandatory): Authenticated field - identifies which device the event came from (added by server based on authenticated device connection).
191
+ * Additional fields depend on the specific event type.
192
+
193
+ **Example Client Message:**
194
+ ```json
195
+ {
196
+ "device_id": 42,
197
+ "channel": 0,
198
+ "payload": {
199
+ "cmd": "terminal_start",
200
+ "shell": "bash",
201
+ "cwd": "/home/user/project"
202
+ }
203
+ }
204
+ ```
205
+
206
+ **Example Server Response:**
207
+ ```json
208
+ {
209
+ "event": "terminal_started",
210
+ "device_id": 42,
211
+ "terminal_id": "uuid-1234-5678",
212
+ "channel": "uuid-1234-5678",
213
+ "pid": 12345
214
+ }
215
+ ```
216
+
217
+ **Note:** The server acts as a translator between the client-side and device-side protocols:
218
+ - When a client sends a command, the server transforms it from the client format to the device format
219
+ - When a device sends an event, the server adds the `device_id` and routes it to the appropriate client sessions
220
+
103
221
  ---
104
222
 
105
223
  ## Actions
@@ -110,18 +228,18 @@ Actions are messages sent from the server to the device, placed within the `payl
110
228
 
111
229
  ```json
112
230
  {
113
- "command": "<command_name>",
114
- "payload": {
115
- "arg1": "value1",
116
- "...": "..."
117
- },
231
+ "cmd": "<command_name>",
232
+ "arg1": "value1",
233
+ "arg2": "value2",
118
234
  "source_client_session": "channel.abc123"
119
235
  }
120
236
  ```
121
237
 
122
- * `command` (string, mandatory): The name of the action to be executed (e.g., `terminal_start`).
123
- * `payload` (object, mandatory): An object containing the specific arguments for the action.
238
+ **Field Descriptions:**
239
+
240
+ * `cmd` (string, mandatory): The name of the action to be executed (e.g., `terminal_start`, `file_read`, `system_info`).
124
241
  * `source_client_session` (string, mandatory): The channel name of the client session that originated this command. This field is automatically added by the server and allows devices to identify which specific client sent the command.
242
+ * Additional fields depend on the specific command (see individual command documentation below).
125
243
 
126
244
  **Note**: Actions do not require targeting information - responses are automatically routed using the client session management system.
127
245
 
@@ -4,6 +4,7 @@ import asyncio
4
4
  import logging
5
5
  from abc import ABC, abstractmethod
6
6
  from typing import Any, Dict, Optional, TYPE_CHECKING
7
+ from portacode.utils.ntp_clock import ntp_clock
7
8
 
8
9
  if TYPE_CHECKING:
9
10
  from ..multiplex import Channel
@@ -42,35 +43,45 @@ class BaseHandler(ABC):
42
43
 
43
44
  async def send_response(self, payload: Dict[str, Any], reply_channel: Optional[str] = None, project_id: str = None) -> None:
44
45
  """Send a response back to the gateway with client session awareness.
45
-
46
+
46
47
  Args:
47
48
  payload: Response payload
48
49
  reply_channel: Optional reply channel for backward compatibility
49
50
  project_id: Optional project filter for targeting specific sessions
50
51
  """
52
+ # Add device_send timestamp if trace present
53
+ if "trace" in payload and "request_id" in payload:
54
+ device_send_time = ntp_clock.now_ms()
55
+ if device_send_time is not None:
56
+ payload["trace"]["device_send"] = device_send_time
57
+ # Update ping to show total time from client_send
58
+ if "client_send" in payload["trace"]:
59
+ payload["trace"]["ping"] = device_send_time - payload["trace"]["client_send"]
60
+ logger.info(f"📤 Device sending traced response: {payload['request_id']}")
61
+
51
62
  # Get client session manager from context
52
63
  client_session_manager = self.context.get("client_session_manager")
53
-
64
+
54
65
  if client_session_manager and client_session_manager.has_interested_clients():
55
66
  # Get target sessions
56
67
  target_sessions = client_session_manager.get_target_sessions(project_id)
57
68
  if not target_sessions:
58
69
  logger.debug("handler: No target sessions found, skipping response send")
59
70
  return
60
-
71
+
61
72
  # Add session targeting information
62
73
  enhanced_payload = dict(payload)
63
74
  enhanced_payload["client_sessions"] = target_sessions
64
-
75
+
65
76
  # Add backward compatibility reply_channel (first session if not provided)
66
77
  if not reply_channel:
67
78
  reply_channel = client_session_manager.get_reply_channel_for_compatibility()
68
79
  if reply_channel:
69
80
  enhanced_payload["reply_channel"] = reply_channel
70
-
71
- logger.debug("handler: Sending response to %d client sessions: %s",
81
+
82
+ logger.debug("handler: Sending response to %d client sessions: %s",
72
83
  len(target_sessions), target_sessions)
73
-
84
+
74
85
  await self.control_channel.send(enhanced_payload)
75
86
  else:
76
87
  # Fallback to original behavior if no client session manager or no clients
@@ -107,18 +118,43 @@ class AsyncHandler(BaseHandler):
107
118
 
108
119
  async def handle(self, message: Dict[str, Any], reply_channel: Optional[str] = None) -> None:
109
120
  """Handle the command by executing it and sending the response."""
110
- logger.info("handler: Processing command %s with reply_channel=%s",
121
+ logger.info("handler: Processing command %s with reply_channel=%s",
111
122
  self.command_name, reply_channel)
112
-
123
+
124
+ # Add handler_dispatch timestamp if trace present
125
+ if "trace" in message and "request_id" in message:
126
+ handler_dispatch_time = ntp_clock.now_ms()
127
+ if handler_dispatch_time is not None:
128
+ message["trace"]["handler_dispatch"] = handler_dispatch_time
129
+ # Update ping to show total time from client_send
130
+ if "client_send" in message["trace"]:
131
+ message["trace"]["ping"] = handler_dispatch_time - message["trace"]["client_send"]
132
+ logger.info(f"🔧 Handler dispatching: {message['request_id']} ({self.command_name})")
133
+
113
134
  try:
114
135
  response = await self.execute(message)
115
136
  logger.info("handler: Command %s executed successfully", self.command_name)
116
-
137
+
117
138
  # Handle cases where execute() sends responses directly and returns None
118
139
  if response is not None:
140
+ # Automatically copy request_id if present in the incoming message
141
+ if "request_id" in message and "request_id" not in response:
142
+ response["request_id"] = message["request_id"]
143
+
144
+ # Pass through trace from request to response (add to existing trace, don't create new one)
145
+ if "trace" in message and "request_id" in message:
146
+ response["trace"] = dict(message["trace"])
147
+ handler_complete_time = ntp_clock.now_ms()
148
+ if handler_complete_time is not None:
149
+ response["trace"]["handler_complete"] = handler_complete_time
150
+ # Update ping to show total time from client_send
151
+ if "client_send" in response["trace"]:
152
+ response["trace"]["ping"] = handler_complete_time - response["trace"]["client_send"]
153
+ logger.info(f"✅ Handler completed: {message['request_id']} ({self.command_name})")
154
+
119
155
  # Extract project_id from response for session targeting
120
156
  project_id = response.get("project_id")
121
- logger.info("handler: %s response project_id=%s, response=%s",
157
+ logger.info("handler: %s response project_id=%s, response=%s",
122
158
  self.command_name, project_id, response)
123
159
  await self.send_response(response, reply_channel, project_id)
124
160
  else:
@@ -147,10 +183,32 @@ class SyncHandler(BaseHandler):
147
183
 
148
184
  async def handle(self, message: Dict[str, Any], reply_channel: Optional[str] = None) -> None:
149
185
  """Handle the command by executing it in an executor and sending the response."""
186
+ # Add handler_dispatch timestamp if trace present
187
+ if "trace" in message and "request_id" in message:
188
+ handler_dispatch_time = ntp_clock.now_ms()
189
+ if handler_dispatch_time is not None:
190
+ message["trace"]["handler_dispatch"] = handler_dispatch_time
191
+ # Update ping to show total time from client_send
192
+ if "client_send" in message["trace"]:
193
+ message["trace"]["ping"] = handler_dispatch_time - message["trace"]["client_send"]
194
+ logger.info(f"🔧 Handler dispatching: {message['request_id']} ({self.command_name})")
195
+
150
196
  try:
151
197
  loop = asyncio.get_running_loop()
152
198
  response = await loop.run_in_executor(None, self.execute, message)
153
-
199
+
200
+ # Automatically copy request_id if present in the incoming message
201
+ if "request_id" in message and "request_id" not in response:
202
+ response["request_id"] = message["request_id"]
203
+
204
+ # Pass through trace from request to response (add to existing trace, don't create new one)
205
+ if "trace" in message and "request_id" in message:
206
+ response["trace"] = dict(message["trace"])
207
+ handler_complete_time = ntp_clock.now_ms()
208
+ if handler_complete_time is not None:
209
+ response["trace"]["handler_complete"] = handler_complete_time
210
+ logger.info(f"✅ Handler completed: {message['request_id']} ({self.command_name})")
211
+
154
212
  # Extract project_id from response for session targeting
155
213
  project_id = response.get("project_id")
156
214
  await self.send_response(response, reply_channel, project_id)
@@ -382,22 +382,18 @@ class ContentRequestHandler(AsyncHandler):
382
382
  async def execute(self, message: Dict[str, Any]) -> None:
383
383
  """Return content by hash if available, chunked for large content."""
384
384
  content_hash = message.get("content_hash")
385
- request_id = message.get("request_id")
386
385
  source_client_session = message.get("source_client_session")
387
-
386
+
388
387
  if not content_hash:
389
388
  raise ValueError("content_hash parameter is required")
390
- if not request_id:
391
- raise ValueError("request_id parameter is required")
392
-
389
+
393
390
  # Check if content is in cache
394
391
  content = _content_cache.get(content_hash)
395
-
392
+
396
393
  if content is not None:
397
- # Create base response
394
+ # Create base response (request_id will be added automatically by base class)
398
395
  base_response = {
399
396
  "event": "content_response",
400
- "request_id": request_id,
401
397
  "content_hash": content_hash,
402
398
  "success": True,
403
399
  }
@@ -411,10 +407,9 @@ class ContentRequestHandler(AsyncHandler):
411
407
 
412
408
  logger.info(f"Sent content response in {len(responses)} chunk(s) for hash: {content_hash[:16]}...")
413
409
  else:
414
- # Content not found in cache
410
+ # Content not found in cache (request_id will be added automatically by base class)
415
411
  response = {
416
412
  "event": "content_response",
417
- "request_id": request_id,
418
413
  "content_hash": content_hash,
419
414
  "content": None,
420
415
  "success": False,
@@ -683,9 +683,8 @@ class ProjectStateDiffContentHandler(AsyncHandler):
683
683
  from_hash = message.get("from_hash")
684
684
  to_hash = message.get("to_hash")
685
685
  content_type = message.get("content_type") # 'original', 'modified', 'html_diff'
686
- request_id = message.get("request_id")
687
686
  source_client_session = message.get("source_client_session")
688
-
687
+
689
688
  # Validate required fields
690
689
  if not server_project_id:
691
690
  raise ValueError("project_id is required")
@@ -697,8 +696,6 @@ class ProjectStateDiffContentHandler(AsyncHandler):
697
696
  raise ValueError("to_ref is required")
698
697
  if not content_type:
699
698
  raise ValueError("content_type is required")
700
- if not request_id:
701
- raise ValueError("request_id is required")
702
699
  if not source_client_session:
703
700
  raise ValueError("source_client_session is required")
704
701
 
@@ -816,9 +813,12 @@ class ProjectStateDiffContentHandler(AsyncHandler):
816
813
  "from_ref": from_ref,
817
814
  "to_ref": to_ref,
818
815
  "content_type": content_type,
819
- "request_id": request_id,
820
816
  "success": success
821
817
  }
818
+
819
+ # Add request_id if present in original message
820
+ if "request_id" in message:
821
+ base_response["request_id"] = message["request_id"]
822
822
 
823
823
  if from_hash:
824
824
  base_response["from_hash"] = from_hash
@@ -850,9 +850,12 @@ class ProjectStateDiffContentHandler(AsyncHandler):
850
850
  "from_ref": from_ref,
851
851
  "to_ref": to_ref,
852
852
  "content_type": content_type,
853
- "request_id": request_id,
854
853
  "success": False,
855
854
  "error": str(e),
856
855
  "chunked": False
857
856
  }
857
+
858
+ # Add request_id if present in original message
859
+ if "request_id" in message:
860
+ error_response["request_id"] = message["request_id"]
858
861
  await self.send_response(error_response, project_id=server_project_id)