Skip to content

Commit 4e6ca4e

Browse files
committed
feat(reply-assistant): add the PySide6 desktop UI, controller and lra commands (v0.4.0)
VISION §15-17: one window with status strip, Capture | Message | Draft panes and an action bar, all state visible without modal dialogs. A Qt controller runs work in threads and posts results back to the GUI thread; the workflow drops superseded results. Adds the ROI editor, Keyboard Shortcuts and System Status pages, Copy Draft fallback, always-on-top option, settings persistence (ROI, single-use restore token) and the commands lra gui, selftest, screenshot, test-window. Error texts name the failing backends.
1 parent 0c5f1b5 commit 4e6ca4e

22 files changed

Lines changed: 2108 additions & 10 deletions

‎linkedinMessagingReplyApp/localPipeline.sh‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ wheel_smoke() {
5858
uv venv -q -p 3.14 "$tmp/venv" &&
5959
VIRTUAL_ENV="$tmp/venv" uv pip install -q dist/*.whl &&
6060
"$tmp/venv/bin/lra" --version &&
61+
QT_QPA_PLATFORM=offscreen "$tmp/venv/bin/lra" --config-dir "$tmp/cfg" selftest &&
6162
"$tmp/venv/bin/python" -c "from pathlib import Path; from linkedin_reply_assistant.config.loader import load_config as f; c = f(Path('$tmp/none')); print(len(c.prompts), 'prompts shipped')"
6263
local rc=$?
6364
rm -rf "$tmp"

‎linkedinMessagingReplyApp/plan.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,7 @@ Two sibling rules are bent, not broken (`AGENTS.md`, B1 and B2). Next step: gate
112112
| 0.2.5 | feat(reply-assistant): add classifier, prompt fences and reply generator | `./localPipeline.sh` (9 stages) | green, coverage 99% |
113113
| 0.2.6 | feat(reply-assistant): add workflow state machine and the Capture & Draft pipeline | `./localPipeline.sh` (9 stages); live: 14/14 reply fixtures on local qwen3.5:4b | green, coverage 99% |
114114
| 0.3.0 | feat(reply-assistant): add browser extension, native host relay and verified insertion (gate 5) | `./localPipeline.sh` (10 stages); e2e: 8/8 (insert, no Send, no key events, mismatch blocked, no composer, non-LinkedIn tab, zero LinkedIn requests) | green, coverage 99% |
115+
| 0.4.0 | feat(reply-assistant): add the PySide6 desktop UI, controller and lra commands | `./localPipeline.sh` (10 stages); lra selftest OK in a clean wheel venv; UI tests 20/20 | green, coverage 98% |
115116

116117
## Results
117118

‎linkedinMessagingReplyApp/pyproject.toml‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,9 @@ lra-native-host = "linkedin_reply_assistant.browser_bridge.native_host:main"
4040
where = ["src"]
4141

4242
[tool.setuptools.package-data]
43-
linkedin_reply_assistant = ["defaults/*.yaml", "defaults/prompts/*.md"]
43+
linkedin_reply_assistant = [
44+
"defaults/*.yaml", "defaults/*.png", "defaults/prompts/*.md", "defaults/samples/*.yaml"
45+
]
4446

4547
[tool.setuptools.dynamic]
4648
version = { attr = "linkedin_reply_assistant.version.__version__" }
@@ -82,9 +84,14 @@ files = ["src", "tests"]
8284

8385
[[tool.mypy.overrides]]
8486
# mypy narrows `flow.state` across method calls that change it.
85-
module = ["tests.unit.state.test_workflow"]
87+
module = ["tests.unit.state.test_workflow", "tests.unit.ui.test_ui"]
8688
disable_error_code = ["comparison-overlap"]
8789

90+
[[tool.mypy.overrides]]
91+
# pytest-qt's mouse helpers have no type hints.
92+
module = ["tests.unit.ui.test_ui"]
93+
disallow_untyped_calls = false
94+
8895
[[tool.mypy.overrides]]
8996
# dbus-fast reads D-Bus signatures from string annotations; mypy cannot type them.
9097
module = ["tests.integration.fake_portal"]
Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
# Copyright (C) 2026 Marcel Petrick <mail@marcelpetrick.it>
2+
# SPDX-License-Identifier: GPL-3.0-or-later
3+
"""Wire the services together and run the desktop application."""
4+
5+
import contextlib
6+
import sys
7+
from collections.abc import Callable
8+
from pathlib import Path
9+
10+
from linkedin_reply_assistant.backends.demo import DemoBackend
11+
from linkedin_reply_assistant.backends.factory import build_manager
12+
from linkedin_reply_assistant.backends.manager import BackendManager
13+
from linkedin_reply_assistant.browser_bridge.inserter import Inserter
14+
from linkedin_reply_assistant.browser_bridge.protocol import socket_path
15+
from linkedin_reply_assistant.browser_bridge.server import BridgeServer
16+
from linkedin_reply_assistant.capture.portal_source import PortalCaptureSource
17+
from linkedin_reply_assistant.capture.source import CaptureSource, ImageFileSource
18+
from linkedin_reply_assistant.config.loader import Config, user_config_dir
19+
from linkedin_reply_assistant.diagnostics.preflight import run_preflight
20+
from linkedin_reply_assistant.events import EventLog, setup_logging
21+
from linkedin_reply_assistant.extraction.ocr import TesseractExtractor
22+
from linkedin_reply_assistant.extraction.vision import build_extractor
23+
from linkedin_reply_assistant.paths import user_state_dir
24+
from linkedin_reply_assistant.pipeline import Pipeline
25+
from linkedin_reply_assistant.portal.runner import AsyncRunner
26+
from linkedin_reply_assistant.reply_engine.generator import ReplyGenerator
27+
from linkedin_reply_assistant.shortcuts.base import DisabledShortcuts, ShortcutService
28+
from linkedin_reply_assistant.shortcuts.portal_global_shortcuts import PortalGlobalShortcuts
29+
from linkedin_reply_assistant.state.settings import load_settings, settings_path
30+
from linkedin_reply_assistant.ui.controller import Controller, Services, SourceSelector
31+
32+
33+
def make_manager(config: Config, demo: bool) -> BackendManager:
34+
if demo:
35+
return BackendManager([DemoBackend()], config.backends.health_cache_seconds)
36+
return build_manager(config.backends)
37+
38+
39+
def make_pipeline(config: Config, manager: BackendManager) -> Pipeline:
40+
ocr = TesseractExtractor(config.app.extraction.ocr_languages)
41+
extractor = build_extractor(config.app.extraction.mode, ocr, manager)
42+
events = EventLog(config.app.log_message_text)
43+
return Pipeline(
44+
config,
45+
extractor,
46+
ReplyGenerator(config, manager),
47+
events,
48+
user_state_dir() / "debug_captures",
49+
)
50+
51+
52+
def image_selector(path: Path) -> SourceSelector:
53+
def select(restore_token: str | None) -> tuple[CaptureSource, str | None]:
54+
return ImageFileSource(path), None
55+
56+
return select
57+
58+
59+
def portal_selector(runner: AsyncRunner) -> SourceSelector:
60+
def select(restore_token: str | None) -> tuple[CaptureSource, str | None]:
61+
source = PortalCaptureSource(runner)
62+
return source, source.select(restore_token)
63+
64+
return select
65+
66+
67+
def build_services(
68+
config: Config,
69+
config_dir: Path | None,
70+
demo: bool = False,
71+
image: Path | None = None,
72+
bridge: BridgeServer | None = None,
73+
shortcuts: ShortcutService | None = None,
74+
runner_factory: Callable[[], AsyncRunner] = AsyncRunner,
75+
) -> Services:
76+
manager = make_manager(config, demo)
77+
pipeline = make_pipeline(config, manager)
78+
runner = runner_factory()
79+
if bridge is None:
80+
bridge = BridgeServer(socket_path())
81+
with contextlib.suppress(OSError): # no insertion then; Copy Draft still works (§21.6)
82+
bridge.start()
83+
if shortcuts is None:
84+
shortcuts = DisabledShortcuts() if image is not None else PortalGlobalShortcuts(runner)
85+
selector = image_selector(image) if image is not None else portal_selector(runner)
86+
active_bridge = bridge
87+
return Services(
88+
config=config,
89+
manager=manager,
90+
pipeline=pipeline,
91+
select_source=selector,
92+
shortcuts=shortcuts,
93+
inserter=Inserter(active_bridge),
94+
bridge_connected=lambda: active_bridge.connected,
95+
preflight=lambda: run_preflight(manager, bridge_status=active_bridge.status),
96+
settings_path=settings_path(config_dir or user_config_dir()),
97+
debug_dir=user_state_dir() / "debug_captures",
98+
events=pipeline.events,
99+
)
100+
101+
102+
def run_gui(config: Config, config_dir: Path | None, demo: bool, image: Path | None) -> int:
103+
from PySide6.QtWidgets import QApplication
104+
105+
from linkedin_reply_assistant.ui.main_window import MainWindow
106+
107+
setup_logging()
108+
app = QApplication.instance() or QApplication(sys.argv)
109+
QApplication.setApplicationName("LinkedIn Reply Assistant")
110+
QApplication.setDesktopFileName("io.github.marcelpetrick.LinkedInReplyAssistant")
111+
services = build_services(config, config_dir, demo, image)
112+
settings = load_settings(services.settings_path)
113+
controller = Controller(services, settings)
114+
window = MainWindow(controller)
115+
window.show()
116+
controller.start()
117+
if image is not None:
118+
controller.select_source()
119+
return int(app.exec())

‎linkedinMessagingReplyApp/src/linkedin_reply_assistant/cli.py‎

Lines changed: 154 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,29 @@
33
"""Command line entry point `lra`."""
44

55
import argparse
6+
import os
67
import sys
8+
import time
79
from collections.abc import Sequence
10+
from dataclasses import replace
11+
from importlib import resources
812
from pathlib import Path
913

1014
from linkedin_reply_assistant.backends.factory import build_manager
11-
from linkedin_reply_assistant.config.loader import ConfigError, load_config
15+
from linkedin_reply_assistant.cancel import CancelToken
16+
from linkedin_reply_assistant.capture.roi import Roi
17+
from linkedin_reply_assistant.capture.source import ImageFileSource
18+
from linkedin_reply_assistant.config.loader import Config, ConfigError, load_config
1219
from linkedin_reply_assistant.diagnostics.preflight import format_report, run_preflight
1320
from linkedin_reply_assistant.version import __version__
1421

22+
# The conversation panel of the bundled self-test image (a Capture Test Window rendering).
23+
SELFTEST_ROI = Roi(0.27, 0.0, 0.73, 0.84)
24+
25+
26+
def defaults_file(name: str) -> Path:
27+
return Path(str(resources.files("linkedin_reply_assistant") / "defaults" / name))
28+
1529

1630
def build_parser() -> argparse.ArgumentParser:
1731
parser = argparse.ArgumentParser(
@@ -23,25 +37,159 @@ def build_parser() -> argparse.ArgumentParser:
2337
"--config-dir", type=Path, help="override ~/.config/linkedin-reply-assistant"
2438
)
2539
commands = parser.add_subparsers(dest="command")
40+
gui = commands.add_parser("gui", help="start the desktop application")
41+
gui.add_argument("--demo", action="store_true", help="offline demo backend instead of Ollama")
42+
gui.add_argument("--image", type=Path, help="capture from an image file instead of the portal")
2643
commands.add_parser("preflight", help="report what this desktop and the AI backends support")
44+
selftest = commands.add_parser("selftest", help="run the whole pipeline on a bundled image")
45+
selftest.add_argument("--live", action="store_true", help="use the configured Ollama backends")
46+
window = commands.add_parser("test-window", help="show the deterministic Capture Test Window")
47+
window.add_argument("--sample", default="friendly_connection_01")
48+
window.add_argument("--theme", choices=["light", "dark"], default="light")
49+
window.add_argument("--zoom", type=float, default=1.0)
50+
shot = commands.add_parser("screenshot", help="render the real main window to a PNG (demo)")
51+
shot.add_argument("output", type=Path)
2752
return parser
2853

2954

30-
def cmd_preflight(config_dir: Path | None) -> int:
31-
config = load_config(config_dir)
55+
def cmd_preflight(config: Config) -> int:
3256
checks = run_preflight(build_manager(config.backends))
3357
print(format_report(checks))
3458
return 1 if any(c.status == "fail" for c in checks) else 0
3559

3660

61+
def ocr_only(config: Config) -> Config:
62+
"""The demo backend has no vision model, so offline runs extract with OCR."""
63+
extraction = replace(config.app.extraction, mode="ocr")
64+
return replace(config, app=replace(config.app, extraction=extraction))
65+
66+
67+
def cmd_selftest(config: Config, live: bool) -> int:
68+
from linkedin_reply_assistant.app import make_manager, make_pipeline
69+
from linkedin_reply_assistant.extraction.base import ExtractionResult
70+
from linkedin_reply_assistant.pipeline import run_full
71+
from linkedin_reply_assistant.reply_engine.generator import Draft
72+
73+
if not live:
74+
config = ocr_only(config)
75+
pipeline = make_pipeline(config, make_manager(config, demo=not live))
76+
results: list[ExtractionResult] = []
77+
drafts: list[Draft] = []
78+
79+
def on_step(step: str, payload: object) -> None:
80+
if isinstance(payload, tuple):
81+
results.append(payload[0])
82+
elif isinstance(payload, Draft):
83+
drafts.append(payload)
84+
85+
source = ImageFileSource(defaults_file("selftest.png"))
86+
timings = run_full(pipeline, 1, source, SELFTEST_ROI, CancelToken(), on_step)
87+
result = results[0]
88+
print(f"capture {timings.capture_ms:.0f} ms")
89+
print(f"extraction {result.extractor} {timings.extraction_ms:.0f} ms, {result.participant!r}")
90+
problems = []
91+
if result.participant != "Kevin Doyle":
92+
problems.append("extraction did not find the sample conversation")
93+
if not drafts:
94+
problems.append("no draft")
95+
else:
96+
draft = drafts[0]
97+
category = draft.classification.category
98+
print(f"category {category} ({draft.classification.source})")
99+
print(f"backend {draft.result.backend} / {draft.result.model}")
100+
print(f"generation {timings.generation_ms:.0f} ms")
101+
print(f"draft {draft.reply!r}")
102+
if category != "sales_outreach":
103+
problems.append(f"unexpected category {category}")
104+
print("selftest " + ("FAILED: " + "; ".join(problems) if problems else "OK"))
105+
return 1 if problems else 0
106+
107+
108+
def cmd_test_window(sample: str, theme: str, zoom: float) -> int: # pragma: no cover - interactive
109+
from PySide6.QtWidgets import QApplication
110+
111+
from linkedin_reply_assistant.model import load_conversation
112+
from linkedin_reply_assistant.testwindow import CaptureTestWindow
113+
114+
app = QApplication.instance() or QApplication(sys.argv)
115+
window = CaptureTestWindow(
116+
load_conversation(defaults_file(f"samples/{sample}.yaml")), theme, zoom
117+
)
118+
window.show()
119+
return int(app.exec())
120+
121+
122+
def cmd_screenshot(config: Config, config_dir: Path | None, output: Path) -> int:
123+
"""Render the real main window after a demo Capture & Draft (used for the README)."""
124+
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
125+
from PySide6.QtWidgets import QApplication
126+
127+
from linkedin_reply_assistant.app import build_services
128+
from linkedin_reply_assistant.browser_bridge.server import BridgeServer
129+
from linkedin_reply_assistant.shortcuts.base import DisabledShortcuts
130+
from linkedin_reply_assistant.state.settings import Settings
131+
from linkedin_reply_assistant.ui.controller import Controller
132+
from linkedin_reply_assistant.ui.main_window import MainWindow
133+
134+
app = QApplication.instance() or QApplication(sys.argv)
135+
config = replace(
136+
config, app=replace(config.app, extraction=replace(config.app.extraction, mode="ocr"))
137+
)
138+
bridge = BridgeServer(output.parent / ".lra-screenshot.sock")
139+
services = build_services(
140+
config,
141+
config_dir,
142+
demo=True,
143+
image=defaults_file("selftest.png"),
144+
bridge=bridge,
145+
shortcuts=DisabledShortcuts("Global hotkey: Ctrl+Alt+L (example)"),
146+
)
147+
services = replace(services, settings_path=output.parent / ".lra-screenshot-state.yaml")
148+
controller = Controller(services, Settings(roi=SELFTEST_ROI))
149+
window = MainWindow(controller)
150+
window.resize(1400, 780)
151+
window.show()
152+
controller.refresh_health()
153+
controller.select_source()
154+
deadline = time.monotonic() + 30
155+
stage = "select"
156+
while time.monotonic() < deadline:
157+
app.processEvents()
158+
if stage == "select" and controller.source is not None:
159+
controller.capture_and_draft()
160+
stage = "draft"
161+
if stage == "draft" and controller.workflow.draft is not None and window.checks:
162+
break
163+
time.sleep(0.02)
164+
window.refresh_bridge()
165+
app.processEvents()
166+
ok = window.grab().save(str(output), "PNG")
167+
window.close()
168+
for leftover in (output.parent / ".lra-screenshot-state.yaml",):
169+
leftover.unlink(missing_ok=True)
170+
print(f"wrote {output}" if ok else f"cannot write {output}")
171+
return 0 if ok and controller.workflow.draft is not None else 1
172+
173+
37174
def main(argv: Sequence[str] | None = None) -> int:
38175
parser = build_parser()
39176
args = parser.parse_args(argv)
177+
if args.command is None:
178+
parser.print_help()
179+
return 0
40180
try:
181+
config = load_config(args.config_dir)
41182
if args.command == "preflight":
42-
return cmd_preflight(args.config_dir)
183+
return cmd_preflight(config)
184+
if args.command == "selftest":
185+
return cmd_selftest(config, args.live)
186+
if args.command == "screenshot":
187+
return cmd_screenshot(config, args.config_dir, args.output)
188+
if args.command == "test-window": # pragma: no cover - interactive
189+
return cmd_test_window(args.sample, args.theme, args.zoom)
190+
from linkedin_reply_assistant.app import run_gui # pragma: no cover - interactive
191+
192+
return run_gui(config, args.config_dir, args.demo, args.image) # pragma: no cover
43193
except ConfigError as exc:
44194
print(f"configuration error: {exc}", file=sys.stderr)
45195
return 2
46-
parser.print_help()
47-
return 0
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
# Synthetic fixture. No real LinkedIn content.
2+
participant: Anna Keller
3+
expected_category: friendly_connection
4+
language: en
5+
messages:
6+
- {sender: Anna Keller, time: "9:14 AM", direction: incoming, text: "Hi Marcel, thanks for accepting my request! I enjoyed your post about local LLMs on small GPUs. Happy to stay in touch."}
7+
forbidden_reply_patterns: ["not the right person", "\\[Name\\]", "schedule a call"]
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
# Synthetic fixture. No real LinkedIn content.
2+
participant: Julia Hartmann
3+
expected_category: recruiting
4+
rule: recruiting
5+
language: de
6+
messages:
7+
- {sender: Julia Hartmann, time: "14:10", direction: incoming, text: "Hallo Marcel, für eine spannende Stelle als Embedded Entwickler bei einem Mittelständler in Augsburg suche ich Unterstützung. Hätten Sie Interesse an der Position?"}
8+
forbidden_reply_patterns: ["not the right person", "Best regards"]
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
# Synthetic fixture. No real LinkedIn content.
2+
participant: Kevin Doyle
3+
expected_category: sales_outreach
4+
rule: sales_call
5+
language: en
6+
messages:
7+
- {sender: Kevin Doyle, time: "11:45 AM", direction: incoming, text: "Hi Marcel, our platform cuts cloud costs by 40%. Do you have 15 minutes for a quick call this week? I can show you a demo and our pricing."}
8+
forbidden_reply_patterns: ["not the right person", "let's schedule", "send me more", "happy to (jump on|have) a call"]
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
# Synthetic fixture. No real LinkedIn content.
2+
participant: Tom Brandt
3+
expected_category: substantive_professional
4+
language: en
5+
messages:
6+
- {sender: Marcel, time: "10:01 AM", direction: outgoing, text: "Thanks for reading the article."}
7+
- {sender: Tom Brandt, time: "10:20 AM", direction: incoming, text: "In your article you used Qt with QML for the dashboard. Did you see performance problems with many charts on the i.MX8, and how did you solve them?"}
8+
forbidden_reply_patterns: ["not the right person"]
33.9 KB
Loading

0 commit comments

Comments
 (0)