Files
mcde/programs/dtchat
lotherk 4774c2c7d8 dtchat: verify adapter files whose hash arrives at the end (T4.5)
Telegram and WhatsApp learn a document's SHA-256 only when the transfer is
finished, so their file-offer carries none and the digest comes with
file-end.  The UI used to verify only the offer hash, which meant those two
paths wrote the bytes unchecked.  accounts_run now takes the offer's hash
when there is one and the file-end's otherwise, hashes the .part file after
the last chunk and renames only on a match; a mismatch still removes the
part file and reports it in the status line and the transcript.

The fake adapter gained the matching modes: latehash offers without a hash
and sends the right one in file-end, badendhash sends a wrong one there.
tests/file_ui.sh drives all four shapes through the real UI under its own
Xvfb with DTCHAT_TEST_FILE_ACCEPT: files and latehash write the verified
hello world, badhash and badendhash are rejected and leave neither the file
nor a .part.  Measured with the built binaries: four ok, exit 0.

Harness entry DtChat/file_ui added; the full run is 53 ok/0 bad
(make mcde-host exit=0, build/logs/mcde-host-2026-11-17-endhash.log).
2026-11-17 13:08:55 +00:00
..

dtchat adapters -- a guide for authors
======================================

An adapter is a separate process that speaks one network protocol for dtchat.
It reads JSON lines on stdin, writes JSON lines on stdout and may write
anything to stderr (dtchat drains and discards it).  The core and the UI never
link a protocol library; an adapter can be written in C, C++, Go, Python or
anything that can read and write lines.

The normative contract is docs/reference/dtchat-adapter-protocol.txt (v1,
ipc=1).  This file is the short version and a skeleton.

1. Start and handshake
----------------------

dtchat starts the process as

    PATH --stdio

with three pipes.  Within 10 seconds the adapter must send one line:

    {"type":"hello","ipc":1,"protocol":"irc","version":"1.0",
     "caps":["text","channels","typing","sasl","tls"],
     "settings":[ ... ]}

`ipc` must be 1 and `protocol` is the protocol name.  `settings` describes the
account form; each entry has `key`, `label`, `type` (`text`, `secret`, `bool`,
`int`, `choice`, `info`, `button`), optional `default`, `required`, `help`,
`choices` and `action`.  `secret` values are stored in secrets.json, never in
the account file, and the UI shows only `*`.

Then dtchat sends:

    {"type":"configure","account":"name","settings":{...},"secrets":{...}}
    {"type":"connect"}

Answer with a state and then events:

    {"type":"state","state":"connecting"}
    {"type":"state","state":"online","detail":"server"}

`online` resets the restart backoff.

2. Commands (core -> adapter)
-----------------------------

    {"type":"send","conv":"#cde","text":"hello","client_id":"c1"}
    {"type":"join","conv":"#cde"}
    {"type":"answer","id":7,"value":"12345"}
    {"type":"disconnect"}
    {"type":"set_presence","show":"online","status":"..."}   (optional)
    {"type":"typing","conv":"#cde","on":true}                (optional)

`answer` replies to a request; `value` is a string or null for cancel.
`disconnect` means: say goodbye and exit.

3. Events (adapter -> core)
---------------------------

    {"type":"conversation","conv":"#cde","kind":"channel","title":"#cde"}
    {"type":"message","conv":"#cde","id":"m1","ts":...,
     "from":"alice","self":false,"kind":"text","text":"hi"}
    {"type":"sent","conv":"#cde","client_id":"c1","ts":...}
    {"type":"presence","buddy":"alice","show":"online","status":"brb"}
    {"type":"roster","conv":"#cde","contact":{"id":"alice","name":"Alice",
     "mode":"@"}}
    {"type":"typing","conv":"#cde","who":"alice","on":true}
    {"type":"log","level":"warn","text":"..."}
    {"type":"error","code":"auth","text":"Password rejected","fatal":false}
    {"type":"bye","reason":"requested"}

`kind` in a message is `text`, `action`, `notice` or `system`.  `fatal:true`
and `bye` mean: do not restart.  Any other exit is a crash; dtchat restarts
after 2, 4, 8 ... 60 seconds (reset by `online`).

4. Asking the person
--------------------

    {"type":"request","id":7,"kind":"code","title":"Telegram",
     "prompt":"Code from the app","secret":true}
    {"type":"request","id":8,"kind":"qr","title":"WhatsApp","hint":"...",
     "qr":{"width":33,"height":33,"data":"<base64, 1 byte per module>"}}

`kind` is `code`, `password`, `notice`, `qr` or `confirm`.  The answer comes
back as `{"type":"answer","id":7,"value":"..."}` (null = cancel).

5. Security
-----------

- Secrets arrive only in `configure`; never write them to stdout, stderr or
  a file of your own.
- Never run a shell from the adapter for a user-controlled string.
- dtchat starts adapters only from its adapter directory (plus an explicit
  path in tests); the adapter is a separate process and may crash without
  taking the UI down.
- A line over 1 MiB, a NUL or invalid JSON ends the process; keep stdout to
  one object per line.

6. Testing
----------

- lib/libDtChat/fake_adapter.c is a minimal adapter (`normal`, `crash`,
  `garbage` modes).
- lib/libDtChat/test_adapter.c starts it with dc_adapter_start() and checks
  the handshake, send/message, join/answer, stop/bye and the restart backoff.
- `tools/mcde-tests.sh` runs the tests; `make mcde-host` builds them.
- For a new adapter, add a `--selftest` that feeds hello/configure/connect
  through pipes and checks the answers without a network, then a fake server
  test for the protocol itself.

7. Skeleton (Python, for a first probe)
---------------------------------------

    #!/usr/bin/env python3
    import json, sys

    def send(obj):
        sys.stdout.write(json.dumps(obj) + "\n")
        sys.stdout.flush()

    send({"type":"hello","ipc":1,"protocol":"demo","version":"0.1",
          "caps":["text"],
          "settings":[{"key":"nick","label":"Nickname","type":"text",
                       "default":"you"}]})
    nick = "you"
    for line in sys.stdin:
        cmd = json.loads(line)
        t = cmd.get("type")
        if t == "configure":
            nick = (cmd.get("settings") or {}).get("nick", nick)
        elif t == "connect":
            send({"type":"state","state":"online"})
            send({"type":"conversation","conv":"lobby","kind":"channel",
                  "title":"Lobby"})
        elif t == "send":
            send({"type":"sent","conv":cmd["conv"],
                  "client_id":cmd.get("client_id")})
            send({"type":"message","conv":cmd["conv"],"from":"echo",
                  "kind":"text","text":cmd["text"]})
        elif t == "disconnect":
            send({"type":"bye","reason":"requested"})
            sys.exit(0)

Save it, `chmod +x`, and start it with a test adapter path; the UI and the
headless mode will show the lobby and echo your messages.

<!-- License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree. -->